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.rationale.untouched

Requirements index · View definition

evidence Valid

Requirement

habeas refactor MUST NOT change rationale text other than the spans cite requirements.refactor.rationale.names, cite requirements.refactor.rationale.paths, and cite requirements.refactor.rationale.addresses cover. For each changed record, it MUST list the other code spans in the rationale that contain an old side of a path or node mapping, so the user can review them.

Rationale

Verdict: I found no gap in requirements.refactor.rationale.untouched.

Obligations

  1. habeas refactor MUST NOT change rationale text other than the spans covered by rationale.names, rationale.paths and rationale.addresses.
  2. For each changed record, it MUST list the other code spans in the rationale that contain an old side of a path or node mapping.

Obligation 1: no other rationale text changes

  • src/refactor.rs#fn[rewrite_rationale] uses CODE_SPAN.replace_all, which matches only backtick-delimited spans.
  • For a span that maps, the closure returns the new name or address. This happens when Mappings::name or Mappings::address returns a value.
  • For every other span, the closure returns captures[0].to_owned(), which is the original text.
  • Text outside backticks is never touched. Spans that are not exactly a mapped name, path or node address are also left alone.
  • Spans such as `src/a.rs:3` and `rules.client` are not rewritten, because beneath requires the remainder to be empty or to start with a separator.
  • src/refactor.rs#fn[rewrite_record] calls rewrite_rationale only for records that end up changed. Unaffected records and records that fail with Unchanged keep their rationale as it was.

Obligation 2: listing other mentions

  • rewrite_rationale collects old_paths(), which are the old paths of path mappings and the old files of node mappings.
  • Each unmapped span that contains one of them is pushed to mentions.
  • rewrite_record returns mentions in Outcome::Changed.
  • src/refactor.rs#fn[refactor] prints each one as “review the rationale’s …”, in both dry-run and real runs.
  • The check uses the file part of a node mapping’s old side, so it can list a few extra spans, such as `src/a.rs`. That fits the purpose of letting the user review them, and I do not count it as a gap.

Tests

  • The unit test src/refactor/tests.rs#fn[rationales_rewrite_exact_code_spans_and_list_other_mentions] carries a {test} reference to rationale.untouched.
    • It asserts that bare text (rules.cli.check) is untouched.
    • It asserts that near-miss spans (src/a.rs:3, rules.client) are untouched.
    • It asserts that the mentions are exactly `src/a.rs` and `src/a.rs:3`.
  • The integration test tests/refactor.rs#fn[a_moved_function_keeps_its_evidence_current] carries a {test} reference to rationale.untouched.
    • It checks the final rationale text, in which verify and src/config.rs are unchanged.
    • It checks that the report contains “review the rationale’s src/config.rs”.
    • It checks that an unaffected record is left unchanged.

References

  • {impl} references to rationale.untouched sit on rewrite_rationale and refactor, which reach all of the code above.

Inputs

Implementation

Input 6: outline src/refactor.rs fn[rewrite_rationale]
/// Rewrites a rationale's code spans that are exactly an old definition
/// name, path, or node address, and lists the other spans that mention an
/// old path.
// {impl}`requirements.refactor.rationale.names`
// {impl}`requirements.refactor.rationale.paths`
// {impl}`requirements.refactor.rationale.addresses`
// {impl}`requirements.refactor.rationale.untouched`
fn rewrite_rationale(mappings: &Mappings, rationale: &str) -> (String, Vec<String>) {
    let old_paths = mappings.old_paths();
    let mut mentions = Vec::new();
    let rewritten = CODE_SPAN.replace_all(rationale, |captures: &regex::Captures<'_>| {
        let span = &captures[1];
        let mapped = mappings.name(span).or_else(|| mappings.address(span));
        match mapped {
            Some(new) => format!("`{new}`"),
            None => {
                if old_paths.iter().any(|old| span.contains(old)) {
                    mentions.push(format!("`{span}`"));
                }
                captures[0].to_owned()
            }
        }
    });
    (rewritten.into_owned(), mentions)
}
Input 7: outline src/refactor.rs fn[refactor]
/// Runs `habeas refactor` with `--map` values, reporting what it changed,
/// or with `dry_run`, what it would change.
// {impl}`requirements.refactor.command`
// {impl}`requirements.refactor.dry_run`
// {impl}`requirements.refactor.record_files`
// {impl}`requirements.refactor.equivalence`
// {impl}`requirements.refactor.rationale.untouched`
pub fn refactor(root: &Path, values: &[String], dry_run: bool) -> Result<String, RefactorError> {
    let root = fs::canonicalize(root)?;
    let records = load_records(&root)?;
    let mappings = parse_mappings(&root, values, &records)?;
    let states = States::compute(&root, mappings)?;
    let mut changed = Vec::new();
    let mut unchanged = Vec::new();
    let mut targets = BTreeMap::<String, usize>::new();
    for (path, record) in &records {
        match rewrite_record(&states, path, record)? {
            Outcome::Unaffected => {}
            Outcome::Unchanged(reason) => unchanged.push((path.clone(), reason)),
            Outcome::Changed {
                path: target,
                value,
                mentions,
            } => {
                *targets.entry(target.clone()).or_default() += 1;
                changed.push((path.clone(), target, value, mentions));
            }
        }
    }
    // A move may take the place of a record that moves away, but only if
    // that record's move survives: dropping one conflict can expose another,
    // so conflicts are dropped until none remain.
    loop {
        let moving = changed
            .iter()
            .filter(|(path, target, ..)| path != target)
            .map(|(path, ..)| path.clone())
            .collect::<BTreeSet<_>>();
        let before = changed.len();
        changed.retain(|(path, target, ..)| {
            let conflict = targets[target] > 1
                || (path != target && root.join(target).exists() && !moving.contains(target));
            if conflict {
                unchanged.push((path.clone(), format!("{target} would be overwritten")));
            }
            !conflict
        });
        if changed.len() == before {
            break;
        }
    }
    unchanged.sort();

    if !dry_run {
        for (file, (content, _)) in &states.rewritten {
            fs::write(root.join(file), content)?;
        }
        for (path, ..) in &changed {
            if !changed.iter().any(|(_, target, ..)| target == path) {
                let old = root.join(path);
                if fs::remove_file(&old).is_ok() {
                    prune(&root, &old);
                }
            }
        }
        for (_, target, value, _) in &changed {
            let target = root.join(target);
            if let Some(parent) = target.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(
                &target,
                format!(
                    "{}\n",
                    serde_json::to_string_pretty(value).map_err(io::Error::from)?
                ),
            )?;
        }
    }

    let (rewrote, change, leave) = if dry_run {
        ("Would rewrite", "Would change", "Would leave")
    } else {
        ("Rewrote", "Changed", "Left")
    };
    let mut report = String::new();
    if !states.rewritten.is_empty() {
        let _ = writeln!(
            report,
            "{rewrote} references or anchors in {} files:",
            states.rewritten.len()
        );
        for (file, (_, edits)) in &states.rewritten {
            let _ = writeln!(report, "- {file} ({edits})");
        }
    }
    let _ = writeln!(report, "{change} {} records:", changed.len());
    for (path, target, _, mentions) in &changed {
        if path == target {
            let _ = writeln!(report, "- {path}");
        } else {
            let _ = writeln!(report, "- {path} -> {target}");
        }
        for mention in mentions {
            let _ = writeln!(report, "  - review the rationale's {mention}");
        }
    }
    if !unchanged.is_empty() {
        let _ = writeln!(
            report,
            "{leave} {} records unchanged; they stay stale until reassessed:",
            unchanged.len()
        );
        for (path, reason) in &unchanged {
            let _ = writeln!(report, "- {path}: {reason}");
        }
    }
    Ok(report)
}

Tests

Input 5: outline src/refactor/tests.rs fn[rationales_rewrite_exact_code_spans_and_list_other_mentions]
// {test}`requirements.refactor.rationale.names`
// {test}`requirements.refactor.rationale.paths`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
#[test]
fn rationales_rewrite_exact_code_spans_and_list_other_mentions() {
    let map = mappings(&[
        ("name", "rules.cli", "rules.core"),
        ("path", "src/old", "src/new"),
        ("node", "src/a.rs#fn[f]", "src/b.rs#fn[f]"),
    ]);
    let (rewritten, mentions) = rewrite_rationale(
        &map,
        "`rules.cli.check` holds; `src/old/x.rs` and `src/a.rs#fn[f]` do it. \
         `src/a.rs` stays, as does `src/a.rs:3`, rules.cli.check, and `rules.client`.",
    );
    assert_eq!(
        rewritten,
        "`rules.core.check` holds; `src/new/x.rs` and `src/b.rs#fn[f]` do it. \
         `src/a.rs` stays, as does `src/a.rs:3`, rules.cli.check, and `rules.client`."
    );
    assert_eq!(mentions, ["`src/a.rs`", "`src/a.rs:3`"]);
}
Input 8: 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)
    );
}

Referenced definitions

Input 2: requirements selection requirements.refactor.rationale.names
:::{req} rationale.names
In the rationale of each changed record, `habeas refactor` MUST rewrite each
code span that is exactly an old definition name, or a name beneath one, to its
new name.
:::
Input 3: requirements selection requirements.refactor.rationale.paths
:::{req} rationale.paths
In the rationale of each changed record, `habeas refactor` MUST rewrite each
code span that is exactly a mapped file path, or a path beneath a mapped
directory, to its new path.
:::
Input 4: requirements selection requirements.refactor.rationale.addresses
:::{req} rationale.addresses
In the rationale of each changed record, `habeas refactor` MUST rewrite each
code span that is exactly `<file>#<selector>` for a mapped node, or for a node
in a mapped file, to the node's new address.
:::
Input 10: 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.rationale.untouched
:::{req} rationale.untouched
`habeas refactor` MUST NOT change rationale text other than the spans
{cite}`requirements.refactor.rationale.names`,
{cite}`requirements.refactor.rationale.paths`, and
{cite}`requirements.refactor.rationale.addresses` cover. For each changed
record, it MUST list the other code spans in the rationale that contain an old
side of a path or node mapping, so the user can review them.
:::
Input 9: outline src/refactor.rs impl[Mappings]
// {impl}`requirements.refactor.mappings`
impl Mappings {
    /// A definition name's new name, if a mapping covers it.
    fn name(&self, name: &str) -> Option<String> {
        self.names
            .iter()
            .find_map(|(old, new)| beneath(name, old, '.').map(|rest| format!("{new}{rest}")))
    }

    /// A current definition name's old name, if a mapping covers it.
    fn name_back(&self, name: &str) -> Option<String> {
        self.names
            .iter()
            .find_map(|(old, new)| beneath(name, new, '.').map(|rest| format!("{old}{rest}")))
    }

    /// A definition selection with a mapped name prefix replaced.
    fn selection(&self, selection: &str) -> Option<String> {
        self.name(selection)
    }

    /// A file's new path under a path mapping.
    fn path(&self, file: &str) -> Option<String> {
        self.paths
            .iter()
            .find_map(|(old, new)| beneath(file, old, '/').map(|rest| format!("{new}{rest}")))
    }

    /// A current file's old path under a path mapping.
    fn path_back(&self, file: &str) -> Option<String> {
        self.paths
            .iter()
            .find_map(|(old, new)| beneath(file, new, '/').map(|rest| format!("{old}{rest}")))
    }

    /// A node's new address: under a node mapping covering it, or else its
    /// file's path mapping.
    fn node(&self, file: &str, item: &str) -> Option<(String, String)> {
        self.nodes
            .iter()
            .find_map(|((old_file, old_item), (new_file, new_item))| {
                (file == old_file)
                    .then(|| beneath_node(item, old_item))
                    .flatten()
                    .map(|rest| (new_file.clone(), join_node(new_item, rest)))
            })
            .or_else(|| self.path(file).map(|file| (file, item.to_owned())))
    }

    /// A current node's old address.
    fn node_back(&self, file: &str, item: &str) -> Option<(String, String)> {
        self.nodes
            .iter()
            .find_map(|((old_file, old_item), (new_file, new_item))| {
                (file == new_file)
                    .then(|| beneath_node(item, new_item))
                    .flatten()
                    .map(|rest| (old_file.clone(), join_node(old_item, rest)))
            })
            .or_else(|| self.path_back(file).map(|file| (file, item.to_owned())))
    }

    /// An anchor value or rationale address, `file` or `file#selector`,
    /// under the mappings.
    fn address(&self, value: &str) -> Option<String> {
        let (file, item) = value.split_once('#').unwrap_or((value, ""));
        self.node(file, item)
            .map(|(file, item)| address(&file, &item))
    }

    /// An address mapped back.
    fn address_back(&self, value: &str) -> Option<String> {
        let (file, item) = value.split_once('#').unwrap_or((value, ""));
        self.node_back(file, item)
            .map(|(file, item)| address(&file, &item))
    }

    /// The old sides of path and node mappings, as paths.
    fn old_paths(&self) -> Vec<&str> {
        self.paths
            .iter()
            .map(|(old, _)| old.as_str())
            .chain(self.nodes.iter().map(|((file, _), _)| file.as_str()))
            .collect()
    }

    /// The {term}`requirements.refactor.mapped_back` form of text: each new
    /// node address, definition name, and path replaced by its old side.
    fn text_back(&self, text: &str) -> String {
        let mut text = text.to_owned();
        for ((old_file, old_item), (new_file, new_item)) in &self.nodes {
            if !new_item.is_empty() {
                text = text.replace(&address(new_file, new_item), &address(old_file, old_item));
            }
        }
        for (old, new) in &self.names {
            text = replace_tokens(&text, new, old, Token::Name);
        }
        for (old, new) in &self.paths {
            text = replace_tokens(&text, new, old, Token::Path);
        }
        text
    }
}
Input 11: outline src/refactor.rs static[CODE_SPAN]
/// A backtick-delimited code span.
static CODE_SPAN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"`([^`\n]+)`").expect("code span pattern"));
Input 12: 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,
    })
}
Input 13: requirements selection requirements.refactor.mappings
:::{req} mappings
Each `--map` MUST have one of these forms:

- a file or directory path, which maps that file, or every file under that
  directory, to the same relative path under the new side;
- `<file>#<selector>`, which maps one outline node, and its outline
  descendants, to the node at the new file and selector;
- a definition name, which maps that full name, and every full name beginning
  with it followed by `.`, to the same suffix under the new name.

A mapping whose old side names a recorded definition, or a prefix of one
followed by `.`, MUST be a definition-name mapping.
:::