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_rewrite

Requirements index · View definition

evidence Valid

Requirement

For a definition-name mapping, habeas refactor MUST rewrite each {impl}, {test}, {cite}, {fixme}, and {term} reference that names an old name, in the book and in the sources reference discovery considers. For a path or node mapping, it MUST rewrite each :impl: or :test: anchor that names an old file or node. It MUST change nothing else in those files.

Rationale

I found no gap against requirements.refactor.reference_rewrite.

Implementation

  • src/refactor.rs#fn[rewrite_source] carries the {impl} reference. src/refactor.rs#impl[States]/fn[compute] calls it on every file reference discovery considers. That is evidence::discovered_files, plus the files of all loaded definitions, which covers the book. It collects the edits in memory, and fn[refactor] writes them out.
  • Obligation: rewrite {impl}, {test}, {cite}, {term} and inline {fixme} references that name an old name.
    • rewrite_source walks crate::reference_roles. It skips roles that are not in a reference context, such as a string literal, and Markdown code blocks are already excluded by reference_roles. It keeps only the kinds Impl, Test, Cite, Term and Fixme. It then replaces the name span with Mappings::name.
    • Mappings::name uses beneath(.., '.'), so rules.checker is not touched by a rules.check mapping.
  • Obligation: rewrite fenced :::{fixme}, :::{impl}, :::{test} and :::{cite} names. rewrite_source loops over crate::fenced::source_fences and edits the name on the opening line.
  • Obligation: for path and node mappings, rewrite :impl: and :test: anchors. In Markdown, rewrite_source iterates definition_blocks(...).options. It keeps only options named impl or test. It maps each value with Mappings::address, which applies a node mapping first and then a path mapping. Option-like lines in body text or code blocks are not directive options, so they are not touched.
  • Obligation: change nothing else. The code applies only the targeted span edits. It skips overlapping edits and rewrites no other text.

Tests

  • src/refactor/tests.rs#fn[sources_rewrite_references_to_names_and_anchors_to_paths] checks the following:
    • {impl} and a fenced {fixme} are rewritten, rules.checker is left alone, and the edit count is 2.
    • {term}, :impl: and :test: file#node anchors are rewritten in Markdown.
    • A {cite} inside a code block is left literal.
    • Option-like lines outside a directive’s options, and inside a code-block directive, are left literal.
    • A role in a string literal is left literal, and :impl: in plain text is left literal.
  • src/refactor/tests.rs#fn[anchors_follow_a_node_mapping_and_leave_other_nodes_alone] checks that a node mapping rewrites only the matching anchor and leaves a sibling node anchor alone.
  • tests/refactor.rs#fn[a_moved_requirement_renames_its_references_and_evidence] is an end-to-end name rewrite. It checks {impl}, {test} and {cite} in the sources and book, and that only the expected files change.
  • tests/refactor.rs#fn[a_moved_file_rewrites_anchors_and_paths] is an end-to-end path anchor rewrite.
  • tests/refactor.rs#fn[a_moved_term_rewrites_definition_inputs_and_the_texts_using_it] is an end-to-end {term} rewrite.
  • tests/refactor.rs#fn[a_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_it] is an end-to-end rewrite in a doc comment.

All obligations have reachable implementation code and tests. All five reference kinds, anchors for path and node mappings, and the “nothing else” boundary cases are covered.

Inputs

Implementation

Input 4: outline src/refactor.rs fn[rewrite_source]
/// Rewrites references and anchors in a source's content: each reference
/// naming a mapped definition, and in Markdown each anchor option naming a
/// mapped file or node. Returns the new content and the number of edits.
// {impl}`requirements.references.reference_contexts`
// {impl}`requirements.refactor.reference_rewrite`
fn rewrite_source(mappings: &Mappings, path: &Path, content: &str) -> (String, usize) {
    let markdown = crate::outline::is_markdown_path(path);
    let mut edits = Vec::new();
    // Only roles that count as references are rewritten; a role in a string
    // literal is literal text.
    let contexts = crate::evidence::reference_contexts(path, content);
    for role in crate::reference_roles(content, markdown) {
        if !crate::evidence::in_reference_context(contexts.as_deref(), role.start) {
            continue;
        }
        if !matches!(
            role.kind,
            ReferenceKind::Impl
                | ReferenceKind::Test
                | ReferenceKind::Cite
                | ReferenceKind::Term
                | ReferenceKind::Fixme
        ) {
            continue;
        }
        if let Some(new) = mappings.name(role.name) {
            let start = role.end - 1 - role.name.len();
            edits.push((start..start + role.name.len(), new));
        }
    }
    let line_starts = std::iter::once(0)
        .chain(content.match_indices('\n').map(|(index, _)| index + 1))
        .collect::<Vec<_>>();
    for fence in crate::fenced::source_fences(path, content) {
        let Some(new) = mappings.name(&fence.name) else {
            continue;
        };
        let Some(&start) = line_starts.get(fence.line - 1) else {
            continue;
        };
        let end = content[start..]
            .find('\n')
            .map_or(content.len(), |end| start + end);
        let line = &content[start..end];
        if let Some(role) = FENCE_ROLE.find(line)
            && line[role.end()..].starts_with(&fence.name)
        {
            let name = start + role.end();
            edits.push((name..name + fence.name.len(), new));
        }
    }
    if markdown {
        // Only the options of real directives are anchors; an `:impl:` line
        // in body text or a code block is literal.
        for block in crate::definition_blocks(content) {
            for option in &block.options {
                if !matches!(option.name.as_str(), "impl" | "test") {
                    continue;
                }
                let Some(new) = mappings.address(&option.value) else {
                    continue;
                };
                let line = &content[option.start..option.end];
                if let Some(offset) = line.rfind(option.value.as_str()) {
                    let start = option.start + offset;
                    edits.push((start..start + option.value.len(), new));
                }
            }
        }
    }
    edits.sort_by_key(|(range, _)| std::cmp::Reverse(range.start));
    let mut rewritten = content.to_owned();
    let mut last = usize::MAX;
    let mut count = 0;
    for (range, new) in edits {
        if range.end > last {
            continue;
        }
        last = range.start;
        rewritten.replace_range(range, &new);
        count += 1;
    }
    (rewritten, count)
}

Tests

Input 2: outline src/refactor/tests.rs fn[sources_rewrite_references_to_names_and_anchors_to_paths]
// {test}`requirements.references.reference_contexts`
// {test}`requirements.refactor.reference_rewrite`
#[test]
fn sources_rewrite_references_to_names_and_anchors_to_paths() {
    let map = mappings(&[
        ("name", "rules.check", "core.check"),
        ("path", "data.txt", "info.txt"),
    ]);
    let rust = concat!(
        "// {impl}`rules.check`\n",
        "// {cite}`rules.checker`\n",
        "// :::{fixme} rules.check\n// A gap.\n// :::\n",
        "fn f() {}\n",
    );
    let (rewritten, edits) = rewrite_source(&map, Path::new("src/lib.rs"), rust);
    assert_eq!(edits, 2);
    assert_eq!(
        rewritten,
        concat!(
            "// {impl}`core.check`\n",
            "// {cite}`rules.checker`\n",
            "// :::{fixme} core.check\n// A gap.\n// :::\n",
            "fn f() {}\n",
        )
    );
    // In Markdown, anchors are rewritten too, but not the declaration's name,
    // and references in code blocks stay literal.
    let markdown = concat!(
        ":::{req} other\n:impl: data.txt\n:test: data.txt#line@abc\n",
        "Uses {term}`rules.check`.\n:::\n\n```text\n{cite}`rules.check`\n```\n",
    );
    let (rewritten, edits) = rewrite_source(&map, Path::new("md/rules.md"), markdown);
    assert_eq!(edits, 3, "{rewritten}");
    assert!(rewritten.contains(":impl: info.txt\n:test: info.txt#line@abc\n"));
    assert!(rewritten.contains("Uses {term}`core.check`."));
    assert!(rewritten.contains("```text\n{cite}`rules.check`\n```"));
    // Option-like lines outside a directive's options are literal.
    let literal = concat!(
        ":::{req} other\nBody.\n:impl: data.txt\n:::\n\n",
        "```text\n:::{req} shown\n:impl: data.txt\n:::\n```\n",
    );
    let (rewritten, edits) = rewrite_source(&map, Path::new("md/rules.md"), literal);
    assert_eq!((rewritten.as_str(), edits), (literal, 0));
    // A role in a string literal is literal text, not a reference to rewrite.
    let literal = "const S: &str = \"{impl}`rules.check`\";\n".to_owned();
    let (rewritten, edits) = rewrite_source(&map, Path::new("src/lib.rs"), &literal);
    assert_eq!((rewritten.as_str(), edits), (literal.as_str(), 0));
    // Plain text is not an anchor outside Markdown.
    let (_, edits) = rewrite_source(&map, Path::new("notes.txt"), ":impl: data.txt\n");
    assert_eq!(edits, 0);
}
Input 3: outline src/refactor/tests.rs fn[anchors_follow_a_node_mapping_and_leave_other_nodes_alone]
// {test}`requirements.refactor.reference_rewrite`
#[test]
fn anchors_follow_a_node_mapping_and_leave_other_nodes_alone() {
    let map = mappings(&[("node", "src/a.rs#fn[f]", "src/b.rs#fn[g]")]);
    let markdown = ":::{req} r\n:impl: src/a.rs#fn[f]\n:test: src/a.rs#fn[other]\nBody.\n:::\n";
    let (rewritten, edits) = rewrite_source(&map, Path::new("md/rules.md"), markdown);
    assert_eq!(edits, 1, "{rewritten}");
    assert_eq!(
        rewritten,
        ":::{req} r\n:impl: src/b.rs#fn[g]\n:test: src/a.rs#fn[other]\nBody.\n:::\n"
    );
}
Input 5: 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 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_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_it]
  • File: tests/refactor.rs
  • Selector: fn[a_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_it]
  • Kind: fn
  • tests/refactor.rs:520–567
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.reference_rewrite`
// {test}`requirements.refactor.equivalence`
#[test]
fn a_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_it() {
    let temp = project();
    let root = temp.path();
    // Doc comments are hashed, so the rewritten reference changes the hash.
    fs::write(
        root.join("src/config.rs"),
        config_source("").replace("// {impl}`rules.load`", "/// {impl}`rules.load`"),
    )
    .unwrap();
    author(root);
    assert_eq!(errors(root), Vec::<String>::new());
    let hash = |root: &Path| {
        habeas::outline_input(root, "src/config.rs", "fn[load]").unwrap()["hash"].clone()
    };
    let before = hash(root);
    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 output = refactor(root, &["--map", "rules.load=core.load"]);
    assert!(output.status.success(), "{output:?}");
    let source = fs::read_to_string(root.join("src/config.rs")).unwrap();
    assert!(source.contains("/// {impl}`core.load`"), "{source}");
    let after = hash(root);
    assert_ne!(before, after);
    let record: Value =
        serde_json::from_str(&fs::read_to_string(root.join("evidence/core.load.json")).unwrap())
            .unwrap();
    assert_eq!(record["inputs"][1]["hash"], after);
    // Only the glob record, whose match set changed, remains stale.
    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());
}

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.reference_rewrite
:::{req} reference_rewrite
For a definition-name mapping, `habeas refactor` MUST rewrite each `{impl}`,
`{test}`, `{cite}`, `{fixme}`, and `{term}` reference that names an old name,
in the book and in the sources reference discovery considers. For a path or
node mapping, it MUST rewrite each `:impl:` or `:test:` anchor that names an
old file or node. It MUST change nothing else in those files.
:::
Input 9: 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 10: 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 12: outline src/lib.rs fn[reference_roles]
pub(crate) fn reference_roles(content: &str, markdown: bool) -> Vec<ReferenceMatch<'_>> {
    let protected = if markdown {
        let mut ranges = protected_ranges(content);
        for block in definition_blocks(content)
            .into_iter()
            .filter(|b| b.kind == DefinitionKind::Term)
        {
            let body = &content[block.body_start..block.body_end];
            let option_start = block.body_start + body.len() - body.trim_start().len();
            let option_end = content[option_start..block.body_end]
                .find('\n')
                .map_or(block.body_end, |offset| option_start + offset);
            ranges.push(option_start..option_end);
        }
        ranges
    } else {
        Vec::new()
    };
    let mut references = Vec::new();

    for (start, _) in content.match_indices('{') {
        if is_escaped(content, start) || is_protected(start, &protected) {
            continue;
        }
        let remaining = &content[start..];
        let (kind, prefix) = if remaining.starts_with("{impl}`") {
            (ReferenceKind::Impl, "{impl}`")
        } else if remaining.starts_with("{cite}`") {
            (ReferenceKind::Cite, "{cite}`")
        } else if remaining.starts_with("{test}`") {
            (ReferenceKind::Test, "{test}`")
        } else if remaining.starts_with("{term}`") {
            (ReferenceKind::Term, "{term}`")
        } else if remaining.starts_with("{fixme}`") {
            // Recognized so validation can report the inline form.
            (ReferenceKind::Fixme, "{fixme}`")
        } else {
            continue;
        };
        let name_start = start + prefix.len();
        let Some(name_end_offset) = content[name_start..].find('`') else {
            continue;
        };
        let name_end = name_start + name_end_offset;
        let name = &content[name_start..name_end];
        let builtin = kind != ReferenceKind::Term && builtins::is_builtin_name(name);
        if valid_name(name) || builtin {
            references.push(ReferenceMatch {
                start,
                end: name_end + 1,
                name,
                kind,
            });
        }
    }

    references
}
Input 13: outline src/fenced.rs fn[source_fences]
/// Fenced references in a source file: in Markdown text, in every line of a
/// plain-text file, or in the comment runs of another supported language. A
/// source its grammar cannot parse has no recognized fences; its parse
/// failure is reported by the checks that outline it.
// {impl}`requirements.references.roles`
pub(crate) fn source_fences(path: &std::path::Path, content: &str) -> Vec<SourceFence> {
    if !content.contains(":::") {
        return Vec::new();
    }
    if crate::outline::is_markdown_path(path) {
        return text_fences(content, true);
    }
    let profile = crate::outline::profile_for_path(path);
    if profile.language.is_none() {
        return text_fences(content, false);
    }
    crate::outline::parse_with(profile, content)
        .map(|outline| comment_fences(content, &outline))
        .unwrap_or_default()
}