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.refactor.reference_digest

Requirements index · View definition

evidence Valid

Requirement

A record’s references digest MUST be rewritten only if the mapped-back current reference set of its subject, under cite requirements.ci.reference_set, has the recorded digest.

Rationale

I found no gaps. The one obligation is that a record’s references digest is rewritten only if the mapped-back current reference set of its subject, under requirements.ci.reference_set, has the recorded digest.

Implementation

  • src/refactor.rs#fn[rewrite_record] (marked {impl}) makes the decision for definition records.
    • It reads the recorded references string and calls states.digests(&new, name), which returns the current digest and the mapped-back digest.
    • It rewrites value["references"] to the current digest only when back == recorded.
    • When back != recorded, it pushes the failure “the reference set of {new} changed”, which yields Outcome::Unchanged and leaves the record untouched.
    • If the name is unchanged and current == back, nothing was mapped, so it neither rewrites nor fails. That is consistent with “only if”.
    • If digests returns None (no definition), it makes no rewrite.
  • src/refactor.rs#impl[States]/fn[digests] (marked {impl}) computes the mapped-back reference set.
    • It takes reference_set_entries over references_back and outlines_back for the old name, and node_back maps each non-anchor entry’s file and item back to the old address.
    • Anchors are already mapped back in definitions_back, which States::compute builds via address_back. It also reverts reference names and commentary through name_back and text_back.
    • digest_entries then encodes and hashes the entries; the encoding and the entry rules belong to requirements.ci.reference_set (not reassessed here).
    • The same entry rules apply to the current-state digest.

Reachability: both helpers are reached from rewrite_record, and digests also carries its own {impl}.

Tests, all carrying {test} references to the subject in tests/refactor.rs

  • a_moved_function_keeps_its_evidence_current covers the positive case. After the move, the digest is rewritten, errors(root) is empty, and a second run changes 0 records.
  • a_moved_file_rewrites_anchors_and_paths covers an anchor mapped back after a file move, with errors(root) empty afterwards.
  • a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite covers the negative case for a renamed requirement. An extra {impl} makes the mapped-back set differ from the recorded digest, so the record is reported as “the reference set of core.load changed” and its bytes are unchanged.
  • a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved covers the negative case for a record with only a reference-set change, with the digest not rewritten and the file unchanged.

I found no unspecified behavior in the implementation beyond what the text covers.

Inputs

Implementation

Input 3: outline src/refactor.rs impl[States]/fn[digests]
    /// The post state's reference-set digest of a current definition, and
    /// the mapped-back digest of its old name.
    // {impl}`requirements.refactor.reference_digest`
    fn digests(&self, new: &str, old: &str) -> io::Result<Option<(String, String)>> {
        let (Some(post), Some(back)) = (
            self.definitions_post.get(new),
            self.definitions_back.get(old),
        ) else {
            return Ok(None);
        };
        let sites = crate::evidence::definition_sites(
            &self.root,
            new,
            post,
            &self.files,
            &self.outlines_post,
        )?;
        let current = crate::evidence::reference_set_digest(
            &self.root,
            &self.outlines_post,
            new,
            post,
            &self.references_post,
            &sites,
        );
        let mut entries = crate::evidence::reference_set_entries(
            &self.root,
            &self.outlines_back,
            old,
            back,
            &self.references_back,
            &sites,
        );
        for entry in &mut entries {
            if entry.origin != "anchor"
                && let Some((file, item)) = self.mappings.node_back(&entry.file, &entry.item)
            {
                entry.file = file;
                entry.item = item;
            }
        }
        Ok(Some((current, crate::evidence::digest_entries(entries))))
    }
Input 4: outline src/refactor.rs fn[rewrite_record]
/// Decides one record under the mappings.
// {impl}`requirements.refactor.whole_record`
// {impl}`requirements.refactor.subject_text`
// {impl}`requirements.refactor.record_fields`
// {impl}`requirements.refactor.reference_digest`
fn rewrite_record(states: &States, path: &str, record: &Value) -> io::Result<Outcome> {
    let mappings = &states.mappings;
    let Some(kind) = record_kind(path) else {
        return Ok(Outcome::Unaffected);
    };
    let mut value = record.clone();
    let mut changed = false;
    let mut failures = Vec::new();
    let new_path = match &kind {
        RecordKind::Definition(name) => {
            let new = mappings.name(name).unwrap_or_else(|| name.clone());
            let field = if record.get("example").is_some() {
                "example"
            } else {
                "requirement"
            };
            let body = |definitions: &BTreeMap<String, Declaration>, name: &str| {
                definitions
                    .get(name)
                    .map(|definition| definition.text.clone())
            };
            if new != *name
                || body(&states.definitions, name) != body(&states.definitions_post, &new)
            {
                match (
                    body(&states.definitions_back, name),
                    body(&states.definitions_post, &new),
                ) {
                    (Some(back), Some(current))
                        if Some(back.as_str()) == record[field].as_str() =>
                    {
                        value[field] = Value::String(current);
                        changed = true;
                    }
                    (_, None) => {
                        failures.push(format!("{new}: no current definition"));
                        changed = true;
                    }
                    _ => {
                        failures.push(format!("{field} text of {new} changed"));
                        changed = true;
                    }
                }
            }
            if let Some(recorded) = record.get("references").and_then(Value::as_str)
                && let Some((current, back)) = states.digests(&new, name)?
                && current != recorded
                && (new != *name || current != back)
            {
                if back == recorded {
                    value["references"] = Value::String(current);
                    changed = true;
                } else {
                    failures.push(format!("the reference set of {new} changed"));
                    changed = true;
                }
            }
            if new != *name {
                changed = true;
            }
            format!("evidence/{new}.json")
        }
        RecordKind::Citation | RecordKind::Site => {
            let file = record
                .get("file")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let item = record
                .get("item")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let (new_file, new_item) = mappings
                .node(file, item)
                .unwrap_or((file.to_owned(), item.to_owned()));
            if (new_file.as_str(), new_item.as_str()) != (file, item) {
                value["file"] = json!(new_file);
                value["item"] = json!(new_item);
                changed = true;
            }
            match &kind {
                RecordKind::Citation => {
                    if let Some(citations) =
                        value.get_mut("citations").and_then(Value::as_array_mut)
                    {
                        for citation in citations {
                            let name = citation["name"].as_str().unwrap_or_default();
                            if let Some(new) = mappings.name(name) {
                                citation["name"] = json!(new);
                                changed = true;
                            }
                            let commentary = citation["commentary"]
                                .as_str()
                                .unwrap_or_default()
                                .to_owned();
                            let (new, edits) =
                                rewrite_source(mappings, Path::new("commentary"), &commentary);
                            if edits > 0 {
                                citation["commentary"] = json!(new);
                                changed = true;
                            }
                        }
                    }
                    // :::{impl} requirements.refactor.equivalence
                    // A citation review validates against the citations its
                    // item currently carries, so a review whose rewritten
                    // citations differ from those would validate differently
                    // after the move; the record is left unchanged instead.
                    // :::
                    if changed && !same_citations(states, &new_file, &new_item, &value) {
                        failures.push(format!(
                            "the citations of {} differ from the recorded ones",
                            address(&new_file, &new_item)
                        ));
                    }
                    crate::citations::review_path(&new_file, &new_item)
                }
                _ => {
                    let requirement = record
                        .get("requirement")
                        .and_then(Value::as_str)
                        .unwrap_or_default();
                    let new = mappings
                        .name(requirement)
                        .unwrap_or_else(|| requirement.to_owned());
                    if new != requirement {
                        value["requirement"] = json!(new);
                        changed = true;
                    }
                    crate::sites::review_path(&new, &new_file, &new_item)
                }
            }
        }
    };
    if let Some(inputs) = value.get_mut("inputs").and_then(Value::as_array_mut) {
        for (index, input) in inputs.iter_mut().enumerate() {
            match rewrite_input(states, input) {
                None => {}
                Some(Ok(new)) => {
                    if new != *input {
                        *input = new;
                        changed = true;
                    }
                }
                Some(Err(error)) => {
                    failures.push(format!("inputs[{index}]: {error}"));
                    changed = true;
                }
            }
        }
    }
    if !changed {
        return Ok(Outcome::Unaffected);
    }
    if !failures.is_empty() {
        return Ok(Outcome::Unchanged(failures.join("; ")));
    }
    let mut mentions = Vec::new();
    if let Some(rationale) = value.get("rationale").and_then(Value::as_str) {
        let (rewritten, found) = rewrite_rationale(mappings, rationale);
        value["rationale"] = Value::String(rewritten);
        mentions = found;
    }
    Ok(Outcome::Changed {
        path: new_path,
        value,
        mentions,
    })
}

Tests

Input 5: outline tests/refactor.rs fn[a_moved_function_keeps_its_evidence_current]
// {test}`requirements.refactor.moved_function`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_function_keeps_its_evidence_current() {
    let temp = project();
    let root = temp.path();
    author(root);
    assert_eq!(errors(root), Vec::<String>::new());
    move_load(root, "");
    let stale = errors(root);
    assert!(
        stale.iter().any(|error| error.contains("fn[load]")),
        "{stale:#?}"
    );
    let unaffected = fs::read(root.join("evidence/rules.check.json")).unwrap();

    let output = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(
        report.contains("Changed 1 records:\n- evidence/rules.load.json\n"),
        "{report}"
    );
    // The other mention of the old file is listed for review.
    assert!(
        report.contains("review the rationale's `src/config.rs`"),
        "{report}"
    );
    // `rules.check` reads no moved node, so it is unaffected and unchanged.
    assert!(!report.contains("rules.check"), "{report}");
    assert_eq!(
        fs::read(root.join("evidence/rules.check.json")).unwrap(),
        unaffected
    );
    assert_eq!(errors(root), Vec::<String>::new());
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.load.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][1]["file"], "src/config/load.rs");
    assert_eq!(
        record["rationale"],
        "`src/config/load.rs#fn[load]` loads it, as `rules.load` asks; `verify` tests it in `src/config.rs`."
    );
    // Running it again changes nothing.
    let again = refactor(
        root,
        &[
            "--map",
            "src/config.rs#fn[load]=src/config/load.rs#fn[load]",
        ],
    );
    assert!(
        stdout(&again).contains("Changed 0 records:"),
        "{}",
        stdout(&again)
    );
}
Input 6: outline tests/refactor.rs fn[a_moved_file_rewrites_anchors_and_paths]
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.paths`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_file_rewrites_anchors_and_paths() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::rename(root.join("data.txt"), root.join("info.txt")).unwrap();
    let output = refactor(root, &["--map", "data.txt=info.txt"]);
    assert!(output.status.success(), "{output:?}");
    let book = fs::read_to_string(root.join("md/rules.md")).unwrap();
    assert!(book.contains(":impl: info.txt\n"), "{book}");
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.check.json")).unwrap())
            .unwrap();
    assert!(
        record["rationale"]
            .as_str()
            .unwrap()
            .starts_with("`info.txt` is checked")
    );
    assert_eq!(errors(root), Vec::<String>::new());
}
Input 7: outline tests/refactor.rs fn[a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite]
  • File: tests/refactor.rs
  • Selector: fn[a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite]
  • Kind: fn
  • tests/refactor.rs:754–786
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_reference_set_changed_beyond_the_mapping_blocks_every_rewrite() {
    let temp = project();
    let root = temp.path();
    author(root);
    move_load_requirement(root, "Configuration MUST load.");
    // A new `{impl}` is not part of the move.
    fs::write(
        root.join("src/config.rs"),
        config_source("").replace(
            "// {impl}`rules.check`\n",
            "// {impl}`rules.check`\n// {impl}`rules.load`\n",
        ),
    )
    .unwrap();
    let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    // Its text and requirements input would be rewritten, but the reference
    // set check fails, so nothing is.
    assert!(
        report.contains("- evidence/rules.load.json: the reference set of core.load changed"),
        "{report}"
    );
    assert!(!report.contains("text of core.load changed"), "{report}");
    assert_eq!(
        fs::read(root.join("evidence/rules.load.json")).unwrap(),
        before
    );
}
Input 8: outline tests/refactor.rs fn[a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved]
  • File: tests/refactor.rs
  • Selector: fn[a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved]
  • Kind: fn
  • tests/refactor.rs:1048–1088
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.command`
#[test]
fn a_changed_reference_set_is_reported_on_a_record_reading_nothing_moved() {
    let temp = project();
    let root = temp.path();
    author(root);
    // `rules.check` records only its glob input, so a move touches only its
    // reference set.
    let path = root.join("evidence/rules.check.json");
    let mut record: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    record["inputs"] = json!([record["inputs"][0]]);
    fs::write(&path, serde_json::to_string_pretty(&record).unwrap()).unwrap();
    let before = fs::read(&path).unwrap();
    // `check` moves, and an extra `{impl}` is added that is not part of it.
    fs::write(
        root.join("src/config.rs"),
        config_source("")
            .replace("// {impl}`rules.check`\nfn check() {}\n\n", "")
            .replace(
                "// {impl}`rules.load`\n",
                "// {impl}`rules.load`\n// {impl}`rules.check`\n",
            ),
    )
    .unwrap();
    fs::write(
        root.join("src/check.rs"),
        "// {impl}`rules.check`\nfn check() {}\n",
    )
    .unwrap();
    let report = stdout(&refactor(
        root,
        &["--map", "src/config.rs#fn[check]=src/check.rs#fn[check]"],
    ));
    assert!(
        report.contains("- evidence/rules.check.json: the reference set of rules.check changed"),
        "{report}"
    );
    assert_eq!(fs::read(&path).unwrap(), before);
}

Referenced definitions

Input 2: requirements selection requirements.ci.reference_set
:::{req} reference_set
A definition's reference set MUST consist of its current incoming `{impl}`, `{test}`, and `{fixme}` edges, except a `{fixme}` inside a site of the definition under {cite}`requirements.references.site_review`, under {cite}`requirements.references.roles` and
{cite}`requirements.references.anchors`: for each edge, its role and the file and
outline selector of the node the reference belongs to under
{cite}`requirements.references.outline_comments`, or of the anchored file or
node, and, for a fenced reference in a source outside the book, the words of
its body under the word rule of {cite}`requirements.references.structural_hash`.
`{cite}` references MUST NOT contribute. The reference-set digest MUST be
the SHA-256 digest of an unambiguous encoding of those entries in sorted order,
so it does not depend on line numbers or on the order references are found.
Authoring MUST record the digest of the reference set it supplied, and
validation MUST recompute it and report a changed reference set as stale
evidence. Adding or removing an `{impl}`, `{test}`, or `{fixme}` reference or anchor,
changing its role, editing its commentary, or moving it to a different node
MUST therefore make the evidence stale even when no recorded input changed; moving a reference within
the node it belongs to MUST NOT.
:::
Input 9: definition requirements.refactor.mapped_back
:::{definition} mapped_back
:phrase: mapped-back

The *mapped-back* form of current text or a current address is the text or
address with each new side of the mappings replaced by its old side.
:::

Other sources

Input 1: requirements selection requirements.refactor.reference_digest
:::{req} reference_digest
A record's `references` digest MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current reference set of its subject,
under {cite}`requirements.ci.reference_set`, has the recorded digest.
:::
Input 10: outline src/refactor.rs impl[States]/fn[compute]
    /// Computes the post and mapped-back states from the current repository.
    // {impl}`requirements.refactor.definition_inputs`
    fn compute(root: &Path, mappings: Mappings) -> io::Result<Self> {
        let definitions = crate::evidence::load_definitions(root)?;
        let mut failures = Vec::new();
        let files = crate::evidence::discovered_files(root, &mut failures);
        let references = crate::evidence::collect_references_with_progress(
            root,
            &files,
            &mut failures,
            &mut |_| {},
        );
        if !failures.is_empty() {
            return Err(io::Error::other(failures.join("\n")));
        }
        let mut sources = files
            .iter()
            .map(|file| display_path(root, file))
            .collect::<BTreeSet<_>>();
        sources.extend(
            definitions
                .values()
                .map(|definition| definition.file.clone()),
        );
        let mut rewritten = BTreeMap::new();
        let mut post = HashMap::new();
        let mut back = HashMap::new();
        for file in &sources {
            let Ok(content) = fs::read_to_string(root.join(file)) else {
                continue;
            };
            let (new, edits) = rewrite_source(&mappings, Path::new(file), &content);
            let reverted = mappings.text_back(&new);
            if reverted != content {
                back.insert(file.clone(), reverted);
            }
            if edits > 0 {
                post.insert(file.clone(), new.clone());
                rewritten.insert(file.clone(), (new, edits));
            }
        }
        let rewrite = |text: &str, file: &str| rewrite_source(&mappings, Path::new(file), text).0;
        let definitions_post = definitions
            .iter()
            .map(|(name, definition)| {
                let mut definition = definition.clone();
                definition.text = rewrite(&definition.text, &definition.file);
                definition.raw_lines = rewrite(&definition.raw_lines.join("\n"), &definition.file)
                    .split('\n')
                    .map(str::to_owned)
                    .collect();
                for anchor in &mut definition.anchors {
                    if let Some(new) = mappings.address(&anchor.label()) {
                        *anchor = Anchor::parse(anchor.kind, &new);
                    }
                }
                (name.clone(), definition)
            })
            .collect::<BTreeMap<_, _>>();
        let definitions_back = definitions_post
            .iter()
            .map(|(name, definition)| {
                let old = mappings.name_back(name).unwrap_or_else(|| name.clone());
                let mut definition = definition.clone();
                definition.text = mappings.text_back(&definition.text);
                definition.raw_lines = definition
                    .raw_lines
                    .iter()
                    .map(|line| mappings.text_back(line))
                    .collect();
                if let Some(opening) = definition.raw_lines.first_mut() {
                    *opening = opening_back(opening, name, &old);
                }
                for anchor in &mut definition.anchors {
                    if let Some(old) = mappings.address_back(&anchor.label()) {
                        *anchor = Anchor::parse(anchor.kind, &old);
                    }
                }
                (old, definition)
            })
            .collect();
        let references_post = references
            .iter()
            .map(|reference| {
                let mut reference = reference.clone();
                if let Some(new) = mappings.name(&reference.name) {
                    reference.name = new;
                }
                if let Some(body) = &mut reference.commentary {
                    *body = rewrite_source(&mappings, Path::new("commentary"), body).0;
                }
                reference
            })
            .collect::<Vec<_>>();
        let references_back = references_post
            .iter()
            .map(|reference| {
                let mut reference = reference.clone();
                if let Some(old) = mappings.name_back(&reference.name) {
                    reference.name = old;
                }
                if let Some(body) = &mut reference.commentary {
                    *body = mappings.text_back(body);
                }
                reference
            })
            .collect();
        Ok(Self {
            root: root.to_owned(),
            mappings,
            files,
            rewritten,
            definitions,
            definitions_post,
            definitions_back,
            references_post,
            references_back,
            outlines_post: OutlineCache::with_overrides(post),
            outlines_back: OutlineCache::with_overrides(back),
        })
    }
Input 11: outline src/evidence.rs fn[reference_set_entries]
/// The entries of a definition's reference set, unsorted, as
/// [`reference_set_digest`] encodes them.
// {impl}`requirements.references.outline_comments`
// {impl}`requirements.ci.reference_set`
pub(crate) fn reference_set_entries<'a>(
    root: &Path,
    outlines: &OutlineCache,
    name: &str,
    definition: &Declaration,
    references: impl IntoIterator<Item = &'a SourceReference>,
    sites: &crate::sites::Sites,
) -> Vec<ReferenceSetEntry> {
    let mut entries = Vec::new();
    for reference in references {
        // A `{fixme}` inside a site of a distributed definition belongs to
        // that site's review instead.
        if reference.name != name
            || crate::sites::in_own_site(root, sites, reference)
            || !reference.is_fixme_edge()
            || !matches!(
                reference.kind,
                ReferenceKind::Impl | ReferenceKind::Test | ReferenceKind::Fixme
            )
        {
            continue;
        }
        let file = display_path(root, &reference.file);
        let parsed = outlines.parse(root, &file);
        let item = match parsed.as_ref() {
            Ok(parsed) if parsed.outline.profile.language.is_some() => {
                let index = parsed.outline.owner_at_line(reference.line);
                parsed.outline.nodes[index].selector.clone()
            }
            // Plain-text files have only a root node; a source that cannot be
            // outlined is reported elsewhere and contributes its whole file.
            _ => String::new(),
        };
        // Commentary in the book is part of the declaration text instead.
        let commentary = reference
            .commentary
            .as_deref()
            .filter(|_| !reference.in_book);
        entries.push(ReferenceSetEntry {
            origin: if commentary.is_some() {
                "fenced-reference"
            } else {
                "reference"
            },
            role: reference.kind.label(),
            file,
            item,
            words: commentary
                .map(|body| body.split_whitespace().map(str::to_owned).collect())
                .unwrap_or_default(),
        });
    }
    for anchor in &definition.anchors {
        entries.push(ReferenceSetEntry {
            origin: "anchor",
            role: anchor.kind.label(),
            file: anchor.file.clone(),
            item: anchor.item.clone(),
            words: Vec::new(),
        });
    }
    entries
}
Input 12: outline src/evidence.rs fn[reference_set_digest]
/// The reference-set digest of a definition: SHA-256 over a length-prefixed
/// encoding of its sorted incoming `{impl}`, `{test}`, and `{fixme}` edges.
/// A reference contributes the selector of the outline node its comment or
/// text belongs to (the root node for plain-text files), so moving it within
/// that node leaves the digest unchanged; an anchor contributes its file and
/// selector as written. `{cite}` references do not contribute. `root` must be
/// canonical, as reference discovery records canonical paths.
// {impl}`requirements.references.outline_comments`
pub(crate) fn reference_set_digest<'a>(
    root: &Path,
    outlines: &OutlineCache,
    name: &str,
    definition: &Declaration,
    references: impl IntoIterator<Item = &'a SourceReference>,
    sites: &crate::sites::Sites,
) -> String {
    digest_entries(reference_set_entries(
        root, outlines, name, definition, references, sites,
    ))
}