[tests] Add anneal-spec-lower quantifier, MathInt, and closure tests (#610)

Human review surface: none

Add standalone integration test coverage in
`tools/anneal-spec/lower/tests/emit_checks_quantifier_paths_math_int_and_closure_edges.rs`
for `anneal-spec-lower` edge cases:

- `emit_checks` quantifier scanning across `safety_requires`, inline
  `mod` and trait `impl` blocks, `anneal::external_spec!` modules and
  impls, `bool` binders, and `.` / `:` token boundaries (`u8::MAX`,
  `.count_ones()`).
- `emit_checks` path qualification for `alloc::` roots (including the
  fallback trait-path branch), `self` / `self::`, `super` / `super::`,
  generic type arguments, and compound `qself` types (`&T`, `[T; N]`,
  `[T]`, `*const T`, `(T)`).
- `rustc --test` execution of emitted `MathInt` multi-limb
  multiplication carry (`u64::MAX * u64::MAX`), cross-limb right shifts
  (`(1u64 << 32) >> 1`), and `PatKind::IntConst` match-scrutinee
  inference.
- `closure::parse_capture_json` raw-pointer detection inside `Vec` and
  `place_mention` preservation on fake pointer-metadata locals.
- `Format::V2Specs` return-type mismatch diagnostics
  (`E_ANNEAL_SIGNATURE_MISMATCH`), dependency-ordered helper emission
  under `--target`, zero-width `HintSiteTable` spans, `SourceMap`
  out-of-bounds column clamping, and sorted CLI file diagnostics.

Agent-authored-by: AI agent acting on joshlf's behalf
diff --git a/tools/anneal-spec/lower/tests/emit_checks_quantifier_paths_math_int_and_closure_edges.rs b/tools/anneal-spec/lower/tests/emit_checks_quantifier_paths_math_int_and_closure_edges.rs
new file mode 100644
index 0000000..fd144e0
--- /dev/null
+++ b/tools/anneal-spec/lower/tests/emit_checks_quantifier_paths_math_int_and_closure_edges.rs
@@ -0,0 +1,369 @@
+// Copyright 2026 The Fuchsia Authors
+//
+// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
+// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
+// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
+// This file may not be copied, modified, or distributed except according to
+// those terms.
+
+//! Integration tests for `anneal_spec_lower` quantifier path scanning,
+//! `qself` and relative path qualification, `MathInt` carry/shift semantics,
+//! match integer constant pattern inference, capture raw-ptr filtering,
+//! `v2-specs` return mismatch checks, and diagnostic/CLI ordering edges.
+
+#![forbid(unsafe_code)]
+
+use std::{
+    fs,
+    path::PathBuf,
+    process::Command,
+    sync::atomic::{AtomicU64, Ordering},
+};
+
+use anneal_spec_lower::{
+    closure::parse_capture_json,
+    emit_checks::{emit_checks, EmitChecksOptions, EmittedChecks},
+    hint_sites::HintSiteTable,
+    lower_with, CapturedProgramSummary, Format, Options, Scope, Source, SourceMap,
+};
+use serde_json::{json, Value};
+
+static NEXT_ID: AtomicU64 = AtomicU64::new(0);
+
+struct TempDir(PathBuf);
+
+impl TempDir {
+    fn new(tag: &str) -> Self {
+        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
+        let dir =
+            std::env::temp_dir().join(format!("anneal-qp-edges-{tag}-{}-{id}", std::process::id()));
+        let _ = fs::remove_dir_all(&dir);
+        fs::create_dir_all(&dir).expect("create temp dir");
+        Self(dir)
+    }
+}
+
+impl Drop for TempDir {
+    fn drop(&mut self) {
+        let _ = fs::remove_dir_all(&self.0);
+    }
+}
+
+fn src(label: &str, text: &str) -> Source {
+    Source { label: label.to_string(), text: text.to_string(), module: Vec::new() }
+}
+
+fn emit_ok(sources: &[Source]) -> EmittedChecks {
+    emit_checks(sources, &EmitChecksOptions::default()).unwrap_or_else(|errs| {
+        panic!(
+            "emit_checks failed:\n{}",
+            errs.iter().map(|e| e.render(sources)).collect::<String>()
+        )
+    })
+}
+
+fn emit_err(sources: &[Source]) -> Vec<(&'static str, String)> {
+    match emit_checks(sources, &EmitChecksOptions::default()) {
+        Ok(_) => panic!("expected emit_checks to fail"),
+        Err(errs) => errs.into_iter().map(|e| (e.diag.code, e.render(sources))).collect(),
+    }
+}
+
+fn assert_quant_fn(rep: &Value, fn_path: &str, role: &str) {
+    let fns = rep["functions"].as_array().expect("functions array");
+    let entry = fns.iter().find(|f| f["function"] == fn_path).unwrap_or_else(|| {
+        panic!("missing function `{fn_path}` in {fns:?}");
+    });
+    assert_eq!(entry["wrapper_post_checked"], false, "expected unchecked pre on {fn_path}");
+    let unchecked = entry["unchecked_clauses"].as_array().expect("unchecked_clauses");
+    assert!(
+        unchecked.iter().any(|u| u["clause_kind"] == "quantifier" && u["clause_role"] == role),
+        "missing quantifier/{role} on {fn_path}: {unchecked:?}"
+    );
+}
+
+#[test]
+fn emit_checks_quantifier_paths_safety_and_free_ident_edges() {
+    let code = r#"
+#[cfg_attr(anneal, anneal::spec(
+    safety_requires(forall(|k: u8| k == k)), ensures(|r| r == x)
+))]
+pub unsafe fn q_safety(x: u8) -> u8 { x }
+mod inner_mod {
+    #[cfg_attr(anneal, anneal::spec(requires(forall(|k: u8| k == k)), ensures(|r| r == x)))]
+    pub fn m_fn(x: u8) -> u8 { x }
+}
+pub trait TrS { fn s_fn(x: u8) -> u8; }
+pub struct S;
+impl TrS for S {
+    #[cfg_attr(anneal, anneal::spec(requires(forall(|k: u8| k == k)), ensures(|r| r == x)))]
+    fn s_fn(x: u8) -> u8 { x }
+}
+anneal::external_spec! {
+    mod ext_m {
+        #[anneal::spec(requires(forall(|k: u8| k == k)), ensures(|r| r == x))]
+        fn em_fn(x: u8) -> u8;
+    }
+    impl ExtTr for ExtS {
+        #[anneal::spec(requires(forall(|k: u8| k == k)), ensures(|r| r == x))]
+        fn es_fn(x: u8) -> u8;
+    }
+}
+#[cfg_attr(anneal, anneal::spec(requires(
+    forall(|b: bool| b == b) && forall(|k: u8| k <= u8::MAX && k.count_ones() <= 8)
+)))]
+pub fn bool_and_scan_ok() {}
+"#;
+    let emitted = emit_ok(&[src("lib.rs", code)]);
+    let rep: Value = serde_json::from_str(&emitted.report_json).expect("parse report JSON");
+    for (p, r) in [
+        ("q_safety", "safety_requires"),
+        ("inner_mod::m_fn", "requires"),
+        ("<S as TrS>::s_fn", "requires"),
+        ("ext_m::em_fn", "requires"),
+        ("<ExtS as ExtTr>::es_fn", "requires"),
+    ] {
+        assert_quant_fn(&rep, p, r);
+    }
+    let fns = rep["functions"].as_array().expect("functions array");
+    let q_entry = fns.iter().find(|f| f["function"] == "q_safety").expect("q_safety");
+    assert_eq!(q_entry["has_safety_requires"], true);
+    assert!(q_entry["harness_skipped_reason"].as_str().is_some_and(|s| s.contains("quantifier")));
+
+    let w_start = emitted.wrappers_rs.find("fn checked_q_safety(").expect("checked_q_safety");
+    let w_body = &emitted.wrappers_rs[w_start..];
+    let w_end = w_body.find("\n    }\n").expect("checked_q_safety end");
+    assert!(!w_body[..w_end].contains("post_q_safety("), "safety quantifier must skip post check");
+    let t_start = emitted.tests_rs.find("fn prop_q_safety()").expect("prop_q_safety");
+    assert!(emitted.tests_rs[t_start.saturating_sub(120)..t_start].contains("#[ignore"));
+
+    // `u8::MAX` and `k.count_ones()` inside `forall` must not count as uses
+    // of outer `let MAX` / `let count_ones` bindings.
+    for (binder, body) in [
+        ("MAX", "let MAX = 1u8; forall(|k: u8| k <= u8::MAX)"),
+        ("count_ones", "let count_ones = 1u32; forall(|k: u8| k.count_ones() <= 8)"),
+    ] {
+        let bad = format!("#[cfg_attr(anneal, anneal::spec(requires({{ {body} }})))]\nfn u() {{}}");
+        let errs = emit_err(&[src("lib.rs", &bad)]);
+        assert!(
+            errs.iter().any(|(c, m)| *c == "E_ANNEAL_UNUSED_LET" && m.contains(binder)),
+            "expected E_ANNEAL_UNUSED_LET for `{binder}`, got: {errs:?}"
+        );
+    }
+}
+
+#[test]
+fn emit_checks_path_qualification_and_qself_compound_type_edges() {
+    let code = r#"
+#[cfg_attr(anneal, anneal::spec(target = "<alloc::vec::Vec<u8> as Tr>::f", ensures(|r| r == x)))]
+fn alloc_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "<u8 as alloc::Tr[0]>::f", ensures(|r| r == x)))]
+fn alloc_tr_fallback_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "self::helper_fn", ensures(|r| r == x)))]
+fn self_path_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "<self as SelfTr>::f", ensures(|r| r == x)))]
+fn self_ty_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "super::helper_fn", ensures(|r| r == x)))]
+fn super_path_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "<super as SupTr>::f", ensures(|r| r == x)))]
+fn super_ty_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(target = "<Wrapper<LocalItem> as Tr>::f", ensures(|r| r == x)))]
+fn generic_f(x: u8) -> u8 { x }
+#[cfg_attr(anneal, anneal::spec(
+    target = "<(&LocalRef, [*const LocalPtr; 2], [LocalSlice], (LocalParen)) as CmpTr>::f",
+    ensures(|r| r == x)
+))]
+fn compound_f(x: u8) -> u8 { x }
+"#;
+    let emitted = emit_ok(&[src("lib.rs", code)]);
+    let w = &emitted.wrappers_rs;
+    assert!(w.contains("<alloc::vec::Vec<u8> as crate::Tr>::f(") && !w.contains("crate::alloc"));
+    assert!(w.contains("<u8 as alloc::Tr[0]>::f("));
+    assert!(w.contains("= super::helper_fn(") && !w.contains("crate::self"));
+    for needle in [
+        "<super as crate::SelfTr>::f(",
+        "= super::super::helper_fn(",
+        "<super::super as crate::SupTr>::f(",
+        "<crate::Wrapper<crate::LocalItem> as crate::Tr>::f(",
+        "&crate::LocalRef",
+        "[* const crate::LocalPtr; 2]",
+        "[crate::LocalSlice]",
+        "(crate::LocalParen)",
+    ] {
+        assert!(w.contains(needle), "missing `{needle}` in wrappers:\n{w}");
+    }
+}
+
+#[test]
+fn emit_checks_math_int_carry_cross_limb_shift_and_match_int_const_run() {
+    let crate_src = r#"
+#![allow(dead_code)]
+#[cfg_attr(anneal, anneal::spec(
+    ensures(|r| r == match 1 { x @ u8::MAX => x.wrapping_add(1), x => x.wrapping_add(1) })
+))]
+pub fn match_const_fn() -> u8 { 2 }
+#[cfg_attr(anneal, anneal::spec(ensures(|r| math(r) == math(a) * math(b))))]
+pub fn mul_u64(a: u64, b: u64) -> u128 { (a as u128) * (b as u128) }
+#[cfg_attr(anneal, anneal::spec(ensures(|r| r == (x >> 1))))]
+pub fn shr_u64(x: u64) -> u64 { x >> 1 }
+"#;
+    let emitted = emit_ok(&[src("lib.rs", crate_src)]);
+    let driver = r#"
+#[test]
+fn verify_math_int_and_match_const_edges() {
+    assert_eq!(anneal_checks_wrappers::checked_match_const_fn(), 2u8);
+    assert!(!anneal_checks_wrappers::post_match_const_fn(0u8));
+    let full_prod = (u64::MAX as u128) * (u64::MAX as u128);
+    assert_eq!(anneal_checks_wrappers::checked_mul_u64(u64::MAX, u64::MAX), full_prod);
+    assert!(!anneal_checks_wrappers::post_mul_u64(u64::MAX, u64::MAX, 1u128));
+    assert_eq!(anneal_checks_wrappers::checked_shr_u64(1u64 << 32), 1u64 << 31);
+    assert!(!anneal_checks_wrappers::post_shr_u64(1u64 << 32, 0u64));
+}
+"#;
+    let harness = format!("{crate_src}\n{}\n{}\n{driver}", emitted.wrappers_rs, emitted.tests_rs);
+    let tmp = TempDir::new("rustc");
+    let rs_path = tmp.0.join("harness.rs");
+    let bin_path = tmp.0.join("harness_bin");
+    fs::write(&rs_path, &harness).expect("write harness");
+    let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
+    let comp = Command::new(&rustc)
+        .args([
+            "--edition=2021",
+            "--test",
+            "-D",
+            "warnings",
+            "--cfg",
+            "anneal_checks",
+            "--check-cfg=cfg(test)",
+            "--check-cfg=cfg(anneal)",
+            "--check-cfg=cfg(anneal_checks)",
+        ])
+        .arg(&rs_path)
+        .arg("-o")
+        .arg(&bin_path)
+        .output()
+        .expect("invoke rustc");
+    assert!(comp.status.success(), "rustc failed:\n{}", String::from_utf8_lossy(&comp.stderr));
+    let run = Command::new(&bin_path).output().expect("run compiled test binary");
+    assert!(run.status.success(), "binary failed:\n{}", String::from_utf8_lossy(&run.stdout));
+}
+
+#[test]
+fn closure_raw_ptr_vec_place_mention_and_v2_ret_mismatch_edges() {
+    let raw_ptr_ty = json!({"kind": "raw_ptr", "mutability": "shared", "pointee": {"kind": "str"}});
+    let u8_ty = json!({"kind": "int", "width": "i8", "signed": false});
+    let unit_ty = json!({"kind": "unit"});
+    let ref_str_ty = json!({"kind": "ref", "mutability": "shared", "pointee": {"kind": "str"}});
+
+    let vec_ptr_cap = json!({
+        "scope": "unit", "mir_profile_version": 2,
+        "bodies": [
+            {"identity": "v_ptr", "is_unsafe": false, "arg_count": 0,
+             "local_tys": [unit_ty, {"kind": "vec", "elem": raw_ptr_ty}]},
+            {"identity": "v_u8", "is_unsafe": false, "arg_count": 0,
+             "local_tys": [unit_ty, {"kind": "vec", "elem": u8_ty}]}
+        ]
+    })
+    .to_string();
+    let parsed_vec = parse_capture_json(&vec_ptr_cap).expect("parse vec capture");
+    assert!(parsed_vec.bodies[0].has_raw_ptr_local && !parsed_vec.bodies[1].has_raw_ptr_local);
+
+    let meta_cap = json!({
+        "program": {
+            "scope": "unit", "mir_profile_version": 2,
+            "bodies": [{
+                "identity": "meta_pm", "is_unsafe": false, "arg_count": 0,
+                "local_tys": [unit_ty, ref_str_ty, raw_ptr_ty],
+                "blocks": [{
+                    "statements": [
+                        {"kind": "assign", "local": 2, "value": {
+                            "kind": "fake_address_of",
+                            "place": {"local": 1, "projection": [{"kind": "deref"}]}
+                        }},
+                        {"kind": "place_mention", "place": {"local": 0, "projection": []}}
+                    ],
+                    "terminator": {"kind": "ret"}
+                }]
+            }]
+        }
+    })
+    .to_string();
+    assert!(!parse_capture_json(&meta_cap).expect("parse meta").bodies[0].has_raw_ptr_local);
+
+    let cap: CapturedProgramSummary = parse_capture_json(
+        &json!({
+            "scope": "unit", "mir_profile_version": 2,
+            "bodies": [{"identity": "mismatch", "is_unsafe": false, "arg_count": 1,
+                        "local_tys": [u8_ty, u8_ty]}]
+        })
+        .to_string(),
+    )
+    .expect("parse mismatch capture");
+    let spec = [src(
+        "lib.rs",
+        "#[cfg_attr(anneal, anneal::spec(ensures(|r| r == (x as u16))))]\n\
+         fn mismatch(x: u8) -> u16 { x as u16 }\n",
+    )];
+    let opts = Options {
+        format: Format::V2Specs,
+        scope: Scope::Unit,
+        capture: Some(cap),
+        ..Options::default()
+    };
+    let errs = lower_with(&spec, &opts).err().expect("expected signature mismatch");
+    assert_eq!(errs[0].diag.code, "E_ANNEAL_SIGNATURE_MISMATCH");
+
+    // Selected-target helper emission must follow dependency order (`z_leaf`
+    // before `a_mid`), opposing both name order and source order.
+    let order_src = [src(
+        "lib.rs",
+        "#[anneal::pure] fn a_mid(x: u8) -> u8 { z_leaf(x) }\n\
+         #[anneal::pure] fn z_leaf(x: u8) -> u8 { x }\n\
+         #[anneal::spec(requires(a_mid(x) == x))] fn entry(x: u8) {}\n",
+    )];
+    let ordered =
+        lower_with(&order_src, &Options { targets: vec!["entry".into()], ..Options::default() })
+            .unwrap_or_else(|e| panic!("lower target failed:\n{}", e[0].render(&order_src)));
+    let leaf_pos = ordered.spec_lean.find("def pure_z_leaf").expect("pure_z_leaf");
+    let mid_pos = ordered.spec_lean.find("def pure_a_mid").expect("pure_a_mid");
+    assert!(leaf_pos < mid_pos, "helpers emitted out of order:\n{}", ordered.spec_lean);
+}
+
+#[test]
+fn hint_sites_diag_and_cli_file_sort_edges() {
+    let sm_json = json!({
+        "schema_version": 1, "hint_mode": "compact",
+        "entries": [{
+            "body": "rust-path-v1::f", "block": 0, "stmt": 0, "macro_path": "crate::m",
+            "call_site": {"file": "src/lib.rs", "lo": 5, "hi": 5, "line": 1, "col": 6}
+        }]
+    })
+    .to_string();
+    assert!(HintSiteTable::from_json_str(&sm_json).is_ok(), "lo==hi span must be accepted");
+
+    let long_span = syn::parse_str::<syn::Ident>("long_identifier_past_eol").expect("ident").span();
+    let sp = SourceMap::new("x\ny").span(long_span);
+    assert_eq!(sp.end_byte, 3, "OOB col must clamp to text end, not line start");
+
+    let bin = env!("CARGO_BIN_EXE_anneal-spec-lower");
+    let tmp = TempDir::new("sort");
+    let (a_rs, b_rs) = (tmp.0.join("a.rs"), tmp.0.join("b.rs"));
+    let (o1, o2) = (tmp.0.join("out1"), tmp.0.join("out2"));
+    fs::write(&a_rs, "#[anneal::spec(bad_clause)] fn fa() {}\n").expect("write a.rs");
+    fs::write(&b_rs, "#[anneal::spec(bad_clause)] fn fb() {}\n").expect("write b.rs");
+
+    for (args, out_dir) in [(vec!["--out-dir"], &o1), (vec!["emit-checks", "--out-dir"], &o2)] {
+        let out = Command::new(bin)
+            .args(&args)
+            .arg(out_dir)
+            .arg(&b_rs)
+            .arg(&a_rs)
+            .output()
+            .expect("run anneal-spec-lower");
+        assert_eq!(out.status.code(), Some(1));
+        let stderr = String::from_utf8_lossy(&out.stderr);
+        let a_pos = stderr.find("a.rs").unwrap_or_else(|| panic!("missing a.rs in:\n{stderr}"));
+        let b_pos = stderr.find("b.rs").unwrap_or_else(|| panic!("missing b.rs in:\n{stderr}"));
+        assert!(a_pos < b_pos, "expected sorted diagnostic order (a before b):\n{stderr}");
+    }
+}