Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.references.coverage.examples

Requirements index · View definition

evidence Valid

Requirement

Every Cargo example target, each .rs file directly under the package’s examples/ directory, each examples/<name>/main.rs, and each [[example]] path in Cargo.toml, MUST {cite} a named example of the book under cite requirements.examples.definition in a comment in that file. An example target without one MUST be a validation error naming the file.

Rationale

I found no gaps.

Obligations

  1. Every Cargo example target must {cite} a named example of the book, in a comment in that file. A target is any of three things:
    • a .rs file directly under examples/;
    • an examples/<name>/main.rs;
    • an [[example]] path in Cargo.toml.
  2. A target without such a cite must be a validation error naming the file.

Code

  • src/rust_coverage.rs#fn[cargo_examples] finds the targets among the discovered files.
    • [name] under examples/ counts if it has an rs extension.
    • [_, main] counts if the file is main.rs.
    • Each [[example]] path from Cargo.toml counts if it is a discovered file.
    • It de-duplicates the targets in a BTreeSet.
  • src/rust_coverage.rs#fn[validate_cargo_examples] runs for each target.
    • It looks for a reference in that file with kind Cite whose name resolves to a definition of kind Example. A cite of a requirement therefore does not count.
    • If none exists, it pushes the error "<path>: Cargo example does not {cite} a named example of the book". display_path makes the path relative to the root, so the error names the file.
  • src/evidence.rs#fn[inspect_repository_with_progress] calls validate_cargo_examples. It passes the discovered files, the definitions and the collected references, so the check is part of validation.
  • The “in a comment” condition is handled by src/evidence.rs#fn[file_references]. It keeps only references inside reference contexts and is implemented under requirements.references.reference_contexts. validate_cargo_examples therefore sees only comment cites.
  • The code does not behave in any way the text leaves unspecified. An unparseable Cargo.toml is silently ignored, which is not a gap. Untracked files are not discovered, so they are not targets.

Tests

  • src/rust_coverage.rs#mod[tests]/fn[cargo_examples_must_cite_a_book_example] runs validate_cargo_examples over four kinds of file.
    • A direct .rs example that cites a book example produces no error.
    • A direct .rs example that cites only a requirement produces an error.
    • An examples/demo/main.rs with no cite produces an error.
    • An [[example]] path (extra/listed.rs) with no cite produces an error.
    • It asserts the exact error text naming each file.
  • tests/coverage.rs#fn[an_untracked_example_is_not_a_target] runs validate_repository end to end. It confirms that a tracked example without a cite yields the file-naming error.

Both the obligation to cite and the error obligation are implemented and tested.

Inputs

Implementation

Input 3: outline src/rust_coverage.rs fn[cargo_examples]
/// The package's Cargo example targets among `files`, the sources reference
/// discovery considers: each `.rs` file directly under `examples/`, each
/// `examples/<name>/main.rs`, and each `[[example]]` path.
// {impl}`requirements.references.coverage.examples`
pub(crate) fn cargo_examples(root: &Path, files: &[PathBuf]) -> Vec<PathBuf> {
    let mut targets = std::collections::BTreeSet::new();
    let examples = root.join("examples");
    for file in files {
        let Ok(relative) = file.strip_prefix(&examples) else {
            continue;
        };
        let parts: Vec<_> = relative.iter().collect();
        let target = match parts.as_slice() {
            [name] => Path::new(name)
                .extension()
                .is_some_and(|extension| extension == "rs"),
            [_, main] => *main == "main.rs",
            _ => false,
        };
        if target {
            targets.insert(file.clone());
        }
    }
    let manifest = fs::read_to_string(root.join("Cargo.toml"))
        .ok()
        .and_then(|text| text.parse::<toml::Table>().ok());
    for example in manifest
        .as_ref()
        .and_then(|manifest| manifest.get("example"))
        .and_then(toml::Value::as_array)
        .into_iter()
        .flatten()
    {
        if let Some(path) = example.get("path").and_then(toml::Value::as_str) {
            let path = root.join(path);
            let path = fs::canonicalize(&path).unwrap_or(path);
            if files.contains(&path) {
                targets.insert(path);
            }
        }
    }
    targets.into_iter().collect()
}
Input 4: outline src/rust_coverage.rs fn[validate_cargo_examples]
/// Reports each Cargo example target that does not `{cite}` a named example
/// of the book.
// {impl}`requirements.references.coverage.examples`
pub(crate) fn validate_cargo_examples(
    root: &Path,
    files: &[PathBuf],
    definitions: &BTreeMap<String, Declaration>,
    references: &[crate::evidence::SourceReference],
    errors: &mut Vec<String>,
) {
    for target in cargo_examples(root, files) {
        let cites_example = references.iter().any(|reference| {
            reference.file == target
                && reference.kind == crate::ReferenceKind::Cite
                && definitions
                    .get(&reference.name)
                    .is_some_and(|d| d.kind == crate::DefinitionKind::Example)
        });
        if !cites_example {
            errors.push(format!(
                "{}: Cargo example does not {{cite}} a named example of the book",
                display_path(root, &target)
            ));
        }
    }
}

Tests

Input 5: outline src/rust_coverage.rs mod[tests]/fn[cargo_examples_must_cite_a_book_example]
    // {test}`requirements.references.coverage.examples`
    #[test]
    fn cargo_examples_must_cite_a_book_example() {
        let project = TempDir::new().unwrap();
        let root = project.path();
        fs::create_dir_all(root.join("examples/demo")).unwrap();
        fs::create_dir_all(root.join("extra")).unwrap();
        fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = 'x'\n\n[[example]]\nname = 'listed'\npath = 'extra/listed.rs'\n",
        )
        .unwrap();
        fs::write(
            root.join("examples/cites.rs"),
            "// {cite}`requirements.case`\nfn main() {}\n",
        )
        .unwrap();
        fs::write(
            root.join("examples/requirement.rs"),
            "// {cite}`requirements.example`\nfn main() {}\n",
        )
        .unwrap();
        fs::write(root.join("examples/demo/main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join("extra/listed.rs"), "fn main() {}\n").unwrap();
        let root = fs::canonicalize(root).unwrap();
        let mut definitions = definitions();
        definitions.insert(
            "requirements.case".to_owned(),
            Declaration {
                kind: DefinitionKind::Example,
                ..definitions["requirements.example"].clone()
            },
        );
        let mut found = Vec::new();
        let references = crate::evidence::collect_references(&root, &mut found);
        let mut errors = Vec::new();
        let files = crate::evidence::discovered_files(&root, &mut found);
        super::validate_cargo_examples(&root, &files, &definitions, &references, &mut errors);
        errors.sort();
        // A citation of a requirement, rather than an example, is not enough.
        assert_eq!(
            errors,
            [
                "examples/demo/main.rs: Cargo example does not {cite} a named example of the book",
                "examples/requirement.rs: Cargo example does not {cite} a named example of the book",
                "extra/listed.rs: Cargo example does not {cite} a named example of the book",
            ]
        );
    }
Input 6: outline tests/coverage.rs fn[an_untracked_example_is_not_a_target]
// {test}`requirements.references.coverage.examples`
#[test]
fn an_untracked_example_is_not_a_target() {
    let temp = project();
    let root = temp.path();
    fs::create_dir_all(root.join("examples")).unwrap();
    fs::write(
        root.join("md/rules.md"),
        ":::{req} check\nChecking MUST work.\n:::\n\n:::{example} demo\nA demo. {cite}`rules.check`\n:::\n",
    )
    .unwrap();
    fs::write(root.join("examples/tracked.rs"), "fn main() {}\n").unwrap();
    commit(root, "first");
    // Untracked, it is not discovered, so its citation is not found either.
    fs::write(
        root.join("examples/untracked.rs"),
        "// {cite}`rules.demo`\nfn main() {}\n",
    )
    .unwrap();
    let errors = habeas::validate_repository(root).unwrap().errors;
    let examples: Vec<_> = errors
        .iter()
        .filter(|error| error.contains("Cargo example"))
        .collect();
    assert_eq!(
        examples,
        ["examples/tracked.rs: Cargo example does not {cite} a named example of the book"]
    );
}

Referenced definitions

Input 2: requirements selection requirements.examples.definition
:::{req} definition
An mdBook chapter MAY define an example with an opening fence of at least three colons immediately followed by `{example} <name>` and a closing colon-only fence of at least the opening length. The full name MUST use the same chapter-derived namespace and valid-name rules as `{req}`. The body MUST include all Markdown between the fences, excluding surrounding whitespace and the header option lines of {cite}`requirements.references.anchors`, and MUST describe a concrete case with expected behavior. An example MUST contain at least one valid `{cite}` or `{test}` reference to a requirement it illustrates; `{cite}` makes the requirement an input to the example's assessment, and `{test}` makes the example an input to the requirement's assessment, under {cite}`requirements.references.roles`. An example MAY use both. An example directive inside a fenced code block MUST remain literal.
:::

Other sources

Input 1: requirements selection requirements.references.coverage.examples
:::{req} coverage.examples
Every Cargo example target, each `.rs` file directly under the package's
`examples/` directory, each `examples/<name>/main.rs`, and each `[[example]]`
`path` in `Cargo.toml`, MUST `{cite}` a named example of the book under
{cite}`requirements.examples.definition` in a comment in that file. An example
target without one MUST be a validation error naming the file.
:::
Input 7: outline src/evidence.rs fn[inspect_repository_with_progress]
// {impl}`requirements.ci.errors`
// {impl}`requirements.examples.evidence`
// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.ci.book_source`
// {impl}`requirements.definitions.declaration`
// {impl}`requirements.references.builtin_definitions`
// {impl}`requirements.ci.determination`
pub(crate) fn inspect_repository_with_progress(
    root: &Path,
    mut progress: impl FnMut(InspectionProgress),
) -> io::Result<RepositoryInspection> {
    let root = fs::canonicalize(root)?;
    progress(InspectionProgress {
        stage: "discovering requirements",
        completed: 0,
        total: None,
    });
    let mut errors = Vec::new();
    if let Err(error) = crate::config::load_workspace_evidence(&root) {
        errors.push(error.to_string());
    }
    let md_root = book_source_dir(&root, &mut errors);
    let definitions = collect_definitions(&root, &md_root, &mut errors);
    let mut discovery_errors = errors.clone();
    // {impl}`requirements.test-coverage.setup.validation`
    // {impl}`requirements.test-coverage.setup.validation.static`
    if let Err(error) = crate::execution_coverage::validate_setup(&root) {
        errors.push(error.to_string());
    }
    // Only the coverage report uses `[coverage]`, so an invalid table is a
    // finding but not a discovery failure, and authoring still proceeds.
    if let Some(error) = crate::config::coverage_error(&root) {
        errors.push(error.to_string());
    }
    let evidence_root = root.join("evidence");
    let listing_errors = errors.len();
    let evidence_files = if evidence_root.is_dir() {
        files_with_extension(&root, &evidence_root, "json", &mut errors)
    } else {
        Vec::new()
    };
    let evidence_listed = errors.len() == listing_errors;
    let mut present = BTreeSet::new();
    let outlines = OutlineCache::default();
    // Citation reviews are validated against their source items below.
    let (review_files, ordinary_files): (Vec<_>, Vec<_>) = evidence_files
        .iter()
        .partition(|file| crate::citations::is_review_path(&evidence_root, file));
    let review_files: Vec<PathBuf> = review_files.into_iter().cloned().collect();
    // Site reviews are validated against the sites of their requirements.
    // {impl}`requirements.ci.orphans`
    let (site_files, ordinary_files): (Vec<_>, Vec<_>) = ordinary_files
        .into_iter()
        .partition(|file| crate::sites::is_review_path(&evidence_root, file));
    let site_files: Vec<PathBuf> = site_files.into_iter().cloned().collect();

    // {impl}`requirements.ci.orphans`
    for (completed, file) in ordinary_files.iter().enumerate() {
        progress(InspectionProgress {
            stage: "evidence files",
            completed,
            total: Some(ordinary_files.len()),
        });
        let relative = file
            .strip_prefix(&evidence_root)
            .expect("evidence file is inside evidence directory");
        let label = display_path(&root, file);
        let name = if relative.components().count() == 1 {
            relative
                .file_name()
                .and_then(|part| part.to_str())
                .and_then(|part| part.strip_suffix(".json"))
        } else {
            None
        };
        let expected = name
            .and_then(|name| definitions.get(name))
            .filter(|d| d.kind != DefinitionKind::Term);

        if let Some(name) = name.filter(|_| expected.is_some()) {
            present.insert(name.to_owned());
        } else {
            errors.push(format!("{label}: no matching requirement or example"));
        }
        validate_evidence_file(&root, file, expected, &definitions, &outlines, &mut errors);
    }
    progress(InspectionProgress {
        stage: "evidence files",
        completed: ordinary_files.len(),
        total: Some(ordinary_files.len()),
    });

    // {impl}`requirements.ci.coverage`
    // Missing evidence is reported as a validation error; inspection never
    // starts authoring.
    // {impl}`requirements.authoring.deterministic_validation`
    for (name, definition) in &definitions {
        if definition.kind != DefinitionKind::Term && !present.contains(name) {
            errors.push(format!(
                "evidence/{name}.json: missing for {} at {}",
                definition.kind.noun(),
                definition.source
            ));
        }
    }

    // Unreadable reference sources are discovery failures: a batch must not
    // treat a partial scan as complete.
    let scanned = errors.len();
    progress(InspectionProgress {
        stage: "discovering source references",
        completed: 0,
        total: None,
    });
    let files = discovered_files(&root, &mut errors);
    let references = collect_references_with_progress(&root, &files, &mut errors, &mut progress);
    discovery_errors.extend(errors[scanned..].iter().cloned());
    validate_committed_credentials(&root, &mut errors);
    // {impl}`requirements.references.distributed`
    let sites = crate::sites::discover(
        &root,
        &definitions,
        &files,
        &outlines,
        &mut errors,
        &mut discovery_errors,
    );
    validate_references(
        &root,
        &definitions,
        &references,
        &sites,
        &outlines,
        &mut errors,
        &mut progress,
    );
    crate::citations::validate(
        &root,
        &definitions,
        &references,
        &outlines,
        &review_files,
        &mut errors,
        &mut progress,
    );
    crate::sites::validate(
        &root,
        &definitions,
        &references,
        &sites,
        &outlines,
        &site_files,
        &mut errors,
        &mut progress,
    );
    crate::rust_coverage::validate_cargo_examples(
        &root,
        &files,
        &definitions,
        &references,
        &mut errors,
    );
    // An item an evidence record or review read is covered.
    // {impl}`requirements.references.rust_item_coverage`
    let reads = crate::rust_coverage::EvidenceReads::load(&evidence_files);
    let uncovered = crate::rust_coverage::validate_rust_functions(
        &root,
        &files,
        &definitions,
        &reads,
        &mut errors,
        &mut discovery_errors,
        &mut progress,
    );

    let examples = definitions
        .values()
        .filter(|definition| definition.kind == DefinitionKind::Example)
        .count();
    let requirements = definitions
        .values()
        .filter(|definition| definition.kind == DefinitionKind::Requirement)
        .count();
    Ok(RepositoryInspection {
        root: root.clone(),
        report: EvidenceReport {
            requirements,
            examples,
            evidence_files: evidence_files.len(),
            errors,
        },
        definitions,
        references,
        sites,
        uncovered,
        evidence_files,
        evidence_listed,
        discovery_errors,
    })
}
Input 8: outline src/evidence.rs fn[collect_references_with_progress]
// {impl}`requirements.ci.errors`
pub(crate) fn collect_references_with_progress(
    root: &Path,
    files: &[PathBuf],
    errors: &mut Vec<String>,
    progress: &mut impl FnMut(InspectionProgress),
) -> Vec<SourceReference> {
    // Book configuration errors are reported by inspection itself.
    let md_root = book_source_dir(root, &mut Vec::new());

    let mut references = Vec::new();
    for (completed, file) in files.iter().enumerate() {
        progress(InspectionProgress {
            stage: "reference source files",
            completed,
            total: Some(files.len()),
        });
        let content = match fs::read_to_string(file) {
            Ok(content) => content,
            Err(error) if error.kind() == io::ErrorKind::InvalidData => continue,
            Err(error) => {
                errors.push(format!(
                    "{}: cannot read reference source: {error}",
                    display_path(root, file)
                ));
                continue;
            }
        };
        if content.contains('\0') {
            continue;
        }
        references.extend(file_references(file, &content, file.starts_with(&md_root)));
    }
    progress(InspectionProgress {
        stage: "reference source files",
        completed: files.len(),
        total: Some(files.len()),
    });
    references
}
Input 9: outline src/evidence.rs fn[file_references]
// {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
}