requirements.references.builtin_definitions
Requirements index · View definition
Requirement
Habeas MUST provide built-in definitions named
habeas:<name>, available in every project without a declaration. Each built-in MUST have fixed text, which states its obligations and is documented in Habeas’s reference documentation, and MUST state which reference roles may use it. References MUST resolve built-in names alongside project definitions. So that every book stands alone, the book MUST render a reference to a built-in as a badge without a link whose hover text gives the built-in’s full text. Built-ins themselves MUST NOT require or permit definition evidence files and MUST NOT appear as definitions in the requirements index,habeas status, or the missing-evidence check of. Per-source citation reviews under
MAY be required for references to a built-in. A project definition MUST NOT use a full name beginning with
habeas:; validation MUST report one, and the:character already makes such names invalid under. Validation MUST report a reference to a built-in in a role the built-in does not permit, or that breaks the built-in’s stated form.
Rationale
The reviewed tests cover every obligation of requirements.references.builtin_definitions that is assessed here.
- Fixed text and documentation.
src/builtins.rs#mod[tests]/fn[habeas_util_has_its_approved_text_and_permits_inline_or_fenced_citations]checks thathabeas:utilhas its fixed text and thatmd/reference.mdquotes exactly that text.- The same test checks that
habeas:noneandhabeas:otherare not built-ins, thathabeas:utilandhabeas:noneare recognised as built-in-shaped names, and thathabeas:andother:utilare not. src/builtins.rs#mod[tests]/fn[coverage_builtin_uses_the_documented_text_and_only_the_citation_role]does the same forhabeas:coverage. It carries a{test}reference to a different requirement, so it is not reviewed as a test of this one. That is not a gap, because the util tests already exercise the role-check mechanism for this requirement.
- Available without declaration and resolved alongside project definitions.
- The
tests/references.rstests use a project that declares no built-ins. - In
fn[fenced_references_in_comments_and_built_in_rules_are_validated], validhabeas:utilcitations, fenced or inline, raise no errors and count as coverage for the cited function (glue,empty). fn[built_ins_have_no_evidence_index_entry_or_status_and_are_validated_in_the_book]shows a valid fenced citation in the book raises no error next to a project{req}.
- The
- Book rendering.
src/lib.rs#mod[tests]/fn[fenced_references_render_their_badge_and_body_and_built_ins_are_unlinked]asserts the following:- Fenced and inline built-in references render as
<span ... habeas-builtin title="<escaped full text>">. - No
<aappears in the inline badge, andhref="habeasdoes not appear anywhere in the rendered chapter. - Unknown built-ins such as
habeas:noneand unknown project names stay literal.
- Fenced and inline built-in references render as
- No evidence files, index, status or missing-evidence check.
fn[built_ins_have_no_evidence_index_entry_or_status_and_are_validated_in_the_book]asserts the following:- An
evidence/habeas:util.jsonfile is reported. - There is no “missing evidence for habeas:” error.
- The status table and the details contain no
habeas:entry. - No detail page exists for a built-in.
- The requirements index lists
rules.readyand omitshabeas:util.
- An
- Reserved names for project definitions.
fn[project_definitions_cannot_use_reserved_built_in_names]checks that a project{req} habeas:noneproduces the “names beginning with habeas: are reserved” error and does not appear in status. The implementation insrc/evidence.rs#fn[collect_definitions]is generic over definition kinds, so this single case covers all kinds. - Role and form violations.
- Using
{impl}onhabeas:utilis reported both in a book chapter and in source-comment fences, with the message “built-in habeas:util may only be referenced with {cite}”. - Unknown built-in names are reported in inline and fenced forms, in the book and in source.
- An unclosed fenced reference is reported.
src/fenced.rs#mod[tests]/fn[opening_fences_take_a_role_and_one_valid_or_built_in_name]checks the fence form.src/builtins.rsdirectly testsBuiltin::checkfor Cite OK and Impl/Test errors.
- Using
- Authoring inputs. The
src/authoring/inputs.rsandsrc/authoring/mod.rstests check that a cited built-in contributes its fixed text exactly once to the mandatory inputs.
The “MAY” clause on citation reviews imposes nothing to test.
I found no plausible requirement-violating behaviour that these assertions would accept.
Inputs
Implementation
Input 16: outline src/evidence.rs fn[validate_references]
- File:
src/evidence.rs - Selector:
fn[validate_references] - Kind:
fn src/evidence.rs:1414–1685
// {impl}`requirements.references.evidence_coverage`
// {impl}`requirements.references.discovery`
// {impl}`requirements.examples.evidence`
// {impl}`requirements.ci.reference_set`
// {impl}`requirements.ci.errors`
// {impl}`requirements.definitions.references`
// {impl}`requirements.references.anchors`
// {impl}`requirements.references.util`
// {impl}`requirements.ci.outcomes`
// {impl}`requirements.ci.determination`
fn validate_references(
root: &Path,
definitions: &BTreeMap<String, Declaration>,
references: &[SourceReference],
sites: &crate::sites::Sites,
outlines: &OutlineCache,
errors: &mut Vec<String>,
progress: &mut impl FnMut(InspectionProgress),
) {
let mut by_definition: BTreeMap<String, Vec<&SourceReference>> = BTreeMap::new();
for reference in references {
let location = format!("{}:{}", display_path(root, &reference.file), reference.line);
// An unclosed fence has no complete body, so only the checks of its
// name, which comes from the opening line, still run.
// {impl}`requirements.references.roles`
let unclosed = reference.commentary.is_some() && !reference.closed;
if unclosed {
errors.push(format!(
"{location}: fenced {{{}}} reference to {} has no closing fence with at least as many colons within its comment run or file",
reference.kind.label(),
reference.name
));
}
// A `{fixme}` whose form or placement failed is not an edge, but
// whether its name resolves is still checked.
let edge = reference.kind != ReferenceKind::Fixme
|| validate_fixme_form(reference, &location, unclosed, errors);
if reference.name.is_empty() {
continue;
}
// {impl}`requirements.references.builtin_definitions`
if crate::builtins::is_builtin_name(&reference.name) {
match crate::builtins::builtin(&reference.name) {
// Its form problems are already reported.
Some(_) if unclosed || !edge => {}
Some(builtin) => {
if let Err(problem) = builtin.check(reference.kind) {
errors.push(format!("{location}: {problem}"));
}
}
None => errors.push(format!(
"{location}: {{{}}}`{}` has no matching built-in definition",
reference.kind.label(),
reference.name
)),
}
continue;
}
let target = definitions.get(&reference.name);
if reference.kind == ReferenceKind::Term {
if !target.is_some_and(|d| d.kind == DefinitionKind::Term) {
errors.push(format!(
"{}:{}: term {} has no matching named definition",
display_path(root, &reference.file),
reference.line,
reference.name
));
}
continue;
}
if target.is_some_and(|d| d.kind != DefinitionKind::Term) {
// A `{fixme}` inside one of its definition's sites acknowledges a
// gap at that site only, so it is not part of the definition's
// coverage or reference set.
// {impl}`requirements.references.evidence_coverage`
if edge && !unclosed && !crate::sites::in_own_site(root, sites, reference) {
by_definition
.entry(reference.name.clone())
.or_default()
.push(reference);
}
} else {
errors.push(format!(
"{}:{}: {{{}}}`{}` has no matching requirement or example",
display_path(root, &reference.file),
reference.line,
reference.kind.label(),
reference.name
));
}
}
let subjects: Vec<_> = definitions
.iter()
.filter(|(_, definition)| definition.kind != DefinitionKind::Term)
.collect();
for (completed, (name, definition)) in subjects.iter().enumerate() {
progress(InspectionProgress {
stage: "reference coverage",
completed,
total: Some(subjects.len()),
});
let evidence_file = root.join("evidence").join(format!("{name}.json"));
let references = by_definition.remove(*name).unwrap_or_default();
// The acknowledgment body can introduce terminology without requiring
// an input selecting the containing implementation.
// {impl}`requirements.definitions.dependencies`
if let Some(mut record) = fs::read_to_string(&evidence_file)
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| value.as_object().cloned())
{
match fixme_acknowledgments(root, outlines, references.iter().copied()) {
Ok(acknowledgments) => {
record.insert("acknowledgments".to_owned(), Value::Array(acknowledgments));
crate::terms::validate_dependencies(
root,
definitions,
outlines,
&record,
Some(&definition.text),
&display_path(root, &evidence_file),
errors,
);
}
Err(error) => {
errors.push(format!(
"{}: cannot resolve acknowledgments: {error}",
display_path(root, &evidence_file),
));
crate::terms::validate_dependencies(
root,
definitions,
outlines,
&record,
Some(&definition.text),
&display_path(root, &evidence_file),
errors,
);
}
}
}
if definition.kind == DefinitionKind::Example
&& !references
.iter()
.any(|reference| reference.kind == ReferenceKind::Test)
&& !definition
.anchors
.iter()
.any(|anchor| anchor.kind == ReferenceKind::Test)
&& fs::read_to_string(&evidence_file)
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| value.get("determination").and_then(Value::as_bool))
== Some(true)
{
errors.push(format!(
"{}: example {name} has a true determination but no {{test}} reference",
display_path(root, &evidence_file)
));
}
if let Some(entries) = fs::read_to_string(&evidence_file)
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| Judgment::from_value(value.get("determination")?).ok())
.and_then(|judgment| match judgment {
Judgment::Fixme(entries) => Some(entries),
_ => None,
})
{
let fixmes = references
.iter()
.copied()
.filter(|reference| reference.kind == ReferenceKind::Fixme)
.collect::<Vec<_>>();
validate_fixme_entries(
root,
&display_path(root, &evidence_file),
name,
&entries,
&fixmes,
errors,
);
}
// {impl}`requirements.ci.reference_set`
if let Some(recorded) = fs::read_to_string(&evidence_file)
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| {
value
.get("references")
.and_then(Value::as_str)
.filter(|digest| is_sha256_hex(digest))
.map(str::to_owned)
})
&& recorded
!= reference_set_digest(
root,
outlines,
name,
definition,
references.iter().copied(),
sites,
)
{
errors.push(format!(
"{}: reference set changed: {{impl}}, {{test}}, or {{fixme}} references or anchors of {} {name} were added, removed, edited, or moved to another node",
display_path(root, &evidence_file),
definition.kind.noun()
));
}
let inputs = evidence_input_ranges(root, &evidence_file, definitions, outlines);
// Only tests require a source input. Implementation locations and
// acknowledgment bodies remain protected by the reference-set digest.
for reference in references
.into_iter()
.filter(|reference| reference.kind == ReferenceKind::Test)
{
if !inputs.iter().any(|input| {
input.file == reference.file
&& input.line_start <= reference.line
&& reference.line <= input.line_end
}) {
errors.push(format!(
"{}: no input covers {{{}}}`{}` at {}:{}",
display_path(root, &evidence_file),
reference.kind.label(),
name,
display_path(root, &reference.file),
reference.line
));
}
}
// An anchor is an edge to a file's root node or another node, so an
// outline input must select that node or one of its ancestors.
for anchor in &definition.anchors {
match anchor.resolve(root, outlines) {
Ok(target) if anchor.kind == ReferenceKind::Test => {
if !inputs.iter().any(|input| {
input.node.as_ref().is_some_and(|node| {
node.path == target.path && target.nodes.contains(&node.index)
})
}) {
errors.push(format!(
"{}: no input selects {} (lines {}-{}) anchored by :{}: on {} {name}",
display_path(root, &evidence_file),
anchor.label(),
target.line_start,
target.line_end,
anchor.kind.label(),
definition.kind.noun()
));
}
}
Ok(_) => {}
Err(error) => errors.push(format!(
"{}: :{}: anchor {} on {} {name} at {} does not resolve to a readable, permitted file or node: {error}",
display_path(root, &evidence_file),
anchor.kind.label(),
anchor.label(),
definition.kind.noun(),
definition.source
)),
}
}
}
progress(InspectionProgress {
stage: "reference coverage",
completed: subjects.len(),
total: Some(subjects.len()),
});
}
Tests
Input 5: outline src/authoring/inputs.rs mod[tests]/fn[cited_built_ins_contribute_their_text_and_fixmes_in_own_sites_do_not]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[cited_built_ins_contribute_their_text_and_fixmes_in_own_sites_do_not] - Kind:
fn src/authoring/inputs.rs:1626–1704
// {test}`requirements.references.authoring_inputs`
// {test}`requirements.references.builtin_definitions`
// {test}`requirements.references.site_review`
// {test}`requirements.authoring.adaptive`
// {test}`requirements.authoring.fixme_inputs`
#[test]
fn cited_built_ins_contribute_their_text_and_fixmes_in_own_sites_do_not() {
let project = crate::authoring::tests::citing_site_project();
let root = project.path();
let fixme = |issue: &str| {
format!(
" // :::{{fixme}} requirements.rule\n // :github: o/r#{issue}\n // Panics instead of reporting.\n // :::\n"
)
};
let source = crate::sites::tests::SOURCE
.replace(
"fn check_two() {}",
&format!("fn check_two() {{\n{}}}", fixme("1")),
)
.replace(
"fn other() { panic!(\"y\"); }",
&format!("fn other() {{\n{}}}", fixme("2")),
);
fs::write(root.join("src/lib.rs"), &source).unwrap();
let sources = AssessmentSources::prepare(root, "requirements.rule").unwrap();
assert!(sources.has_applicable_fixme);
let own_site = AssessmentSources::prepare_site(
root,
"requirements.rule",
"src/lib.rs",
"fn[check_two]",
)
.unwrap();
assert!(own_site.has_applicable_fixme);
let clean_site = AssessmentSources::prepare_site(
root,
"requirements.rule",
"src/lib.rs",
"fn[check_one]",
)
.unwrap();
assert!(!clean_site.has_applicable_fixme);
assert!(clean_site.model_acknowledgments().is_empty());
let only_site = source.replace(&fixme("2"), "");
fs::write(root.join("src/lib.rs"), only_site).unwrap();
assert!(
!AssessmentSources::prepare(root, "requirements.rule")
.unwrap()
.has_applicable_fixme
);
fs::write(root.join("src/lib.rs"), &source).unwrap();
let mandatory = sources.mandatory_inputs();
let items = mandatory
.iter()
.filter_map(|input| input["item"].as_str())
.collect::<Vec<_>>();
// Only the acknowledgment outside the subject's own sites belongs to
// this assessment, and it contributes no containing source.
assert!(items.is_empty(), "{mandatory:#?}");
let acknowledgments = sources.model_acknowledgments();
assert_eq!(acknowledgments.len(), 1, "{acknowledgments:#?}");
assert_eq!(acknowledgments[0]["item"], "fn[other]");
assert_eq!(acknowledgments[0]["issues"][0]["reference"], "o/r#2");
// A cited built-in contributes its fixed text once, and a cited
// declaration its own declaration.
assert_eq!(
mandatory
.iter()
.filter(|input| input["builtin"] == "habeas:util")
.collect::<Vec<_>>(),
[&builtin_input("habeas:util")]
);
assert!(
mandatory
.iter()
.any(|input| input["requirements"] == "requirements.other"),
"{mandatory:#?}"
);
}
Input 6: outline src/authoring/mod.rs mod[tests]/fn[site_reviews_cite_declarations_go_stale_with_them_and_name_root_sites]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[site_reviews_cite_declarations_go_stale_with_them_and_name_root_sites] - Kind:
fn src/authoring/mod.rs:4668–4781
// {test}`requirements.references.site_review`
// {test}`requirements.references.builtin_definitions`
#[test]
fn site_reviews_cite_declarations_go_stale_with_them_and_name_root_sites() {
let project = citing_site_project();
let root = project.path();
// Records a current review of a site with its mandatory inputs.
let write = |label: &str, queries: &[&str], drop: Option<&str>| {
let subject = AuthoringSubject::parse(label);
let AuthoringSubject::Site {
requirement,
file,
item,
} = &subject
else {
unreachable!()
};
let mut sources = subject.sources(root).unwrap();
let mandatory = sources.mandatory_inputs().to_vec();
sources.record_inputs(&mandatory);
let inputs = sources
.recorded_inputs()
.iter()
.filter(|input| drop.is_none_or(|name| input["requirements"] != name))
.cloned()
.collect::<Vec<_>>();
let path = subject.evidence_path(root);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(
&path,
json!({"requirement": requirement, "file": file, "item": item,
"queries": queries, "applies": true, "fixmes": [],
"determination": true, "rationale": "Fine.", "inputs": inputs})
.to_string(),
)
.unwrap();
(sources, path)
};
let review_errors = |path: &Path| {
let prefix = format!("{}:", crate::evidence::display_path(root, path));
crate::sites::tests::inspect(root)
.0
.into_iter()
.filter(|error| error.starts_with(&prefix))
.collect::<Vec<_>>()
};
// A site review receives each declaration and built-in text its
// requirement cites.
let (sources, two) = write(
"sites:requirements.rule/src/lib.rs#fn[check_two]",
&["checkers"],
None,
);
let mandatory = sources.mandatory_inputs();
assert!(
mandatory
.iter()
.any(|input| input["requirements"] == "requirements.other"
&& input["text"][1] == "Other MUST hold."),
"{mandatory:#?}"
);
assert_eq!(
mandatory
.iter()
.filter(|input| input["builtin"] == "habeas:util")
.count(),
1,
"{mandatory:#?}"
);
assert_eq!(review_errors(&two), Vec::<String>::new());
// A review without a cited declaration is incomplete.
let (_, one) = write(
"sites:requirements.rule/src/lib.rs#fn[check_one]",
&["checkers", "panics"],
Some("requirements.other"),
);
assert!(
review_errors(&one)
.iter()
.any(|error| error
.contains("inputs must include the declaration of requirements.other")),
"{:#?}",
review_errors(&one)
);
// Omitting the selector names the file's root node.
let (_, attributes) = write("sites:requirements.attributes/src/lib.rs", &["inner"], None);
assert!(
attributes.ends_with("evidence/sites/requirements.attributes/src/lib.rs/_root.json"),
"{}",
attributes.display()
);
assert_eq!(review_errors(&attributes), Vec::<String>::new());
// Changing the requirement's or a cited declaration makes the review
// stale.
let chapter = root.join("md/requirements.md");
let original = fs::read_to_string(&chapter).unwrap();
for (old, new) in [
("Other MUST hold.", "Other MUST still hold."),
("Each checker MUST", "Every checker MUST"),
] {
fs::write(&chapter, original.replace(old, new)).unwrap();
assert!(
review_errors(&two)
.iter()
.any(|error| error.contains("input text changed")),
"{new}: {:#?}",
review_errors(&two)
);
}
}
Input 7: outline src/builtins.rs mod[tests]/fn[habeas_util_has_its_approved_text_and_permits_inline_or_fenced_citations]
- File:
src/builtins.rs - Selector:
mod[tests]/fn[habeas_util_has_its_approved_text_and_permits_inline_or_fenced_citations] - Kind:
fn src/builtins.rs:134–168
// {test}`requirements.references.util`
// {test}`requirements.references.builtin_definitions`
#[test]
fn habeas_util_has_its_approved_text_and_permits_inline_or_fenced_citations() {
let util = builtin("habeas:util").unwrap();
assert!(
util.text()
.starts_with("Cite this on an item that serves other code, including code outside")
);
assert!(
util.text()
.ends_with("judges what it does as part of that root.")
);
assert!(util.check(ReferenceKind::Cite).is_ok());
for role in [ReferenceKind::Impl, ReferenceKind::Test] {
assert!(
util.check(role)
.unwrap_err()
.contains("built-in habeas:util may only be referenced with {cite}")
);
}
// The reference documentation quotes the same text.
let documented = quoted_text(
include_str!("../md/reference.md"),
"The built-in `habeas:util` has this text:",
);
assert_eq!(documented, util.text());
// `habeas:none` was removed, so it is an unknown built-in name.
assert!(builtin("habeas:none").is_none());
assert!(builtin("habeas:other").is_none());
assert!(is_builtin_name("habeas:util"));
assert!(is_builtin_name("habeas:none"));
assert!(!is_builtin_name("habeas:"));
assert!(!is_builtin_name("other:util"));
}
Input 8: outline src/fenced.rs mod[tests]/fn[opening_fences_take_a_role_and_one_valid_or_built_in_name]
- File:
src/fenced.rs - Selector:
mod[tests]/fn[opening_fences_take_a_role_and_one_valid_or_built_in_name] - Kind:
fn src/fenced.rs:291–330
// {test}`requirements.references.roles`
// {test}`requirements.ci.identifiers`
// {test}`requirements.references.builtin_definitions`
#[test]
fn opening_fences_take_a_role_and_one_valid_or_built_in_name() {
let role = |name: &str| format!(":::{{{name}}}");
assert_eq!(
opening_fence(&format!("{} requirements.ready", role("impl"))),
Some((ReferenceKind::Impl, "requirements.ready", 3))
);
assert_eq!(
opening_fence("::::{cite} habeas:util"),
Some((ReferenceKind::Cite, "habeas:util", 4))
);
// A syntactically built-in name is recognized so validation can report
// an unknown built-in rather than leaving it literal.
assert_eq!(
opening_fence(&format!("{} habeas:unknown", role("impl"))),
Some((ReferenceKind::Impl, "habeas:unknown", 3))
);
assert_eq!(
opening_fence(&format!(" {} a.b", role("test"))),
Some((ReferenceKind::Test, "a.b", 3))
);
for literal in [
format!(" {} a.b", role("test")),
format!("{}a.b", role("cite")),
format!("{} a b", role("cite")),
format!("{} a..b", role("cite")),
format!("{} .a", role("cite")),
format!("{} a.", role("cite")),
format!("{} a/b", role("impl")),
format!("{} caf\u{e9}.b", role("impl")),
format!("{} other:none", role("cite")),
format!("{} a.b", role("term")),
"::{cite} a.b".to_owned(),
] {
assert_eq!(opening_fence(&literal), None, "{literal}");
}
}
Input 9: outline src/lib.rs mod[tests]/fn[fenced_references_render_their_badge_and_body_and_built_ins_are_unlinked]
- File:
src/lib.rs - Selector:
mod[tests]/fn[fenced_references_render_their_badge_and_body_and_built_ins_are_unlinked] - Kind:
fn src/lib.rs:915–1004
// {test}`requirements.references.book_badges`
// {test}`requirements.references.builtin_definitions`
// {test}`requirements.test-coverage.check.exceptions.anchor`
#[test]
fn fenced_references_render_their_badge_and_body_and_built_ins_are_unlinked() {
let mut book = Book::new();
let content = [
"::::{req} ready\nReady MUST hold.\n\n:::{cite} rules.other\nThe *other* rule.\n:::\n::::\n\n",
":::{req} other\nOther.\n:::\n\n",
":::{cite} habeas:util\nServes its caller.\n:::\n\n",
":::{cite} habeas:coverage\nA substantive coverage explanation.\n:::\n\n",
":::{cite} habeas:none\nRemoved.\n:::\n\n",
"Inline {cite}`habeas:none` stays literal.\n\n",
"Inline {cite}`habeas:util` is a badge.\n\n",
":::{cite} rules.missing\nUnknown.\n:::\n\n",
"```text\n:::{cite} rules.other\n:::\n```\n",
]
.concat();
book.push_item(Chapter::new("Rules", content, "rules.md", Vec::new()));
let root = book_root();
preprocess_book(&mut book, root.path()).unwrap();
let rendered = book.chapters().next().unwrap().content.clone();
// The project reference links to its definition, then its body.
let mut html = String::new();
pulldown_cmark::html::push_html(&mut html, pulldown_cmark::Parser::new(&rendered));
assert!(html.contains("<p>The <em>other</em> rule.</p>"), "{html}");
assert!(html.contains("alt=\"req rules.ready\""), "{html}");
let linked = "<div class=\"habeas-fenced-ref\">\n\n<p><a class=\"habeas-req-badge habeas-req-ref-cite\" href=\"rules.html#habeas-req-rules.other\">";
let start = rendered.find(linked).expect(&rendered);
let after = &rendered[start..];
assert!(
after.find("alt=\"cite rules.other\"").unwrap()
< after.find("The *other* rule.").unwrap(),
"{rendered}"
);
assert!(
!rendered.contains(":::{cite} rules.other\nThe"),
"{rendered}"
);
// The outer requirement still contains it and closes at its own fence.
assert!(!rendered.contains("See evidence"), "{rendered}");
// A built-in has no link; its hover text is its full text.
let util = crate::builtins::builtin("habeas:util").unwrap();
let coverage = crate::builtins::builtin("habeas:coverage").unwrap();
assert!(rendered.contains(&format!(
"<span class=\"habeas-req-badge habeas-req-ref-cite habeas-builtin\" title=\"{}\"><img",
super::escape_html(coverage.text())
)), "{rendered}");
assert!(
rendered.contains(&format!(
"<span class=\"habeas-req-badge habeas-req-ref-cite habeas-builtin\" title=\"{}\"><img",
super::escape_html(util.text())
)),
"{rendered}"
);
let inline = rendered
.split("Inline ")
.find(|part| part.contains(" is a badge."))
.unwrap();
let inline = inline.split(" is a badge.").next().unwrap();
assert!(inline.starts_with(&format!("<span class=\"habeas-req-badge habeas-req-ref-cite habeas-builtin\" title=\"{}\"><img", super::escape_html(util.text()))), "{inline}");
assert!(
inline.contains("habeas:util") && inline.ends_with("</span>"),
"{inline}"
);
assert!(!inline.contains("<a "), "{inline}");
let badge = "<p><span class=\"habeas-req-badge habeas-req-ref-cite habeas-builtin\"";
let fenced = rendered.find(badge).expect(&rendered);
assert!(
rendered[fenced..].find("Serves its caller.").is_some(),
"{rendered}"
);
assert!(!rendered.contains("href=\"habeas"), "{rendered}");
// Invalid forms, unknown names, and code examples remain literal.
assert!(
rendered.contains(":::{cite} habeas:none\nRemoved.\n:::"),
"{rendered}"
);
assert!(rendered.contains("Inline {cite}`habeas:none` stays literal."));
assert!(
rendered.contains(":::{cite} rules.missing\nUnknown.\n:::"),
"{rendered}"
);
assert!(
rendered.contains("```text\n:::{cite} rules.other\n:::\n```"),
"{rendered}"
);
}
Input 10: outline tests/references.rs fn[fenced_references_in_comments_and_built_in_rules_are_validated]
- File:
tests/references.rs - Selector:
fn[fenced_references_in_comments_and_built_in_rules_are_validated] - Kind:
fn tests/references.rs:72–129
// {test}`requirements.references.roles`
// {test}`requirements.references.builtin_definitions`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.procedure`
// {test}`requirements.references.util`
#[test]
fn fenced_references_in_comments_and_built_in_rules_are_validated() {
let temp = project();
let root = temp.path();
let cr = role("cite");
let source = format!(
"// :::{cr} habeas:util\n// Glue that formats output.\n// :::\nfn glue() {{}}\n\n\
// {cr}`habeas:none`\nfn inline() {{}}\n\n\
// :::{cr} habeas:util\n// {cr}`rules.ready`\n// :::\nfn empty() {{}}\n\n\
// :::{im} habeas:util\n// Wrong role.\n// :::\nfn wrong_role() {{}}\n\n\
// :::{cr} habeas:other\n// Unknown.\n// :::\nfn unknown() {{}}\n\n\
// :::{cr} rules.ready\n// never closed\n\n// :::\nfn unclosed() {{}}\n\n\
// :::{cr} habeas:none\n// Formats output.\n// :::\nfn fenced_none() {{}}\n",
im = role("impl"),
);
fs::write(root.join("src/lib.rs"), source).unwrap();
let errors = errors(root);
for expected in [
// `habeas:none` was removed: it is an unknown name in either form.
"src/lib.rs:6: {cite}`habeas:none` has no matching built-in definition",
"src/lib.rs:30: {cite}`habeas:none` has no matching built-in definition",
"src/lib.rs:14: built-in habeas:util may only be referenced with {cite}",
"src/lib.rs:19: {cite}`habeas:other` has no matching built-in definition",
"src/lib.rs:24: fenced {cite} reference to rules.ready has no closing fence",
"src/lib.rs:7: function inline has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
"src/lib.rs:17: function wrong_role has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
"src/lib.rs:22: function unknown has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
"src/lib.rs:28: function unclosed has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
"src/lib.rs:33: function fenced_none has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
] {
assert!(has(&errors, expected), "missing {expected:?}: {errors:#?}");
}
// A fenced citation of habeas:util covers its function, as does an
// inline reference in a fence body.
assert!(!has(&errors, "function glue"), "{errors:#?}");
assert!(!has(&errors, "function empty"), "{errors:#?}");
// Only valid citations other than habeas:util need reviews.
assert!(has(
&errors,
"missing citation review for src/lib.rs fn[empty]"
));
for item in ["glue", "inline", "fenced_none"] {
assert!(
!has(
&errors,
&format!("missing citation review for src/lib.rs fn[{item}]")
),
"{errors:#?}"
);
}
// Built-ins need no evidence.
assert!(!has(&errors, "evidence/habeas:"), "{errors:#?}");
}
Input 11: outline tests/references.rs fn[built_ins_have_no_evidence_index_entry_or_status_and_are_validated_in_the_book]
- File:
tests/references.rs - Selector:
fn[built_ins_have_no_evidence_index_entry_or_status_and_are_validated_in_the_book] - Kind:
fn tests/references.rs:187–243
// {test}`requirements.references.builtin_definitions`
#[test]
fn built_ins_have_no_evidence_index_entry_or_status_and_are_validated_in_the_book() {
let temp = project();
let root = temp.path();
let cr = role("cite");
let chapter = format!(
"# Rules\n\n:::{{req}} ready\nReady.\n:::\n\nSee {cr}`habeas:none`.\n\n:::{im} habeas:util\nWrong role.\n:::\n\n:::{cr} habeas:util\nServes its callers.\n:::\n\n# Index\n\n:::{{requirements-index}}\n:::\n",
im = role("impl"),
);
fs::write(root.join("md/rules.md"), &chapter).unwrap();
// An evidence file for a built-in is not permitted: it is an orphan.
fs::write(
root.join("evidence/habeas:util.json"),
json!({"requirement": "x", "determination": true, "rationale": "x", "inputs": []})
.to_string(),
)
.unwrap();
let errors = errors(root);
for expected in [
// `habeas:none` was removed, so it is an unknown built-in.
"md/rules.md:7: {cite}`habeas:none` has no matching built-in definition",
"md/rules.md:9: built-in habeas:util may only be referenced with {cite}",
] {
assert!(has(&errors, expected), "missing {expected:?}: {errors:#?}");
}
assert!(
has(&errors, "evidence/habeas:util.json"),
"an evidence file for a built-in must be reported: {errors:#?}"
);
// The fenced citation in the book is valid, and no built-in
// needs evidence.
assert!(!has(&errors, "md/rules.md:13"), "{errors:#?}");
assert!(!has(&errors, "missing evidence for habeas:"), "{errors:#?}");
// Built-ins are not definitions in status or the requirements index.
let status = habeas::status_markdown(root, true).unwrap();
let table = &status[..status.find("## ").unwrap()];
assert!(table.contains("`rules.ready` (requirement)"), "{status}");
assert!(!table.contains("habeas:"), "{status}");
assert!(!status.contains("### `habeas:"), "{status}");
let mut book = Book::new();
book.push_item(Chapter::new("Rules", chapter, "rules.md", Vec::new()));
habeas::preprocess_book(&mut book, root).unwrap();
let rendered = book
.chapters()
.map(|chapter| (chapter.name.clone(), chapter.content.clone()))
.collect::<Vec<_>>();
assert!(
!rendered.iter().any(|(name, _)| name.contains("habeas:")),
"no detail page for a built-in: {rendered:#?}"
);
let (_, content) = &rendered[0];
let index = &content[content.find("# Index").unwrap()..];
assert!(index.contains("rules.ready"), "{index}");
assert!(!index.contains("habeas:util"), "{index}");
}
Input 12: outline tests/references.rs fn[project_definitions_cannot_use_reserved_built_in_names]
- File:
tests/references.rs - Selector:
fn[project_definitions_cannot_use_reserved_built_in_names] - Kind:
fn tests/references.rs:245–265
// {test}`requirements.references.builtin_definitions`
#[test]
fn project_definitions_cannot_use_reserved_built_in_names() {
let temp = project();
let root = temp.path();
fs::write(
root.join("md/rules.md"),
":::{req} ready\nReady.\n:::\n\n:::{req} habeas:none\nShadow.\n:::\n",
)
.unwrap();
let errors = errors(root);
assert!(
has(
&errors,
"md/rules.md:5: invalid requirement name \"rules.habeas:none\": names beginning with habeas: are reserved"
),
"{errors:#?}"
);
let status = habeas::status_markdown(root, true).unwrap();
assert!(!status.contains("`habeas:none` (requirement)"), "{status}");
}
Referenced definitions
Input 2: requirements selection requirements.ci.coverage
requirements.ci.coverage:md/requirements/ci.md:3–5
:::{req} coverage
Repository validation MUST check that every requirement defined by a fenced `{req}` directive in a chapter under the configured mdBook source directory has an evidence file named `evidence/<full-requirement-name>.json`, and MUST report each requirement whose evidence file is missing. The full name MUST use the chapter's path-derived namespace followed by the directive name; for example, a directive named `check` in `md/requirements.md` has the full name `requirements.check`.
:::
Input 3: requirements selection requirements.references.citation_review
requirements.references.citation_review:md/requirements/references.md:146–174
:::{req} citation_review
Every source item outside the book that carries at least one `{cite}` reference
other than a citation of `habeas:util` under {cite}`requirements.references.util`
MUST have a citation review: an assessment of that item's citations, recorded at
`evidence/citations/<file>/<selector>.json`, where `<file>` is the item's
project-relative path, `<selector>` is its outline selector with every `/` and
`%` percent-encoded, and the root node uses `_root`. The review MUST use the
prompt defined by {cite}`requirements.authoring.citation_prompt`. For citations
of project requirements and examples, the reviewer MUST assess whether the item
should be re-checked or kept in sync when the cited definition changes, and
whether the reference procedure of
{cite}`requirements.references.procedure` calls for `{impl}` or `{test}` instead.
For citations of built-ins, the reviewer MUST check the permitted reference
roles and forms and any citation-review criteria stated in the built-in's fixed
text, using the item's source and commentary. A permitted citation role alone
MUST NOT suffice when the fixed text states additional criteria. Mandatory inputs,
under {cite}`requirements.authoring.mandatory_inputs`, MUST be the item's outline
node, each cited declaration or built-in text, and the citations' commentary. The record MUST contain the item's file and selector,
its citations by role, name, and commentary, `determination`, `rationale`, and
`inputs`, with determinations under {cite}`requirements.ci.outcomes`. Validation
MUST require a current, accepted review for every such item and report stale,
missing, or orphaned reviews; a review MUST become stale when the item's hash,
a cited declaration, or its citations or their commentary change. Authoring with
`--all` MUST include citation reviews, and `habeas author citations:<file>#<selector>`
MUST author the review of the one item it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>`
names the file's root node. A citation in a requirement or example
declaration is reviewed as part of that definition's own assessment instead.
:::
Input 4: requirements selection requirements.ci.identifiers
requirements.ci.identifiers:md/requirements/ci.md:329–331
:::{req} identifiers
Requirement and reference names MUST have nonempty dot-separated segments containing only ASCII letters, digits, underscores, or hyphens. A `{req}` directive whose full name is invalid, including one whose chapter path gives an invalid namespace, and a role with an invalid name MUST remain literal and MUST NOT define or reference a requirement. For nested chapter paths, a leading `reqs/` and a final `index` or `README` segment MUST be omitted from the requirement namespace.
:::
Other sources
Input 1: requirements selection requirements.references.builtin_definitions
requirements.references.builtin_definitions:md/requirements/references.md:126–144
:::{req} builtin_definitions
Habeas MUST provide built-in definitions named `habeas:<name>`, available in
every project without a declaration. Each built-in MUST have fixed text, which
states its obligations and is documented in Habeas's reference documentation, and
MUST state which reference roles may use it. References MUST resolve built-in
names alongside project definitions. So that every book stands alone, the book
MUST render a reference to a built-in as a badge without a link whose hover text
gives the built-in's full text. Built-ins themselves MUST NOT require or permit
definition evidence files and MUST NOT appear as definitions in the requirements
index, `habeas status`, or the missing-evidence check of
{cite}`requirements.ci.coverage`. Per-source citation reviews under
{cite}`requirements.references.citation_review` MAY be required for references
to a built-in. A project definition
MUST NOT use a full name beginning with `habeas:`; validation MUST report one,
and the `:` character already makes such names invalid under
{cite}`requirements.ci.identifiers`. Validation MUST report a reference to a
built-in in a role the built-in does not permit, or that breaks the built-in's
stated form.
:::
Input 13: outline src/builtins.rs mod[tests]/fn[coverage_builtin_uses_the_documented_text_and_only_the_citation_role]
- File:
src/builtins.rs - Selector:
mod[tests]/fn[coverage_builtin_uses_the_documented_text_and_only_the_citation_role] - Kind:
fn src/builtins.rs:98–132
// {test}`requirements.test-coverage.check.exceptions.anchor`
#[test]
fn coverage_builtin_uses_the_documented_text_and_only_the_citation_role() {
let coverage = builtin("habeas:coverage").unwrap();
assert_eq!(
coverage.text(),
quoted_text(
include_str!("../md/reference.md"),
"The built-in `habeas:coverage` has this text:",
)
);
assert!(coverage.text().contains("difficulty alone"));
assert!(coverage.text().contains("file's 80%"));
assert!(
coverage
.text()
.contains("without conditional build matching")
);
assert!(coverage.check(ReferenceKind::Cite).is_ok());
for kind in [
ReferenceKind::Impl,
ReferenceKind::Test,
ReferenceKind::Fixme,
ReferenceKind::Term,
] {
assert!(coverage.check(kind).is_err());
}
assert_eq!(
BUILTINS
.iter()
.filter(|builtin| builtin.name == "habeas:coverage")
.count(),
1
);
}
Input 14: outline src/builtins.rs impl[Builtin]/fn[check]
- File:
src/builtins.rs - Selector:
impl[Builtin]/fn[check] - Kind:
fn src/builtins.rs:61–77
/// Checks a reference to this built-in, returning the problem when its
/// role is not permitted.
// {cite}`habeas:util`
pub(crate) fn check(&self, kind: ReferenceKind) -> Result<(), String> {
if !self.roles.contains(&kind) {
return Err(format!(
"built-in {} may only be referenced with {}",
self.name,
self.roles
.iter()
.map(|role| format!("{{{}}}", role.label()))
.collect::<Vec<_>>()
.join(" or ")
));
}
Ok(())
}
Input 15: outline src/evidence.rs fn[collect_definitions]
- File:
src/evidence.rs - Selector:
fn[collect_definitions] - Kind:
fn src/evidence.rs:442–593
// {impl}`requirements.examples.definition`
// {impl}`requirements.ci.requirements_inputs`
// {impl}`requirements.ci.errors`
// {impl}`requirements.ci.identifiers`
// {impl}`requirements.definitions.declaration`
fn collect_definitions(
root: &Path,
md_root: &Path,
errors: &mut Vec<String>,
) -> BTreeMap<String, Declaration> {
let mut definitions = BTreeMap::new();
for file in files_with_extension(root, md_root, "md", errors) {
let relative = file
.strip_prefix(md_root)
.expect("chapter file is inside md directory");
if relative == Path::new("SUMMARY.md") {
continue;
}
let label = display_path(root, &file);
let content = match fs::read_to_string(&file) {
Ok(content) => content,
Err(error) => {
errors.push(format!("{label}: cannot read chapter: {error}"));
continue;
}
};
let namespace = chapter_namespace(relative);
let blocks = definition_blocks(&content);
crate::sites::validate_query_placement(&label, &content, &blocks, errors);
for block in &blocks {
let line = content[..block.start]
.bytes()
.filter(|byte| *byte == b'\n')
.count()
+ 1;
let source = format!("{label}:{line}");
let name = full_requirement_name(&namespace, &block.name);
// An invalid name declares nothing, but the checks of the
// declaration's fence, options, and text still run.
let named = if name.starts_with("habeas:") || block.name.starts_with("habeas:") {
errors.push(format!(
"{source}: invalid {} name {name:?}: names beginning with habeas: are reserved for built-in definitions",
block.kind.noun()
));
false
} else if !valid_name(&name) {
errors.push(format!(
"{source}: invalid {} name {name:?}",
block.kind.noun()
));
false
} else {
true
};
if !block.closed {
errors.push(format!(
"{source}: {} {name} is missing a closing colon fence",
block.kind.noun()
));
}
// {impl}`requirements.ci.span`
// {impl}`requirements.ci.requirement_text`
let text = crate::without_options(&content, block.body_start..block.body_end, &blocks)
.trim()
.to_owned();
let mut anchors = Vec::new();
for option in &block.options {
let kind = match (block.kind, option.name.as_str()) {
(DefinitionKind::Requirement, "impl") => ReferenceKind::Impl,
(DefinitionKind::Requirement | DefinitionKind::Example, "test") => {
ReferenceKind::Test
}
_ => {
errors.push(format!(
"{label}:{}: {} {name} has unsupported option :{}:",
option.line,
block.kind.noun(),
option.name
));
continue;
}
};
if option.value.is_empty() {
errors.push(format!(
"{label}:{}: {} {name} has an :{}: option without a file path",
option.line,
block.kind.noun(),
option.name
));
continue;
}
anchors.push(Anchor::parse(kind, &option.value));
}
if text.is_empty() {
errors.push(format!(
"{source}: {} {name} has no text",
block.kind.noun()
));
}
if block.kind == DefinitionKind::Term
&& let Err(error) = crate::terms::declaration(&text)
{
errors.push(format!("{source}: definition {name}: {error}"));
}
if !named {
continue;
}
match definitions.entry(name.clone()) {
Entry::Vacant(slot) => {
let raw_lines =
crate::without_options(&content, block.start..block.end, &blocks)
.lines()
.map(|line| line.strip_suffix('\r').unwrap_or(line).to_owned())
.collect::<Vec<_>>();
let line_count = content[block.start..block.end].lines().count();
slot.insert(Declaration {
kind: block.kind,
text,
source,
file: label.clone(),
line_start: line,
line_end: line + line_count.saturating_sub(1),
raw_lines,
anchors,
});
}
Entry::Occupied(previous) => errors.push(format!(
"{source}: duplicate {} {name}; first declared at {}",
block.kind.noun(),
previous.get().source
)),
}
}
}
for (name, definition) in &definitions {
if definition.kind == DefinitionKind::Example
&& !example_references_requirement(definition, &definitions)
{
errors.push(format!(
"{}: example {name} must reference at least one requirement with {{cite}} or {{test}}",
definition.source
));
}
}
definitions
}
Input 17: outline src/evidence.rs mod[tests]/fn[failed_checks_do_not_hide_later_independent_checks]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[failed_checks_do_not_hide_later_independent_checks] - Kind:
fn src/evidence.rs:2669–2736
// {test}`requirements.ci.errors`
#[test]
fn failed_checks_do_not_hide_later_independent_checks() {
let temp = fixture();
let root = temp.path();
let fixme = "{fixme}`requirements.missing`".to_owned();
fs::create_dir_all(root.join("md/bad dir")).unwrap();
// Invalid and reserved names still have their fence and text checked.
fs::write(root.join("md/bad dir/rules.md"), ":::{req} good\n:::\n").unwrap();
fs::write(
root.join("md/requirements.md"),
format!(
":::{{req}} habeas:none\n:::\n\n:::{{req}} one\nFirst.\n:::\n\nSee {fixme}.\n\n:::{{fixme}} requirements.one\n:::\n"
),
)
.unwrap();
fs::write(
root.join("evidence/requirements.one.json"),
json!({
"requirement": "First.",
"determination": true,
"rationale": "Checked.",
"inputs": [
{"definition": "requirements.missing", "text": [1, 2]},
{"requirements": "requirements.none", "matches": ["requirements.one", "requirements.one", 3], "text": ["x"]},
{"file": "src/gone.rs", "item": "", "hash": "ABC"},
]
})
.to_string(),
)
.unwrap();
let errors = validate_repository(root).unwrap().errors;
let all = errors.join("\n");
for detail in [
"md/bad dir/rules.md:1: invalid requirement name \"bad dir.rules.good\"",
"md/bad dir/rules.md:1: requirement bad dir.rules.good has no text",
"md/requirements.md:1: invalid requirement name \"requirements.habeas:none\": names beginning with habeas: are reserved",
"md/requirements.md:1: requirement requirements.habeas:none has no text",
// Every element of `text` is checked, and the definition is
// still resolved.
"inputs[0]: text[0] must be a string",
"inputs[0]: text[1] must be a string",
"inputs[0]: requirements.missing: no matching named definition",
// Duplicate matches are reported beside a non-string entry, and
// the selection is still resolved.
"inputs[1]: matches[2] must be a string",
"inputs[1]: matches must have distinct definition names",
"inputs[1]: requirements glob \"requirements.none\" matches no requirement",
// A malformed hash does not hide a missing file.
"inputs[2]: hash must be a lowercase hexadecimal SHA-256 digest",
"inputs[2]: cannot open src/gone.rs",
// An inline `{fixme}` in the book is reported for its form, its
// placement, and its unknown name.
"md/requirements.md:8: inline {fixme} reference to requirements.missing must use the fenced form",
"md/requirements.md:8: a named {fixme} to requirements.missing must appear in a source outside the book",
&format!("md/requirements.md:8: {fixme} has no matching requirement or example"),
// A misplaced named `{fixme}` still has its body checked.
"md/requirements.md:10: a named {fixme} to requirements.one must appear in a source outside the book",
"md/requirements.md:10: {fixme} to requirements.one has an empty body",
] {
assert!(all.contains(detail), "missing {detail:?} in:\n{all}");
}
// No failure is reported twice.
let mut unique = errors.clone();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), errors.len(), "{all}");
}