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.definition_inputs

Requirements index · View definition

evidence Valid

Requirement

A requirements or definition input MUST be rewritten only if the mapped-back current text of each definition it records equals the recorded text and, for a requirements input, the mapped selection’s current matches are exactly the recorded matches with the mapping applied.

Rationale

I found no gap. I did not read InputSelector::resolve or to_input. I took from rewrite_input that to_input includes the recorded text and matches, which the equality check below relies on.

Obligations

  1. A requirements or definition input is rewritten only if the mapped-back current text of each definition it records equals the recorded text.
  2. For a requirements input, the mapped selection’s current matches must be exactly the recorded matches with the mapping applied.

Code for obligation 1

  • src/refactor.rs#impl[States]/fn[compute] builds definitions_back. For each definition it maps the text and raw lines back with mappings.text_back. It also maps the opening fence’s short name back with opening_back, maps anchors back with address_back, and keys the definition by its old name.
  • src/refactor.rs#fn[rewrite_input] resolves the original selector against definitions_back and turns it into an input with selector.to_input. It rewrites the input only when that result equals the recorded input (&back == input). Otherwise it returns the “no longer selects what it recorded” error.
  • That equality covers the recorded definition text, so it applies to both requirements and definition inputs.

Code for obligation 2

  • rewrite_input resolves the mapped selector (new_selector) against definitions_post. It then requires the current matches to equal the recorded names, mapped with mappings.name and sorted. This applies only to requirements inputs, because definition inputs carry no matches, so is_none_or passes for them.

Reachability and unspecified behavior

  • Everything the code depends on is reached from the {impl} items compute, opening_back and rewrite_input.
  • The affected check returns None for inputs no mapping touches. This is within the scope of rewriting only affected inputs, so it is not unspecified behavior.

Tests

  • tests/refactor.rs#fn[a_term_edited_while_moving_leaves_its_definition_input_stale] covers a definition’s text differing after mapping back. The input is reported stale and the record is left unchanged.
  • tests/refactor.rs#fn[a_moved_requirement_renames_its_references_and_evidence] covers the match-set check. The rules.* glob no longer selects what it recorded, so it is reported stale.
  • tests/refactor.rs#fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it] covers a definition input that is rewritten when its text is unchanged.
  • tests/refactor.rs#fn[a_moved_chapter_rewrites_glob_selections_and_their_matches] covers a requirements input whose matches map exactly, so it is rewritten.
  • src/refactor/tests.rs#fn[mapped_back_text_replaces_whole_new_names_and_paths] and #fn[opening_fences_map_their_short_names_back] test the mapped-back helpers text_back and opening_back.
  • No test mutates the text of a definition inside a requirements input. That case runs through the same &back == input comparison as the definition-input case, so it needs no separate test.

Inputs

Implementation

Input 4: 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 5: outline src/refactor.rs fn[opening_back]
// {impl}`requirements.refactor.definition_inputs`
/// A declaration's opening fence with its short name mapped back from the
/// current full name `new` to `old`.
fn opening_back(opening: &str, new: &str, old: &str) -> String {
    let Some((fence, short)) = opening.rsplit_once(' ') else {
        return opening.to_owned();
    };
    if new == old || !new.ends_with(short) {
        return opening.to_owned();
    }
    let segments = short.split('.').count();
    let parts = old.split('.').collect::<Vec<_>>();
    let old_short = parts[parts.len().saturating_sub(segments)..].join(".");
    format!("{fence} {old_short}")
}
Input 6: outline src/refactor.rs fn[rewrite_input]
/// Rewrites one input, or returns `None` when no mapping affects it.
// {impl}`requirements.refactor.outline_inputs`
// {impl}`requirements.refactor.definition_inputs`
fn rewrite_input(states: &States, input: &Value) -> Option<Result<Value, String>> {
    let mappings = &states.mappings;
    let root = &states.root;
    match InputSelector::from_input(input)? {
        InputSelector::Outline { file, item } => {
            let recorded = input.get("hash").and_then(Value::as_str)?;
            let mapped = mappings.node(&file, &item);
            let (new_file, new_item) = mapped.clone().unwrap_or((file.clone(), item.clone()));
            if mapped.is_none() && !states.rewritten.contains_key(&new_file) {
                return None;
            }
            let back = states.hash(&states.outlines_back, &new_file, &new_item);
            let current = states.hash(&states.outlines_post, &new_file, &new_item);
            Some(match (back, current) {
                (Ok(back), Ok(current)) if back == recorded => {
                    Ok(json!({"file": new_file, "item": new_item, "hash": current}))
                }
                (Err(error), _) | (_, Err(error)) => Err(error),
                _ => Err(format!(
                    "{} no longer has the recorded hash",
                    address(&new_file, &new_item)
                )),
            })
        }
        selector @ (InputSelector::Requirements { .. } | InputSelector::Definition { .. }) => {
            let (new_selector, names) = match &selector {
                InputSelector::Requirements { requirements } => (
                    InputSelector::Requirements {
                        requirements: mappings
                            .selection(requirements)
                            .unwrap_or_else(|| requirements.clone()),
                    },
                    input
                        .get("matches")
                        .and_then(Value::as_array)
                        .into_iter()
                        .flatten()
                        .filter_map(Value::as_str)
                        .map(str::to_owned)
                        .collect::<Vec<_>>(),
                ),
                InputSelector::Definition { definition } => (
                    InputSelector::Definition {
                        definition: mappings
                            .name(definition)
                            .unwrap_or_else(|| definition.clone()),
                    },
                    vec![definition.clone()],
                ),
                InputSelector::Outline { .. } => unreachable!(),
            };
            let affected = new_selector != selector
                || names.iter().any(|name| {
                    let new = mappings.name(name).unwrap_or_else(|| name.clone());
                    mappings.name(name).is_some()
                        || states.definitions.get(name).map(|d| &d.raw_lines)
                            != states.definitions_post.get(&new).map(|d| &d.raw_lines)
                });
            if !affected {
                return None;
            }
            let back = selector
                .resolve(root, &states.definitions_back, &states.outlines_back)
                .map(|resolved| selector.to_input(&resolved));
            let current = new_selector
                .resolve(root, &states.definitions_post, &states.outlines_post)
                .map(|resolved| new_selector.to_input(&resolved));
            Some(match (back, current) {
                (Ok(back), Ok(current))
                    if &back == input && {
                        let mut mapped = names
                            .iter()
                            .map(|name| mappings.name(name).unwrap_or_else(|| name.clone()))
                            .collect::<Vec<_>>();
                        mapped.sort();
                        current
                            .get("matches")
                            .is_none_or(|matches| *matches == json!(mapped))
                    } =>
                {
                    Ok(current)
                }
                (_, Err(error)) => Err(error),
                _ => Err(format!(
                    "{} no longer selects what it recorded",
                    match &new_selector {
                        InputSelector::Requirements { requirements } => requirements,
                        InputSelector::Definition { definition } => definition,
                        InputSelector::Outline { .. } => unreachable!(),
                    }
                )),
            })
        }
    }
}

Tests

Input 2: outline src/refactor/tests.rs fn[mapped_back_text_replaces_whole_new_names_and_paths]
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.definition_inputs`
#[test]
fn mapped_back_text_replaces_whole_new_names_and_paths() {
    let map = mappings(&[
        ("name", "rules.cli.check", "rules.core.check"),
        ("path", "src/a.rs", "src/b.rs"),
        ("node", "src/c.rs#fn[f]", "src/d.rs#fn[f]"),
    ]);
    assert_eq!(
        map.text_back("{impl}`rules.core.check` and rules.core.check.case"),
        "{impl}`rules.cli.check` and rules.cli.check.case"
    );
    // Longer names and other paths are left alone.
    assert_eq!(map.text_back("rules.core.checker"), "rules.core.checker");
    assert_eq!(map.text_back("xrules.core.check"), "xrules.core.check");
    assert_eq!(map.text_back("see src/b.rs."), "see src/a.rs.");
    assert_eq!(map.text_back("src/b.rs.bak"), "src/b.rs.bak");
    assert_eq!(map.text_back("lib/src/b.rs"), "lib/src/b.rs");
    assert_eq!(map.text_back("`src/d.rs#fn[f]`"), "`src/c.rs#fn[f]`");
}
Input 3: outline src/refactor/tests.rs fn[opening_fences_map_their_short_names_back]
// {test}`requirements.refactor.definition_inputs`
#[test]
fn opening_fences_map_their_short_names_back() {
    assert_eq!(
        opening_back(":::{req} verify", "rules.verify", "rules.check"),
        ":::{req} check"
    );
    assert_eq!(
        opening_back("::::{req} check", "core.check", "rules.check"),
        "::::{req} check"
    );
    assert_eq!(
        opening_back(
            ":::{req} line.detection",
            "a.line.detection",
            "b.lines.detection"
        ),
        ":::{req} lines.detection"
    );
}
Input 7: outline tests/refactor.rs fn[a_moved_requirement_renames_its_references_and_evidence]
// {test}`requirements.refactor.moved_requirement`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_requirement_renames_its_references_and_evidence() {
    let temp = project();
    let root = temp.path();
    author(root);
    fs::write(
        root.join("md/notes.md"),
        "Loading follows {cite}`rules.load`.\n",
    )
    .unwrap();
    // `load` moves to the `core` chapter; references still name the old name.
    fs::write(
        root.join("md/rules.md"),
        "# Rules\n\n:::{req} check\n:impl: data.txt\nThe data MUST be checked.\n:::\n",
    )
    .unwrap();
    fs::write(
        root.join("md/core.md"),
        "# Core\n\n:::{req} load\nConfiguration MUST load.\n:::\n",
    )
    .unwrap();
    let before = snapshot(root);
    let output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let report = stdout(&output);
    assert!(report.contains("- src/config.rs (2)"), "{report}");
    assert!(report.contains("- md/notes.md (1)"), "{report}");
    assert_eq!(
        fs::read_to_string(root.join("md/notes.md")).unwrap(),
        "Loading follows {cite}`core.load`.\n"
    );
    // Only the rewritten references and the moved evidence changed.
    let after = snapshot(root);
    let differing = before
        .keys()
        .chain(after.keys())
        .filter(|file| before.get(*file) != after.get(*file))
        .cloned()
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        differing.into_iter().collect::<Vec<_>>(),
        [
            "evidence/core.load.json",
            "evidence/rules.load.json",
            "md/notes.md",
            "src/config.rs",
        ]
    );
    assert!(
        report.contains("- evidence/rules.load.json -> evidence/core.load.json"),
        "{report}"
    );
    // The glob no longer matches what it recorded, so that record is stale.
    assert!(
        report.contains(
            "- evidence/rules.check.json: inputs[0]: rules.* no longer selects what it recorded"
        ),
        "{report}"
    );
    assert!(!root.join("evidence/rules.load.json").exists());
    let source = fs::read_to_string(root.join("src/config.rs")).unwrap();
    assert!(source.contains("// {impl}`core.load`") && source.contains("// {test}`core.load`"));
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.load.json")).unwrap())
            .unwrap();
    assert_eq!(
        record["inputs"][0],
        requirements_input("core.load", &["core.load"], &LOAD_TEXT)
    );
    assert!(
        record["rationale"]
            .as_str()
            .unwrap()
            .contains("as `core.load` asks")
    );
    let remaining = errors(root);
    assert!(
        remaining
            .iter()
            .all(|error| error.starts_with("evidence/rules.check.json")),
        "{remaining:#?}"
    );
}
Input 8: outline tests/refactor.rs fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it]
  • File: tests/refactor.rs
  • Selector: fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it]
  • Kind: fn
  • tests/refactor.rs:832–868
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.subject_text`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.record_fields`
#[test]
fn a_moved_term_rewrites_definition_inputs_and_the_texts_using_it() {
    let temp = project();
    let root = temp.path();
    add_term(root);
    assert_eq!(usage_errors(root), Vec::<String>::new());
    fs::remove_file(root.join("md/terms.md")).unwrap();
    fs::write(
        root.join("md/glossary.md"),
        "# Glossary\n\n:::{definition} term\n:phrase: term\n\nA word.\n:::\n",
    )
    .unwrap();
    let output = refactor(root, &["--map", "terms.term=glossary.term"]);
    assert!(output.status.success(), "{output:?}");
    assert_eq!(
        fs::read_to_string(root.join("md/usage.md")).unwrap(),
        "# Usage\n\n:::{req} use\nThe {term}`glossary.term` MUST be used.\n:::\n"
    );
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/usage.use.json")).unwrap())
            .unwrap();
    assert_eq!(
        record["requirement"],
        "The {term}`glossary.term` MUST be used."
    );
    assert_eq!(record["inputs"][1]["definition"], "glossary.term");
    assert_eq!(
        record["rationale"],
        "Nothing implements `usage.use`, which uses `glossary.term`."
    );
    assert_eq!(usage_errors(root), Vec::<String>::new());
}
Input 9: outline tests/refactor.rs fn[a_term_edited_while_moving_leaves_its_definition_input_stale]
  • File: tests/refactor.rs
  • Selector: fn[a_term_edited_while_moving_leaves_its_definition_input_stale]
  • Kind: fn
  • tests/refactor.rs:870–895
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_term_edited_while_moving_leaves_its_definition_input_stale() {
    let temp = project();
    let root = temp.path();
    add_term(root);
    fs::remove_file(root.join("md/terms.md")).unwrap();
    fs::write(
        root.join("md/glossary.md"),
        "# Glossary\n\n:::{definition} term\n:phrase: term\n\nA longer word.\n:::\n",
    )
    .unwrap();
    let before = fs::read(root.join("evidence/usage.use.json")).unwrap();
    let report = stdout(&refactor(root, &["--map", "terms.term=glossary.term"]));
    assert!(
        report.contains(
            "- evidence/usage.use.json: inputs[1]: glossary.term no longer selects what it recorded"
        ),
        "{report}"
    );
    assert_eq!(
        fs::read(root.join("evidence/usage.use.json")).unwrap(),
        before
    );
}
Input 10: outline tests/refactor.rs fn[a_moved_chapter_rewrites_glob_selections_and_their_matches]
  • File: tests/refactor.rs
  • Selector: fn[a_moved_chapter_rewrites_glob_selections_and_their_matches]
  • Kind: fn
  • tests/refactor.rs:955–982
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.definition_inputs`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_chapter_rewrites_glob_selections_and_their_matches() {
    let temp = project();
    let root = temp.path();
    author(root);
    let chapter = fs::read_to_string(root.join("md/rules.md")).unwrap();
    fs::remove_file(root.join("md/rules.md")).unwrap();
    fs::write(
        root.join("md/core.md"),
        chapter.replace("# Rules", "# Core"),
    )
    .unwrap();
    let output = refactor(root, &["--map", "rules=core"]);
    assert!(output.status.success(), "{output:?}");
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.check.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][0]["requirements"], "core.*");
    assert_eq!(
        record["inputs"][0]["matches"],
        json!(["core.check", "core.load"])
    );
    assert_eq!(errors(root), Vec::<String>::new());
}

Referenced definitions

Input 11: 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.definition_inputs
:::{req} definition_inputs
A requirements or definition input MUST be rewritten only if the
{term}`requirements.refactor.mapped_back` current text of each definition it
records equals the recorded text and, for a requirements input, the mapped
selection's current matches are exactly the recorded matches with the mapping
applied.
:::