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

Requirements index · View definition

evidence Valid

Requirement

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.

Rationale

The requirement is met by src/refactor.rs#fn[rewrite_rationale], and tests cover each behavior it specifies.

Obligation: In the rationale of each changed record, 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.

Implementation

  • src/refactor.rs#fn[rewrite_rationale] carries an {impl} reference to the subject. src/refactor.rs#fn[rewrite_record] calls it on the record’s rationale field and writes the result back, but only on the path that returns Outcome::Changed. That covers “each changed record”.
  • rewrite_rationale matches backtick-delimited spans with CODE_SPAN, a regex that matches whole spans, so each span is judged by its exact text. For each span it calls Mappings::address and replaces the span with `new` when an address mapping applies.
  • src/refactor.rs#impl[Mappings]/fn[address] splits the span at # and calls Mappings::node. node first looks for an explicit node mapping: the file equals the old file and the selector is the mapped node or beneath it, which gives the new file and the new selector. Otherwise it falls back to the file’s path mapping, which gives the new file and the unchanged selector. Together these cover both “a mapped node” and “a node in a mapped file”.
  • These helpers are reached from rewrite_rationale, so they need no references of their own.

Tests

  • src/refactor/tests.rs#fn[rationales_rewrite_exact_code_spans_and_list_other_mentions] has a {test} reference to the subject. It asserts that `src/a.rs#fn[f]` becomes `src/b.rs#fn[f]` under a node mapping. It also asserts that a bare `src/a.rs` is left alone.
  • src/refactor/tests.rs#fn[rationales_rewrite_addresses_of_nodes_in_mapped_files] asserts that `src/old/x.rs#fn[f]` and `src/old/x.rs#mod[m]/fn[g]` become src/new/x.rs… addresses under a path mapping.
  • tests/refactor.rs#fn[a_moved_function_keeps_its_evidence_current] runs the CLI end to end. It asserts that the rationale’s `src/config.rs#fn[load]` becomes `src/config/load.rs#fn[load]`, and that the record is rewritten and a second run changes nothing.

No gaps found.

Inputs

Implementation

Input 4: 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)
}

Tests

Input 2: 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 3: outline src/refactor/tests.rs fn[rationales_rewrite_addresses_of_nodes_in_mapped_files]
// {test}`requirements.refactor.rationale.addresses`
#[test]
fn rationales_rewrite_addresses_of_nodes_in_mapped_files() {
    let map = mappings(&[("path", "src/old", "src/new")]);
    let (rewritten, mentions) = rewrite_rationale(
        &map,
        "`src/old/x.rs#fn[f]` and `src/old/x.rs#mod[m]/fn[g]` do it.",
    );
    assert_eq!(
        rewritten,
        "`src/new/x.rs#fn[f]` and `src/new/x.rs#mod[m]/fn[g]` do it."
    );
    assert!(mentions.is_empty());
}
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)
    );
}

Referenced definitions

Input 7: 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.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 6: 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 8: 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"));