requirements.references.reference_contexts
Requirements index · View definition
Requirement
Each supported language profile MUST define where in its files roles count as references, and SHOULD exclude places that hold code or data rather than prose, such as string literals. In a file with a language outline under
, inline and fenced roles MUST count only within comments as its profile defines them, including doc comments; a role anywhere else, including in a string literal, MUST remain literal. In Markdown, escaped roles and roles in code examples remain literal under
. In a plain-text file, roles MUST count anywhere.
Rationale
Verdict: the tests are adequate. One residual gap is possible: the references-in-comments tests don’t run on the TypeScript, CSS or YAML profiles. I judge that gap too weak to fail the requirement.
Obligations derived from requirements.references.reference_contexts
- In a file with a language outline, inline and fenced roles count only inside comments, doc comments included.
- A role anywhere else, including a string literal, stays literal. This covers a fenced role that spans lines of a string literal.
- In Markdown, escaped roles and roles in code examples stay literal. This is delegated to
requirements.references.discovery. - In a plain-text file, roles count anywhere.
Coverage
src/evidence.rs#mod[tests]/fn[roles_count_only_in_comments_of_outlined_files]callsfile_referencesand asserts the exact names that are found. It covers:- Rust, where a
//comment and a///doc comment count and a role in a string literal does not. - TOML, where a
#comment counts and a role in a string value does not. - Python, where a
#comment counts and a role in a docstring does not. - A fenced role in a Rust
//comment, which counts, against a fenced role spanning lines of a string literal, which does not. - Plain text (
notes.txt), where a role counts anywhere. - Markdown, where a prose role counts and a role in a code fence does not.
- Rust, where a
src/terms.rs#mod[tests]/fn[term_dependencies_of_outlined_sources_come_only_from_comments]repeats the comments-only rule for Rust, Python and TOML. It asserts that only the role in the comment yields a dependency and the role in the string does not.src/refactor/tests.rs#fn[sources_rewrite_references_to_names_and_anchors_to_paths]covers the rewriting side. A role in a Rust string is not rewritten, and a Markdown code block stays literal.- The Markdown escaped-role case is delegated to
requirements.references.discovery. The same test is marked for that requirement, andsrc/evidence.rs#mod[tests]/fn[every_markdown_extension_keeps_escaped_and_code_roles_literal]covers escaped roles directly.
Implementation shape
- I read
reference_contexts,in_reference_contextandfile_referencesto see how profiles feed the rule. - All outlined languages share one path: the byte ranges of the comments in the parsed outline decide where a role counts.
- Comment detection for every profile, including TypeScript, CSS and YAML, is tested separately in
src/outline/tests.rs#fn[comment_runs_follow_the_same_rules_in_every_language].
Residual gap
- No reference-context test runs on the TypeScript, CSS or YAML profiles. Because they share the path above, the three languages that are tested stand in for the rest, so I did not count this as an established gap.
Inputs
Implementation
Input 7: outline src/evidence.rs fn[reference_contexts]
- File:
src/evidence.rs - Selector:
fn[reference_contexts] - Kind:
fn src/evidence.rs:1928–1951
/// The inline and fenced references in one text file, in line order.
/// Where roles count as references in a file's content: the byte ranges of
/// its comments when it has a language outline, or `None` where roles count
/// anywhere: Markdown, which has its own rules, plain text, and a file that
/// cannot be parsed, which is reported elsewhere.
// {impl}`requirements.references.reference_contexts`
pub(crate) fn reference_contexts(
file: &Path,
content: &str,
) -> Option<Vec<std::ops::Range<usize>>> {
if crate::outline::is_markdown_path(file) {
return None;
}
let profile = crate::outline::profile_for_path(file);
profile.language?;
let outline = crate::outline::parse_with(profile, content).ok()?;
Some(
outline
.comments
.iter()
.map(|comment| comment.byte_start..comment.byte_end)
.collect(),
)
}
Input 8: outline src/evidence.rs fn[in_reference_context]
- File:
src/evidence.rs - Selector:
fn[in_reference_context] - Kind:
fn src/evidence.rs:1953–1960
/// Whether a role at byte `start` counts under [`reference_contexts`].
// {impl}`requirements.references.reference_contexts`
pub(crate) fn in_reference_context(
contexts: Option<&[std::ops::Range<usize>]>,
start: usize,
) -> bool {
contexts.is_none_or(|ranges| ranges.iter().any(|range| range.contains(&start)))
}
Input 9: outline src/evidence.rs fn[file_references]
- File:
src/evidence.rs - Selector:
fn[file_references] - Kind:
fn src/evidence.rs:1962–2015
// {impl}`requirements.references.reference_contexts`
fn file_references(file: &Path, content: &str, in_book: bool) -> Vec<SourceReference> {
let markdown = crate::outline::is_markdown_path(file);
let mut references = Vec::new();
let roles = reference_roles(content, markdown);
let contexts = if roles.is_empty() {
None
} else {
reference_contexts(file, content)
};
for role in roles {
if !in_reference_context(contexts.as_deref(), role.start) {
continue;
}
let line = content[..role.start]
.bytes()
.filter(|byte| *byte == b'\n')
.count()
+ 1;
references.push(SourceReference {
name: role.name.to_owned(),
kind: role.kind,
file: file.to_owned(),
line,
commentary: None,
closed: true,
in_book,
in_declaration: false,
});
}
let fences = crate::fenced::source_fences(file, content);
// Declarations are found only where a `{fixme}` needs them.
let declarations = if markdown && fences.iter().any(|f| f.kind == ReferenceKind::Fixme) {
declaration_line_ranges(content)
} else {
Vec::new()
};
for fence in fences {
references.push(SourceReference {
in_declaration: declarations
.iter()
.any(|range| range.0 < fence.line && fence.line < range.1),
name: fence.name,
kind: fence.kind,
file: file.to_owned(),
line: fence.line,
commentary: Some(fence.body),
closed: fence.closed,
in_book,
});
}
references.sort_by_key(|reference| reference.line);
references
}
Tests
Input 4: outline src/evidence.rs mod[tests]/fn[roles_count_only_in_comments_of_outlined_files]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[roles_count_only_in_comments_of_outlined_files] - Kind:
fn src/evidence.rs:2076–2146
// {test}`requirements.references.reference_contexts`
// {test}`requirements.references.discovery`
#[test]
fn roles_count_only_in_comments_of_outlined_files() {
// The role's brace is built at run time, so this source holds none.
let role = |name: &str| format!("{{impl}}`{name}`");
let names = |file: &str, content: String| {
super::file_references(Path::new(file), &content, false)
.into_iter()
.map(|reference| reference.name)
.collect::<Vec<_>>()
};
assert_eq!(
names(
"src/lib.rs",
format!(
"// {}\n/// {}\nfn f() -> &'static str {{ \"{}\" }}\n",
role("a.comment"),
role("a.doc"),
role("a.string")
)
),
["a.comment", "a.doc"]
);
assert_eq!(
names(
"config.toml",
format!("# {}\nkey = \"{}\"\n", role("b.comment"), role("b.string"))
),
["b.comment"]
);
assert_eq!(
names(
"tool.py",
format!(
"# {}\ndef f():\n \"\"\"{}\"\"\"\n",
role("c.comment"),
role("c.docstring")
)
),
["c.comment"]
);
// A fenced role spanning lines of a string literal is literal too.
assert_eq!(
names(
"src/lib.rs",
format!(
"// :::{0}impl}} f.comment\n// Body.\n// :::\nconst S: &str = \"\n:::{0}impl}} f.string\nBody.\n:::\n\";\n",
'{'
)
),
["f.comment"]
);
// Plain text has no comments: roles count anywhere.
assert_eq!(
names("notes.txt", format!("see {}\n", role("d.text"))),
["d.text"]
);
// Markdown keeps its own rules.
assert_eq!(
names(
"md/rules.md",
format!(
"Uses {}.\n\n```text\n{}\n```\n",
role("e.prose"),
role("e.code")
)
),
["e.prose"]
);
}
Input 5: outline src/refactor/tests.rs fn[sources_rewrite_references_to_names_and_anchors_to_paths]
- File:
src/refactor/tests.rs - Selector:
fn[sources_rewrite_references_to_names_and_anchors_to_paths] - Kind:
fn src/refactor/tests.rs:137–187
// {test}`requirements.references.reference_contexts`
// {test}`requirements.refactor.reference_rewrite`
#[test]
fn sources_rewrite_references_to_names_and_anchors_to_paths() {
let map = mappings(&[
("name", "rules.check", "core.check"),
("path", "data.txt", "info.txt"),
]);
let rust = concat!(
"// {impl}`rules.check`\n",
"// {cite}`rules.checker`\n",
"// :::{fixme} rules.check\n// A gap.\n// :::\n",
"fn f() {}\n",
);
let (rewritten, edits) = rewrite_source(&map, Path::new("src/lib.rs"), rust);
assert_eq!(edits, 2);
assert_eq!(
rewritten,
concat!(
"// {impl}`core.check`\n",
"// {cite}`rules.checker`\n",
"// :::{fixme} core.check\n// A gap.\n// :::\n",
"fn f() {}\n",
)
);
// In Markdown, anchors are rewritten too, but not the declaration's name,
// and references in code blocks stay literal.
let markdown = concat!(
":::{req} other\n:impl: data.txt\n:test: data.txt#line@abc\n",
"Uses {term}`rules.check`.\n:::\n\n```text\n{cite}`rules.check`\n```\n",
);
let (rewritten, edits) = rewrite_source(&map, Path::new("md/rules.md"), markdown);
assert_eq!(edits, 3, "{rewritten}");
assert!(rewritten.contains(":impl: info.txt\n:test: info.txt#line@abc\n"));
assert!(rewritten.contains("Uses {term}`core.check`."));
assert!(rewritten.contains("```text\n{cite}`rules.check`\n```"));
// Option-like lines outside a directive's options are literal.
let literal = concat!(
":::{req} other\nBody.\n:impl: data.txt\n:::\n\n",
"```text\n:::{req} shown\n:impl: data.txt\n:::\n```\n",
);
let (rewritten, edits) = rewrite_source(&map, Path::new("md/rules.md"), literal);
assert_eq!((rewritten.as_str(), edits), (literal, 0));
// A role in a string literal is literal text, not a reference to rewrite.
let literal = "const S: &str = \"{impl}`rules.check`\";\n".to_owned();
let (rewritten, edits) = rewrite_source(&map, Path::new("src/lib.rs"), &literal);
assert_eq!((rewritten.as_str(), edits), (literal.as_str(), 0));
// Plain text is not an anchor outside Markdown.
let (_, edits) = rewrite_source(&map, Path::new("notes.txt"), ":impl: data.txt\n");
assert_eq!(edits, 0);
}
Input 6: outline src/terms.rs mod[tests]/fn[term_dependencies_of_outlined_sources_come_only_from_comments]
- File:
src/terms.rs - Selector:
mod[tests]/fn[term_dependencies_of_outlined_sources_come_only_from_comments] - Kind:
fn src/terms.rs:282–325
// {test}`requirements.references.reference_contexts`
// {test}`requirements.definitions.dependencies`
#[test]
fn term_dependencies_of_outlined_sources_come_only_from_comments() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("md")).unwrap();
fs::create_dir_all(root.join("src")).unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
fs::write(
root.join("md/terms.md"),
":::{definition} unit\n:phrase: unit\nA unit.\n:::\n",
)
.unwrap();
let used = "{term}`terms.unit`".to_owned();
let missing = "{term}`terms.missing`".to_owned();
let declarations = crate::evidence::load_definitions(root).unwrap();
let outlines = OutlineCache::default();
for (file, text) in [
(
"src/lib.rs",
format!("// Uses {used}.\nconst NAME: &str = \"{missing}\";\n"),
),
("tool.py", format!("# Uses {used}.\nNAME = \"{missing}\"\n")),
(
"config.toml",
format!("# Uses {used}.\nname = \"{missing}\"\n"),
),
] {
fs::write(root.join(file), text).unwrap();
let record = json!({"inputs": [{"file": file, "item": ""}]});
assert_eq!(
dependencies(
root,
&declarations,
&outlines,
record.as_object().unwrap(),
None
),
Ok(BTreeSet::from(["terms.unit".to_owned()])),
"{file}"
);
}
}
Referenced definitions
Input 2: requirements selection requirements.references.outlines
requirements.references.outlines:md/requirements/references.md:358–378
:::{req} outlines
Habeas MUST parse Rust, Python, TypeScript, CSS, Markdown, TOML, and YAML
sources with pinned tree-sitter grammars, selected by file extension compared
case-insensitively. A source with any syntax error MUST fail to parse, reporting
the line of its first error. Every
other text file MUST use a plain-text profile in which each line that is not
blank is an anonymous outline node of kind `line`. Each supported language MUST
have an outline profile that maps grammar node kinds to short outline kind names
and, for each mapped kind, states whether a node is named, and by which fields
or children, or anonymous. Only mapped kinds MUST appear in the outline; other
nodes MUST be transparent, so their outline descendants appear under the
nearest outline ancestor. A profile MAY attach grammar siblings to an outline
node, such as Rust attributes and doc comments preceding an item, so the outline
tree need not match the grammar tree exactly; attached siblings are part of that
node for its line range and hash. Every file's outline MUST have a root node
for the whole file, independent of language. Source in no other outline node,
such as top-level statements no profile maps, MUST belong to the root node;
profiles MUST NOT invent fallback kinds for it. Comments MUST NOT be outline nodes. Profiles MUST be
documented. Upgrading a grammar or profile MAY change outlines and MUST be
treated as a deliberate change.
:::
Input 3: requirements selection requirements.references.discovery
requirements.references.discovery:md/requirements/references.md:99–112
:::{req} discovery
Habeas MUST find the references of {cite}`requirements.references.roles`
in project source files, where {cite}`requirements.references.reference_contexts`
says they count, and MUST fail with the source file and line if a
name has no matching `{req}` or `{example}` definition. In Markdown, escaped
roles and roles in code examples MUST remain literal. Reference discovery MUST
consider exactly the project sources that source-access policy permits under
{cite}`requirements.authoring.source_tools`: in a Git worktree, files present in
the Git index, including staged new files; outside Git, all project files; in
both cases excluding the project-root `book` and `evidence` directories, `.git`
and `target` directories at any depth, and paths disallowed by
{cite}`requirements.configuration.evidence_paths`. Evidence snapshots and
generated build output MUST therefore not be counted as source references.
:::
Other sources
Input 1: requirements selection requirements.references.reference_contexts
requirements.references.reference_contexts:md/requirements/references.md:114–124
:::{req} reference_contexts
Each supported language profile MUST define where in its files roles count as
references, and SHOULD exclude places that hold code or data rather than prose,
such as string literals. In a file with a language outline under
{cite}`requirements.references.outlines`, inline and fenced roles MUST count
only within comments as its profile defines them, including doc comments; a
role anywhere else, including in a string literal, MUST remain literal. In
Markdown, escaped roles and roles in code examples remain literal under
{cite}`requirements.references.discovery`. In a plain-text file, roles MUST
count anywhere.
:::