| // 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. | |
| //! End-to-end tests over RawCppBundle fixtures captured by a real | |
| //! `anneal-clang-dump` from `tests/fixtures/src/*.c` (see | |
| //! `README.md`). | |
| use std::path::PathBuf; | |
| use anneal_lower_cpp::{ | |
| ir::{Expr, Program, Proj, SignedOverflowMode, Terminator, Ty}, | |
| lower_bundle_json, lower_bundle_json_to_lean, EmitOptions, LowerError, Options, | |
| }; | |
| fn fixture_path(name: &str) -> PathBuf { | |
| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name) | |
| } | |
| fn fixture(name: &str) -> String { | |
| std::fs::read_to_string(fixture_path(&format!("{name}.json"))) | |
| .unwrap_or_else(|e| panic!("missing fixture {name}.json: {e}")) | |
| } | |
| fn lower(name: &str) -> Result<Program, LowerError> { | |
| lower_bundle_json(&fixture(name), &Options::default()) | |
| } | |
| fn edit(name: &str, f: impl FnOnce(&mut serde_json::Value)) -> String { | |
| let mut v: serde_json::Value = serde_json::from_str(&fixture(name)).unwrap(); | |
| f(&mut v); | |
| v.to_string() | |
| } | |
| #[track_caller] | |
| fn assert_unsequenced(name: &str) { | |
| match lower(name) { | |
| Err(LowerError::UnsequencedSideEffects { .. }) => {} | |
| other => panic!("{name}: expected UnsequencedSideEffects, got {other:?}"), | |
| } | |
| } | |
| // --------------------------- mandatory negatives --------------------------- | |
| #[test] | |
| fn rejects_unsequenced_read_and_write() { | |
| // x + (x = 1) | |
| assert_unsequenced("neg_unseq_assign_read"); | |
| } | |
| #[test] | |
| fn rejects_unsequenced_call_arguments() { | |
| // sink(++x, ++x) | |
| assert_unsequenced("neg_unseq_call_args"); | |
| } | |
| #[test] | |
| fn rejects_exceptions_policy() { | |
| match lower("neg_exceptions") { | |
| Err(LowerError::UnsupportedLangPolicy { .. }) => {} | |
| other => panic!("expected UnsupportedLangPolicy, got {other:?}"), | |
| } | |
| } | |
| #[test] | |
| fn rejects_subscript_with_postincrement_of_index() { | |
| // a[i] = i++ | |
| assert_unsequenced("neg_subscript_postinc"); | |
| } | |
| #[test] | |
| fn rejects_nested_assignment_to_same_variable() { | |
| // x = (x = 1) + 1 | |
| assert_unsequenced("neg_nested_assign"); | |
| } | |
| #[test] | |
| fn rejects_store_unsequenced_with_postincrement() { | |
| // x = x++ | |
| assert_unsequenced("neg_self_postinc"); | |
| } | |
| #[test] | |
| fn rejects_two_indeterminately_sequenced_calls() { | |
| // g() + h() | |
| assert_unsequenced("neg_two_calls"); | |
| } | |
| // ------------------------------- positives ------------------------------- | |
| #[test] | |
| fn accepts_single_side_effect_expressions() { | |
| // x = x + 1; x += 1; ++x; s1 += *buf++; p[i] = p[i] + 1; while (len > 0) | |
| let p = lower("pos_ssenf_ok").expect("pos_ssenf_ok must lower"); | |
| assert_eq!(p.bodies.len(), 1); | |
| assert!(!p.is_partial); | |
| } | |
| #[test] | |
| fn clean_adler32_lowers_to_expected_shape() { | |
| let p = lower("clean_adler32").expect("clean_adler32 must lower"); | |
| assert_eq!(p.entry_def_id, 0); | |
| assert_eq!(p.bodies.len(), 1); | |
| assert!(p.records.is_empty()); | |
| let b = &p.bodies[0]; | |
| assert_eq!(b.identity, "clean_adler32_update"); | |
| assert!(!b.is_external); | |
| // _0 return slot, _1.._3 parameters, then locals. | |
| assert_eq!(b.locals[0].ty, b.sig.ret); | |
| assert!(!b.locals[0].is_param); | |
| assert!(b.locals[1..=3].iter().all(|l| l.is_param)); | |
| assert!(b.locals[4..].iter().all(|l| !l.is_param)); | |
| let u8_char = | |
| Ty::Int(anneal_lower_cpp::ir::Width::W8, anneal_lower_cpp::ir::Sign::Unsigned, true); | |
| assert_eq!(b.sig.params[1], Ty::Ptr(Box::new(u8_char), true, false, false)); | |
| // Two loops: two back edges to loop headers and one `ret`. | |
| let rets = b.blocks.iter().filter(|blk| blk.term == Terminator::Ret).count(); | |
| assert_eq!(rets, 1); | |
| // `*buf++` reads through a dereference projection. | |
| let derefs = format!("{:?}", b.blocks).matches("Deref").count(); | |
| assert!(derefs >= 1); | |
| assert_eq!(p.policy.signed_overflow, SignedOverflowMode::IsoUB); | |
| assert!(p.policy.exceptions_off); | |
| assert!(p.policy.little_endian); | |
| } | |
| #[test] | |
| fn control_flow_is_explicit() { | |
| let p = lower("pos_control_flow").expect("pos_control_flow must lower"); | |
| let b = &p.bodies[0]; | |
| let branches = b.blocks.iter().filter(|blk| matches!(blk.term, Terminator::Branch(..))).count(); | |
| // for-cond, 2x if, ||, &&, ?:, do-while cond (&&, !), 3 switch cases. | |
| assert!(branches >= 10, "only {branches} branches"); | |
| for (i, blk) in b.blocks.iter().enumerate() { | |
| let succ = match &blk.term { | |
| Terminator::Goto(t) => vec![*t], | |
| Terminator::Branch(_, t, f) => vec![*t, *f], | |
| Terminator::Call(_, _, _, n) => vec![*n], | |
| Terminator::Ret | Terminator::Unreachable => vec![], | |
| }; | |
| for s in succ { | |
| assert!(s < b.blocks.len(), "bb{i} jumps to missing bb{s}"); | |
| } | |
| } | |
| } | |
| #[test] | |
| fn struct_fields_and_direct_calls() { | |
| let p = lower("pos_struct_ptr").expect("pos_struct_ptr must lower"); | |
| assert_eq!(p.bodies.len(), 2); | |
| assert_eq!(p.bodies[0].identity, "pos_struct_ptr"); | |
| assert_eq!(p.bodies[1].identity, "mix"); | |
| assert_eq!(p.records.len(), 1); | |
| let r = &p.records[0]; | |
| assert_eq!(r.record_id, "struct.pair"); | |
| assert_eq!((r.size_bytes, r.align_bytes), (8, 4)); | |
| assert_eq!(r.fields[1].offset_bits, 32); | |
| let calls: Vec<_> = p.bodies[0] | |
| .blocks | |
| .iter() | |
| .filter_map(|b| match &b.term { | |
| Terminator::Call(c, args, dst, _) => Some((c.clone(), args.len(), dst.is_some())), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!(calls, vec![("mix".to_owned(), 2, true)]); | |
| let dbg = format!("{:?}", p.bodies[0].blocks); | |
| assert!(dbg.contains("Field(\"struct.pair\", 1")); | |
| let _ = (Proj::Deref, Expr::ConstBool(true)); | |
| } | |
| #[test] | |
| fn large_bodies_are_hoisted_into_bounded_chunks() { | |
| let mut p = lower("clean_adler32").expect("clean_adler32 must lower"); | |
| let b = &mut p.bodies[0]; | |
| let local = b.locals[4].clone(); | |
| let first_new = b.locals.len(); | |
| for _ in 0..700 { | |
| b.locals.push(local.clone()); | |
| } | |
| for id in first_new..first_new + 700 { | |
| b.blocks[0].stmts.push(anneal_lower_cpp::ir::Stmt::StorageLive(id)); | |
| } | |
| let lean = p.lean(&anneal_lower_cpp::ir::EmitMeta { | |
| namespace: "CapturedCpp", | |
| tu_main_file: "synthetic.c", | |
| target_triple: "x86_64-unknown-linux-gnu", | |
| lang_standard: "c11", | |
| }); | |
| assert!(lean.contains("def body_0_clean_adler32_update_locals_0 : List CppLocalDecl")); | |
| assert!(lean.contains("def body_0_clean_adler32_update_bb0_stmts_0 : List CppStmt")); | |
| // Every hoisted leaf holds at most `LEAF_LEN` elements. | |
| for def in lean.split("\ndef ").filter(|d| d.contains("_locals_") || d.contains("_stmts_")) { | |
| let body = def.split(":= [").nth(1).unwrap_or(""); | |
| let body = body.split("\n]").next().unwrap_or(""); | |
| assert!(body.matches(",\n").count() < anneal_lower_common::chunk::LEAF_LEN, "{def}"); | |
| } | |
| if let Some(dir) = std::env::var_os("ANNEAL_LOWER_CPP_DUMP_DIR") { | |
| std::fs::write(std::path::Path::new(&dir).join("LargeCapturedCpp.lean"), &lean).unwrap(); | |
| } | |
| } | |
| #[path = "pipeline/abi_and_bundle_guards.rs"] | |
| mod abi_and_bundle_guards; | |
| #[path = "pipeline/c_policy_and_globals.rs"] | |
| mod c_policy_and_globals; | |
| #[path = "pipeline/cxx.rs"] | |
| mod cxx; |