requirements.refactor.outline_inputs
Requirements index · View definition
Requirement
An outline input MUST be rewritten only if the mapped node exists and its structural hash, computed under
over the mapped-back text of the node, equals the recorded hash.
Rationale
I found no gaps.
Obligation: an outline input is rewritten only if (a) the mapped node exists and (b) its structural hash, computed over the mapped-back text of the node, equals the recorded hash.
Implementation: src/refactor.rs#fn[rewrite_input] carries the {impl} reference. Its InputSelector::Outline arm does the following:
- It finds the node’s new address with
mappings.node(&file, &item). That function (src/refactor.rs#impl[Mappings]/fn[node]) uses a node mapping covering the node, or else the file’s path mapping. If no mapping applies and the file is not rewritten, the arm returnsNoneand leaves the input alone. - It computes the hash at the mapped address with
states.hash(&states.outlines_back, &new_file, &new_item). Hereoutlines_backis anOutlineCachewhose overrides are built inStates::compute. For each source file,computeapplies the mappings and thenmappings.text_back, so every new name or path goes back to its old side. That gives the mapped-back text, and the hash is the outline node’sstructural_hash. - Existence is covered because
States::hashcallsparsed.resolve(file, item)?. A missing node givesErr, so the input is not rewritten. - The input is rewritten (
Ok(json!({file, item, hash: current}))) only when the mapped-back hash equals the recorded hash. Any other result gives anErr(“no longer has the recorded hash”), and the input is not rewritten.
requirements.references.structural_hash is cited as context, and the code uses the outline’s structural_hash as that requirement specifies.
Tests: each test carries a {test} reference to the subject.
- Matching hash is rewritten.
tests/refactor.rs#fn[a_moved_function_keeps_its_evidence_current]shows that a moved function’s record is rewritten to the new file and errors disappear. - Hash mismatch is not rewritten.
tests/refactor.rs#fn[a_function_edited_while_moving_leaves_its_records_stale]shows the “no longer has the recorded hash” report and a record left byte-identical. - Missing mapped node is not rewritten.
tests/refactor.rs#fn[an_input_whose_node_is_missing_after_the_move_is_not_rewritten]shows the “no outline node matches” report and an unchanged record. - Mapped-back text drives the hash.
tests/refactor.rs#fn[a_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_it]shows the recorded hash matches only through the mapped-back text. It uses a doc comment naming a renamed requirement and checks the new hash is stored. - Mapped-back text replacement.
src/refactor/tests.rs#fn[mapped_back_text_replaces_whole_new_names_and_paths]teststext_backdirectly, including its boundary cases.
I found no unspecified behavior in the {impl} code that this requirement or another requirement it marks with {impl} does not cover.
Inputs
Implementation
Input 4: outline src/refactor.rs fn[rewrite_input]
- File:
src/refactor.rs - Selector:
fn[rewrite_input] - Kind:
fn src/refactor.rs:623–720
/// 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 3: outline src/refactor/tests.rs fn[mapped_back_text_replaces_whole_new_names_and_paths]
- File:
src/refactor/tests.rs - Selector:
fn[mapped_back_text_replaces_whole_new_names_and_paths] - Kind:
fn src/refactor/tests.rs:115–135
// {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 5: outline tests/refactor.rs fn[a_moved_function_keeps_its_evidence_current]
- File:
tests/refactor.rs - Selector:
fn[a_moved_function_keeps_its_evidence_current] - Kind:
fn tests/refactor.rs:171–241
// {test}`requirements.refactor.moved_function`
// {test}`requirements.refactor.command`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.reference_digest`
// {test}`requirements.refactor.rationale.addresses`
// {test}`requirements.refactor.rationale.untouched`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.mappings`
#[test]
fn a_moved_function_keeps_its_evidence_current() {
let temp = project();
let root = temp.path();
author(root);
assert_eq!(errors(root), Vec::<String>::new());
move_load(root, "");
let stale = errors(root);
assert!(
stale.iter().any(|error| error.contains("fn[load]")),
"{stale:#?}"
);
let unaffected = fs::read(root.join("evidence/rules.check.json")).unwrap();
let output = refactor(
root,
&[
"--map",
"src/config.rs#fn[load]=src/config/load.rs#fn[load]",
],
);
assert!(output.status.success(), "{output:?}");
let report = stdout(&output);
assert!(
report.contains("Changed 1 records:\n- evidence/rules.load.json\n"),
"{report}"
);
// The other mention of the old file is listed for review.
assert!(
report.contains("review the rationale's `src/config.rs`"),
"{report}"
);
// `rules.check` reads no moved node, so it is unaffected and unchanged.
assert!(!report.contains("rules.check"), "{report}");
assert_eq!(
fs::read(root.join("evidence/rules.check.json")).unwrap(),
unaffected
);
assert_eq!(errors(root), Vec::<String>::new());
let record: Value =
serde_json::from_str(&fs::read_to_string(root.join("evidence/rules.load.json")).unwrap())
.unwrap();
assert_eq!(record["inputs"][1]["file"], "src/config/load.rs");
assert_eq!(
record["rationale"],
"`src/config/load.rs#fn[load]` loads it, as `rules.load` asks; `verify` tests it in `src/config.rs`."
);
// Running it again changes nothing.
let again = refactor(
root,
&[
"--map",
"src/config.rs#fn[load]=src/config/load.rs#fn[load]",
],
);
assert!(
stdout(&again).contains("Changed 0 records:"),
"{}",
stdout(&again)
);
}
Input 6: outline tests/refactor.rs fn[a_function_edited_while_moving_leaves_its_records_stale]
- File:
tests/refactor.rs - Selector:
fn[a_function_edited_while_moving_leaves_its_records_stale] - Kind:
fn tests/refactor.rs:243–274
// {test}`requirements.refactor.edited_while_moving`
// {test}`requirements.refactor.outline_inputs`
// {test}`requirements.refactor.whole_record`
// {test}`requirements.refactor.command`
#[test]
fn a_function_edited_while_moving_leaves_its_records_stale() {
let temp = project();
let root = temp.path();
author(root);
move_load(root, " parse();");
let before = fs::read(root.join("evidence/rules.load.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(
"- evidence/rules.load.json: inputs[1]: src/config/load.rs#fn[load] no longer has the recorded hash"
),
"{report}"
);
assert_eq!(
fs::read(root.join("evidence/rules.load.json")).unwrap(),
before
);
assert!(!errors(root).is_empty());
}
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[an_input_whose_node_is_missing_after_the_move_is_not_rewritten]
- File:
tests/refactor.rs - Selector:
fn[an_input_whose_node_is_missing_after_the_move_is_not_rewritten] - Kind:
fn tests/refactor.rs:897–920
// {test}`requirements.refactor.outline_inputs`
#[test]
fn an_input_whose_node_is_missing_after_the_move_is_not_rewritten() {
let temp = project();
let root = temp.path();
author(root);
// The file moves, but `verify` does not come with it.
fs::remove_file(root.join("src/config.rs")).unwrap();
fs::write(
root.join("src/settings.rs"),
config_source("").replace("fn verify() { load(); check(); }\n", ""),
)
.unwrap();
let before = fs::read(root.join("evidence/rules.load.json")).unwrap();
let report = stdout(&refactor(root, &["--map", "src/config.rs=src/settings.rs"]));
assert!(
report.contains("inputs[2]: src/settings.rs: no outline node matches \"fn[verify]\""),
"{report}"
);
assert_eq!(
fs::read(root.join("evidence/rules.load.json")).unwrap(),
before
);
}
Referenced definitions
Input 2: requirements selection requirements.references.structural_hash
requirements.references.structural_hash:md/requirements/references.md:394–413
:::{req} structural_hash
A node's structural hash MUST be the SHA-256 digest of an unambiguous encoding of
its outline-relevant structure, including siblings its profile attaches to it:
the kinds of its named grammar nodes and, in source order, its text pieces. A
text piece MUST be the text of a leaf token, or text inside a node that no child
token covers. Each text piece MUST be hashed as its ordered list of words, where
words are separated by whitespace, the whitespace itself, including leading and
trailing whitespace, is never hashed, and each word is encoded separately, so
`ab cd` and `abcd` differ. The same rule MUST apply in every language. Comments
MUST be excluded, except comment kinds the profile includes; the Rust profile MUST include doc comments. For an included comment, only its text and its
profile's comment group MUST be hashed, not its delimiter tokens such as `//`,
`///`, `//!`, `/*`, `*/`, or a leading `*`; the Rust profile's groups are inner
and outer doc comments. The words of consecutive included comments of one group
MUST be hashed as one ordered list, so reflowing them across more or fewer lines
or comments does not change the hash, while moving text between groups does. A `line`
node's hash MUST be computed by the same word rule over the line's text. A node's
identity hash MUST be computed the same way but MUST also exclude its outline
descendants and their attached siblings, so editing a descendant does not change
its ancestors' selectors.
:::
Input 9: definition requirements.refactor.mapped_back
requirements.refactor.mapped_back:md/requirements/refactor.md:58–63
:::{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.outline_inputs
requirements.refactor.outline_inputs:md/requirements/refactor.md:65–71
:::{req} outline_inputs
An outline input MUST be rewritten only if the mapped node exists and its
structural hash, computed under
{cite}`requirements.references.structural_hash` over the
{term}`requirements.refactor.mapped_back` text of the node, equals the recorded
hash.
:::
Input 10: outline src/refactor.rs impl[States]
- File:
src/refactor.rs - Selector:
impl[States] - Kind:
impl src/refactor.rs:393–567
impl States {
/// 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),
})
}
/// A node's structural hash in a state.
fn hash(&self, outlines: &OutlineCache, file: &str, item: &str) -> Result<String, String> {
let parsed = outlines.parse(&self.root, file);
let parsed = parsed.as_ref().as_ref().map_err(Clone::clone)?;
let index = parsed.resolve(file, item)?;
Ok(parsed.outline.nodes[index].structural_hash.clone())
}
/// The post state's reference-set digest of a current definition, and
/// the mapped-back digest of its old name.
// {impl}`requirements.refactor.reference_digest`
fn digests(&self, new: &str, old: &str) -> io::Result<Option<(String, String)>> {
let (Some(post), Some(back)) = (
self.definitions_post.get(new),
self.definitions_back.get(old),
) else {
return Ok(None);
};
let sites = crate::evidence::definition_sites(
&self.root,
new,
post,
&self.files,
&self.outlines_post,
)?;
let current = crate::evidence::reference_set_digest(
&self.root,
&self.outlines_post,
new,
post,
&self.references_post,
&sites,
);
let mut entries = crate::evidence::reference_set_entries(
&self.root,
&self.outlines_back,
old,
back,
&self.references_back,
&sites,
);
for entry in &mut entries {
if entry.origin != "anchor"
&& let Some((file, item)) = self.mappings.node_back(&entry.file, &entry.item)
{
entry.file = file;
entry.item = item;
}
}
Ok(Some((current, crate::evidence::digest_entries(entries))))
}
}
Input 11: outline src/refactor.rs impl[Mappings]/fn[node]
- File:
src/refactor.rs - Selector:
impl[Mappings]/fn[node] - Kind:
fn src/refactor.rs:137–149
/// 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())))
}