requirements.refactor.equivalence
Requirements index · View definition
Requirement
After
habeas refactorsucceeds, each record it changed MUST pass or fail validation exactly as it did before the move.
Rationale
I found no gap against requirements.refactor.equivalence.
Obligations. There are two. A changed record that passed validation before the move must still pass. A changed record that failed before must still fail.
Implementation. src/refactor.rs#fn[rewrite_record] and src/refactor.rs#fn[refactor] carry {impl} references to this requirement. Together they keep both properties.
rewrite_recordrewrites a record only when its state, mapped back through the mappings, matches what the record recorded.- Outline inputs:
rewrite_inputaccepts an input only if the mapped-back hash equals the recorded hash. It then writes the post-move hash. If the hash differs, it returns an error and the record is left unchanged. - Requirement and definition inputs: they are accepted only if the mapped-back selection and matches equal what was recorded.
- Definition text and reference-set digest: they are rewritten only if the mapped-back value equals what was recorded. Otherwise they become a failure and the record is left unchanged.
- Citation reviews: they are guarded by the nested
{impl}fence. If the rewritten citations differ from the item’s current citations (same_citations), the record is left unchanged. - Site reviews: they have
file,itemandrequirementremapped consistently with the rewritten sources.
- Outline inputs:
- Any failure turns the outcome into
Outcome::Unchanged, so a record that was stale or failing before stays exactly as it was. Records that remain are written under the correct path byrefactor.
Tests. Each obligation has a test that carries a {test} reference to requirements.refactor.equivalence.
- Pass preserved. These tests run
refactorand then assert that validation errors are empty or limited to the expected glob record:a_moved_function_keeps_its_evidence_currenta_moved_file_rewrites_anchors_and_pathsa_rename_rewrites_the_hash_of_a_node_whose_doc_comment_names_ita_moved_chapter_rewrites_glob_selections_and_their_matchesa_citation_review_follows_its_item_and_the_name_it_citessite_reviews_follow_their_site_and_renamed_requirementinsrc/refactor/tests.rs
- Fail preserved.
a_record_failing_before_the_move_fails_the_same_way_after_itsetsdeterminationto false. It checks that the record is changed and that the post-move errors equal the pre-move errors apart from the rewritten rationale address. - Guard for citation reviews.
a_citation_review_whose_citations_changed_in_the_move_is_left_unchangedchecks that a review whose citations changed is reported and not rewritten. - Other leave-unchanged branches. Other tests in
tests/refactor.rscover them: edited function, edited requirement, changed reference set, and stale glob. They are tagged with other requirements. Those branches only decline to change a record, so they are not changed-record behavior under this requirement.
Inputs
Implementation
Input 3: outline src/refactor.rs fn[rewrite_record]
- File:
src/refactor.rs - Selector:
fn[rewrite_record] - Kind:
fn src/refactor.rs:722–894
/// 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 4: outline src/refactor.rs fn[refactor]
- File:
src/refactor.rs - Selector:
fn[refactor] - Kind:
fn src/refactor.rs:1122–1240
/// 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 2: outline src/refactor/tests.rs fn[site_reviews_follow_their_site_and_renamed_requirement]
- File:
src/refactor/tests.rs - Selector:
fn[site_reviews_follow_their_site_and_renamed_requirement] - Kind:
fn src/refactor/tests.rs:249–320
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
#[test]
fn site_reviews_follow_their_site_and_renamed_requirement() {
use crate::sites::tests::{RULE, SOURCE, inspect, project, write_review};
let temp = project(RULE, SOURCE);
let root = temp.path();
fs::write(
root.join("evidence/requirements.rule.json"),
json!({"requirement": "x", "determination": true, "rationale": "Fine.", "inputs": []})
.to_string(),
)
.unwrap();
crate::evidence::tests::stamp_reference_sets(root);
write_review(
root,
"fn[check_one]",
json!({"queries": ["checkers", "panics"]}),
);
write_review(root, "fn[check_two]", json!({}));
write_review(
root,
"mod[inner]/fn[check_three]",
json!({"queries": ["checkers", "panics"]}),
);
let site_errors = |root: &Path| {
let (errors, _) = inspect(root);
errors
.into_iter()
.filter(|error| error.starts_with("evidence/sites/"))
.collect::<Vec<_>>()
};
assert_eq!(site_errors(root), Vec::<String>::new());
// The requirement moves to the `rules` chapter and `check_two` to its
// own file, both unchanged.
let chapter = fs::read_to_string(root.join("md/requirements.md")).unwrap();
fs::remove_file(root.join("md/requirements.md")).unwrap();
fs::write(root.join("md/rules.md"), chapter).unwrap();
fs::write(
root.join("src/lib.rs"),
SOURCE.replace("fn check_two() {}\n", ""),
)
.unwrap();
fs::write(root.join("src/other.rs"), "fn check_two() {}\n").unwrap();
let report = refactor(
root,
&[
"requirements.rule=rules.rule".to_owned(),
"src/lib.rs#fn[check_two]=src/other.rs#fn[check_two]".to_owned(),
],
false,
)
.unwrap();
assert!(
report.contains(
"- evidence/sites/requirements.rule/src/lib.rs/fn[check_two].json -> evidence/sites/rules.rule/src/other.rs/fn[check_two].json"
),
"{report}"
);
let moved: Value = serde_json::from_str(
&fs::read_to_string(root.join("evidence/sites/rules.rule/src/other.rs/fn[check_two].json"))
.unwrap(),
)
.unwrap();
assert_eq!(moved["requirement"], "rules.rule");
assert_eq!(moved["file"], "src/other.rs");
assert_eq!(moved["item"], "fn[check_two]");
assert!(!root.join("evidence/sites/requirements.rule").exists());
assert_eq!(site_errors(root), Vec::<String>::new());
}
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_moved_file_rewrites_anchors_and_paths]
- File:
tests/refactor.rs - Selector:
fn[a_moved_file_rewrites_anchors_and_paths] - Kind:
fn tests/refactor.rs:368–393
// {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_citation_review_follows_its_item_and_the_name_it_cites]
- File:
tests/refactor.rs - Selector:
fn[a_citation_review_follows_its_item_and_the_name_it_cites] - Kind:
fn tests/refactor.rs:569–653
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
#[test]
fn a_citation_review_follows_its_item_and_the_name_it_cites() {
let temp = project();
let root = temp.path();
let cited = format!(
"{}\n// {{cite}}`rules.load`\nfn helper() {{}}\n",
config_source("")
);
fs::write(root.join("src/config.rs"), &cited).unwrap();
author(root);
let review = |root: &Path, file: &str, name: &str, text: &[&str]| {
json!({
"file": file,
"item": "fn[helper]",
"citations": [{"role": "cite", "name": name, "commentary": ""}],
"determination": true,
"rationale": format!("`{file}#fn[helper]` relies on `{name}`."),
"inputs": [
habeas::outline_input(root, file, "fn[helper]").unwrap(),
requirements_input(name, &[name], text),
],
})
};
fs::create_dir_all(root.join("evidence/citations/src/config.rs")).unwrap();
fs::write(
root.join("evidence/citations/src/config.rs/fn[helper].json"),
serde_json::to_string_pretty(&review(root, "src/config.rs", "rules.load", &LOAD_TEXT))
.unwrap(),
)
.unwrap();
assert_eq!(errors(root), Vec::<String>::new());
// The helper moves to its own file, and `load` to the `core` chapter.
fs::write(root.join("src/config.rs"), config_source("")).unwrap();
fs::write(
root.join("src/helper.rs"),
"// {cite}`rules.load`\nfn helper() {}\n",
)
.unwrap();
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",
"src/config.rs#fn[helper]=src/helper.rs#fn[helper]",
"--map",
"rules.load=core.load",
],
);
assert!(output.status.success(), "{output:?}");
assert!(
stdout(&output).contains(
"- evidence/citations/src/config.rs/fn[helper].json -> evidence/citations/src/helper.rs/fn[helper].json"
),
"{}",
stdout(&output)
);
assert!(!root.join("evidence/citations/src/config.rs").exists());
let moved: Value = serde_json::from_str(
&fs::read_to_string(root.join("evidence/citations/src/helper.rs/fn[helper].json")).unwrap(),
)
.unwrap();
assert_eq!(
moved,
review(root, "src/helper.rs", "core.load", &LOAD_TEXT)
);
let remaining = errors(root);
assert!(
remaining
.iter()
.all(|error| error.starts_with("evidence/rules.check.json")),
"{remaining:#?}"
);
}
Input 9: outline tests/refactor.rs fn[a_record_failing_before_the_move_fails_the_same_way_after_it]
- File:
tests/refactor.rs - Selector:
fn[a_record_failing_before_the_move_fails_the_same_way_after_it] - Kind:
fn tests/refactor.rs:922–953
// {test}`requirements.refactor.equivalence`
#[test]
fn a_record_failing_before_the_move_fails_the_same_way_after_it() {
let temp = project();
let root = temp.path();
author(root);
let path = root.join("evidence/rules.load.json");
let mut record: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
record["determination"] = json!(false);
fs::write(&path, serde_json::to_string_pretty(&record).unwrap()).unwrap();
let failing = errors(root);
assert!(!failing.is_empty());
move_load(root, "");
let output = refactor(
root,
&[
"--map",
"src/config.rs#fn[load]=src/config/load.rs#fn[load]",
],
);
assert!(
stdout(&output).contains("- evidence/rules.load.json\n"),
"{}",
stdout(&output)
);
// The same failure, quoting the rationale as rewritten.
let expected = failing
.iter()
.map(|error| error.replace("`src/config.rs#fn[load]`", "`src/config/load.rs#fn[load]`"))
.collect::<Vec<_>>();
assert_eq!(errors(root), expected);
}
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());
}
Input 11: outline tests/refactor.rs fn[a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged]
- File:
tests/refactor.rs - Selector:
fn[a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged] - Kind:
fn tests/refactor.rs:1164–1218
// {test}`requirements.refactor.equivalence`
// {test}`requirements.refactor.whole_record`
#[test]
fn a_citation_review_whose_citations_changed_in_the_move_is_left_unchanged() {
let temp = project();
let root = temp.path();
fs::write(
root.join("src/config.rs"),
format!(
"{}\n// {{cite}}`rules.load`\nfn helper() {{}}\n",
config_source("")
),
)
.unwrap();
author(root);
let path = root.join("evidence/citations/src/config.rs/fn[helper].json");
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(
&path,
serde_json::to_string_pretty(&json!({
"file": "src/config.rs",
"item": "fn[helper]",
"citations": [{"role": "cite", "name": "rules.load", "commentary": ""}],
"determination": true,
"rationale": "`src/config.rs#fn[helper]` relies on `rules.load`.",
"inputs": [
habeas::outline_input(root, "src/config.rs", "fn[helper]").unwrap(),
requirements_input("rules.load", &["rules.load"], &LOAD_TEXT),
],
}))
.unwrap(),
)
.unwrap();
let before = fs::read(&path).unwrap();
// The helper moves, and now cites a different requirement. Plain
// comments are not hashed, so only its citations reveal the change.
fs::write(root.join("src/config.rs"), config_source("")).unwrap();
fs::write(
root.join("src/helper.rs"),
"// {cite}`rules.check`\nfn helper() {}\n",
)
.unwrap();
let report = stdout(&refactor(
root,
&["--map", "src/config.rs#fn[helper]=src/helper.rs#fn[helper]"],
));
assert!(
report.contains(
"- evidence/citations/src/config.rs/fn[helper].json: the citations of src/helper.rs#fn[helper] differ from the recorded ones"
),
"{report}"
);
assert_eq!(fs::read(&path).unwrap(), before);
assert!(!root.join("evidence/citations/src/helper.rs").exists());
}
Other sources
Input 1: requirements selection requirements.refactor.equivalence
requirements.refactor.equivalence:md/requirements/refactor.md:103–106
:::{req} equivalence
After `habeas refactor` succeeds, each record it changed MUST pass or fail
validation exactly as it did before the move.
:::
Input 12: 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!(),
}
)),
})
}
}
}
Input 13: 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 14: outline src/refactor.rs fn[same_citations]
- File:
src/refactor.rs - Selector:
fn[same_citations] - Kind:
fn src/refactor.rs:896–929
// {cite}`habeas:util`
/// Whether a citation review's citations, as rewritten, are the post
/// state's citations of its item.
fn same_citations(states: &States, file: &str, item: &str, value: &Value) -> bool {
let items = crate::citations::citation_items(
&states.root,
&states.definitions_post,
&states.references_post,
&states.outlines_post,
);
let Some(current) = items.get(&(file.to_owned(), item.to_owned())) else {
return false;
};
let recorded = value["citations"]
.as_array()
.into_iter()
.flatten()
.map(|citation| crate::citations::Citation {
role: match citation["role"].as_str() {
Some("cite") => "cite",
Some("impl") => "impl",
Some("test") => "test",
Some("fixme") => "fixme",
_ => "",
},
name: citation["name"].as_str().unwrap_or_default().to_owned(),
commentary: citation["commentary"]
.as_str()
.unwrap_or_default()
.to_owned(),
})
.collect::<Vec<_>>();
crate::citations::same_citations(&recorded, ¤t.citations)
}