blob: 122cdd11a7cfac3fd72038bcc98e81f47be7b4e9 [file]
// 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.
//! Constructs that real C11 and C++20 code needs beyond the first two rungs:
//! comparisons used as `int`, brace initializers and compound literals,
//! read-only static locals, externalized callees, block-scope lifetimes,
//! `std::nullptr_t`, and `--entry` reachability. Every fixture is captured
//! from `tests/fixtures/src/` as described in `README.md`.
#![recursion_limit = "256"]
use std::path::PathBuf;
use anneal_lower_cpp::{
ir::{BinOp, Body, Expr, Program, Sign, Stmt, Terminator, Ty, Width},
lower_bundle_json, lower_bundle_json_to_lean, EmitOptions, LowerError, Options,
};
#[path = "gaps/c11_and_static_locals.rs"]
mod c11_and_static_locals;
#[path = "gaps/cxx_and_jump_rejections.rs"]
mod cxx_and_jump_rejections;
fn fixture(name: &str) -> String {
let path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("tests/fixtures/{name}.json"));
std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("missing fixture {name}.json: {e}"))
}
fn lower_entry(name: &str, entry: Option<&str>) -> Result<Program, LowerError> {
lower_bundle_json(&fixture(name), &Options { entry: entry.map(str::to_owned) })
}
fn lower_ok(name: &str) -> Program {
lower_entry(name, None).unwrap_or_else(|e| panic!("{name}: {e}"))
}
fn body<'p>(p: &'p Program, symbol: &str) -> &'p Body {
p.bodies.iter().find(|b| b.identity == symbol).unwrap_or_else(|| panic!("no body `{symbol}`"))
}
fn local(b: &Body, name: &str) -> usize {
b.locals
.iter()
.position(|l| l.debug_name == name)
.unwrap_or_else(|| panic!("no local `{name}`"))
}
/// Every expression in `b`, including subexpressions.
fn exprs(b: &Body) -> Vec<&Expr> {
fn walk<'e>(e: &'e Expr, out: &mut Vec<&'e Expr>) {
out.push(e);
match e {
Expr::ConstInt(..)
| Expr::ConstBool(_)
| Expr::NullPtr(_)
| Expr::ReadPlace(..)
| Expr::AddrOf(..) => {}
Expr::Unary(_, _, a)
| Expr::IntCast(.., a)
| Expr::IntToBool(a)
| Expr::BoolToInt(_, _, a)
| Expr::PtrCast(_, a)
| Expr::BitCast(_, _, a) => walk(a, out),
Expr::Binary(_, _, a, c) | Expr::PtrAdd(_, _, a, c) => {
walk(a, out);
walk(c, out);
}
}
}
let mut out = Vec::new();
for blk in &b.blocks {
for s in &blk.stmts {
if let Stmt::Assign(_, _, e) = s {
walk(e, &mut out);
}
}
match &blk.term {
Terminator::Branch(c, ..) => walk(c, &mut out),
Terminator::Call(_, args, ..) => args.iter().for_each(|a| walk(a, &mut out)),
_ => {}
}
}
out
}
fn stmts(b: &Body) -> impl Iterator<Item = &Stmt> {
b.blocks.iter().flat_map(|blk| blk.stmts.iter())
}
fn storage_dead_count(b: &Body, l: usize) -> usize {
stmts(b).filter(|s| matches!(s, Stmt::StorageDead(x) if *x == l)).count()
}
fn is_cmp(op: &BinOp) -> bool {
matches!(op, BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge)
}
#[track_caller]
fn assert_unsupported(r: Result<Program, LowerError>, needle: &str) {
match r {
Err(LowerError::UnsupportedConstruct { detail }) if detail.contains(needle) => {}
other => panic!("expected UnsupportedConstruct mentioning `{needle}`, got {other:?}"),
}
}
/// Edits the first `decl_stmt` named `name` in the fixture.
fn edit_decl(fixture_name: &str, name: &str, f: impl Fn(&mut serde_json::Value)) -> String {
fn find<'v>(v: &'v mut serde_json::Value, name: &str) -> Option<&'v mut serde_json::Value> {
let is_decl = v.get("kind").and_then(|k| k.as_str()) == Some("decl_stmt")
&& v.get("name").and_then(|n| n.as_str()) == Some(name);
if is_decl {
return Some(v);
}
match v {
serde_json::Value::Object(m) => m.values_mut().find_map(|c| find(c, name)),
serde_json::Value::Array(a) => a.iter_mut().find_map(|c| find(c, name)),
_ => None,
}
}
let mut v: serde_json::Value = serde_json::from_str(&fixture(fixture_name)).unwrap();
f(find(&mut v, name).unwrap_or_else(|| panic!("no declaration `{name}`")));
v.to_string()
}
// ------------------------------ C11 -----------------------------------------
#[test]
fn c11_comparisons_are_bool_valued_and_converted_to_int() {
c11_and_static_locals::c11_comparisons_are_bool_valued_and_converted_to_int();
}
#[test]
fn c11_init_lists_and_compound_literals_initialize_fieldwise() {
c11_and_static_locals::c11_init_lists_and_compound_literals_initialize_fieldwise();
}
#[test]
fn rejects_short_array_initializer_list_without_filler() {
c11_and_static_locals::rejects_short_array_initializer_list_without_filler();
}
#[test]
fn c11_static_const_locals_are_initialized_on_entry() {
c11_and_static_locals::c11_static_const_locals_are_initialized_on_entry();
}
#[test]
fn rejects_static_local_whose_address_escapes() {
c11_and_static_locals::rejects_static_local_whose_address_escapes();
}
#[test]
fn rejects_mutable_static_local() {
c11_and_static_locals::rejects_mutable_static_local();
}
#[test]
fn rejects_static_local_without_constant_initializer() {
c11_and_static_locals::rejects_static_local_without_constant_initializer();
}
#[test]
fn externalized_callee_is_declared_without_its_body() {
c11_and_static_locals::externalized_callee_is_declared_without_its_body();
}
#[test]
fn c_block_locals_die_on_every_exit_of_their_scope() {
c11_and_static_locals::c_block_locals_die_on_every_exit_of_their_scope();
}
// ------------------------------ C++20 ---------------------------------------
#[test]
fn cxx_nullptr_t_values_are_null_pointers_that_are_never_read() {
cxx_and_jump_rejections::cxx_nullptr_t_values_are_null_pointers_that_are_never_read();
}
#[test]
fn cxx_deduction_guides_scoped_enums_and_void_statements_lower() {
cxx_and_jump_rejections::cxx_deduction_guides_scoped_enums_and_void_statements_lower();
}
#[test]
fn entry_lowers_only_functions_it_can_reach() {
cxx_and_jump_rejections::entry_lowers_only_functions_it_can_reach();
}
#[test]
fn goto_leaving_blocks_ends_their_lifetimes() {
cxx_and_jump_rejections::goto_leaving_blocks_ends_their_lifetimes();
}
#[test]
fn rejects_jumps_past_declarations() {
cxx_and_jump_rejections::rejects_jumps_past_declarations();
}
#[test]
fn rejects_pointer_subtraction_of_unrepresentable_offsets() {
cxx_and_jump_rejections::rejects_pointer_subtraction_of_unrepresentable_offsets();
}
#[test]
fn cxx_aliases_through_references_and_assignments_are_memory() {
cxx_and_jump_rejections::cxx_aliases_through_references_and_assignments_are_memory();
}
#[test]
fn cxx_rejects_side_effects_in_null_pointer_constants() {
cxx_and_jump_rejections::cxx_rejects_side_effects_in_null_pointer_constants();
}
#[test]
fn cxx_rejects_by_value_records_that_are_not_trivially_copyable() {
cxx_and_jump_rejections::cxx_rejects_by_value_records_that_are_not_trivially_copyable();
}
#[test]
fn emitted_comments_and_strings_cannot_be_escaped() {
cxx_and_jump_rejections::emitted_comments_and_strings_cannot_be_escaped();
}
// --------------------- Gate-2 Round 1 regressions --------------------------
/// Fills `is_const` defaults on legacy synthetic test fixtures built by
/// `c11_bundle` / `cxx20_bundle` when a test does not specify `is_const`
/// explicitly. Real bundles and dedicated schema tests exercise strict
/// `is_const` parsing directly.
fn fill_synthetic_is_const(v: &mut serde_json::Value) {
fn visit_node(n: &mut serde_json::Value) {
match n {
serde_json::Value::Object(o) => {
let kind = o.get("kind").and_then(|k| k.as_str());
if kind == Some("decl_stmt") && !o.contains_key("is_const") {
let is_static_const =
o.get("is_static_const").and_then(|b| b.as_bool()).unwrap_or(false);
o.insert("is_const".into(), is_static_const.into());
} else if matches!(
kind,
Some(
"compound_literal"
| "materialize_temporary"
| "bind_temporary"
| "construct"
| "init_list"
)
) && !o.contains_key("is_const")
{
o.insert("is_const".into(), false.into());
}
for val in o.values_mut() {
visit_node(val);
}
}
serde_json::Value::Array(arr) => {
for item in arr {
visit_node(item);
}
}
_ => {}
}
}
if let Some(records) = v.get_mut("records").and_then(|r| r.as_array_mut()) {
for r in records {
if let Some(fields) = r.get_mut("fields").and_then(|f| f.as_array_mut()) {
for f in fields {
if let Some(fo) = f.as_object_mut() {
fo.entry("is_const").or_insert_with(|| false.into());
}
}
}
}
}
if let Some(functions) = v.get_mut("functions").and_then(|f| f.as_array_mut()) {
for func in functions {
if let Some(params) = func.get_mut("params").and_then(|p| p.as_array_mut()) {
for p in params {
if let Some(po) = p.as_object_mut() {
if !po.contains_key("is_const") {
let is_this =
po.get("is_this").and_then(|b| b.as_bool()).unwrap_or(false);
po.insert("is_const".into(), is_this.into());
}
}
}
}
if let Some(body) = func.get_mut("body_stmt") {
visit_node(body);
}
}
}
}
fn c11_bundle(records: serde_json::Value, functions: serde_json::Value) -> String {
let mut v = serde_json::json!({
"schema_version": 1,
"tu_main_file": "synthetic.c",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": false,
"lang_standard": "c11",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": records,
"functions": functions
});
fill_synthetic_is_const(&mut v);
v.to_string()
}
fn cxx20_bundle(records: serde_json::Value, functions: serde_json::Value) -> String {
let mut v = serde_json::json!({
"schema_version": 1,
"tu_main_file": "synthetic.cc",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": true,
"lang_standard": "c++20",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": records,
"functions": functions
});
fill_synthetic_is_const(&mut v);
v.to_string()
}
fn i32_ty() -> serde_json::Value {
serde_json::json!({"kind": "int", "bits": 32, "signed": true, "is_char_like": false})
}
fn u32_ty() -> serde_json::Value {
serde_json::json!({"kind": "int", "bits": 32, "signed": false, "is_char_like": false})
}
fn int_lit(v: i64) -> serde_json::Value {
serde_json::json!({
"kind": "int_lit",
"ty": i32_ty(),
"value_category": "prvalue",
"value_str": v.to_string(),
"bits": 32,
"signed": true
})
}
/// Checks that every root-to-return path through `b` executes `StorageLive(l)`
/// and `StorageDead(l)` in strict 1-to-1 alternation (never live twice, never
/// dead without being live).
fn assert_balanced_storage_on_all_paths(b: &Body, l: usize) {
fn dfs(b: &Body, bb: usize, mut live: bool, l: usize, path: &mut Vec<usize>) {
for s in &b.blocks[bb].stmts {
match s {
Stmt::StorageLive(x) if *x == l => {
assert!(!live, "double StorageLive(_{l}) along {path:?} -> bb{bb}: {b:?}");
live = true;
}
Stmt::StorageDead(x) if *x == l => {
assert!(live, "unpaired StorageDead(_{l}) along {path:?} -> bb{bb}: {b:?}");
live = false;
}
_ => {}
}
}
path.push(bb);
let succs = match &b.blocks[bb].term {
Terminator::Goto(t) => vec![*t],
Terminator::Branch(_, t, f) => vec![*t, *f],
Terminator::Call(_, _, _, n) => vec![*n],
Terminator::Ret => {
assert!(!live, "_{l} still live at Ret along {path:?}: {b:?}");
path.pop();
return;
}
Terminator::Unreachable => {
path.pop();
return;
}
};
for nx in succs {
// Unroll back-edges at most twice (0, 1, and 2 loop iterations).
if path.iter().filter(|&&p| p == nx).count() <= 2 {
dfs(b, nx, live, l, path);
}
}
path.pop();
}
dfs(b, b.entry_block, false, l, &mut Vec::new());
}
#[test]
fn rejects_static_const_with_mutable_field() {
// Direct `has_mutable` record on a hoisted `static const` local.
let rec_s = serde_json::json!({
"id": "struct.MutBox",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"has_mutable": true,
"is_trivially_copyable": true,
"fields": [{"name": "n", "offset_bits": 0, "bit_width": null, "ty": i32_ty()}]
});
let rec_outer = serde_json::json!({
"id": "struct.Outer",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"has_mutable": false,
"is_trivially_copyable": true,
"fields": [{
"name": "inner",
"offset_bits": 0,
"bit_width": null,
"ty": {"kind": "record", "id": "struct.MutBox"}
}]
});
let make_fn = |rec_id: &str, write_field: bool, has_mutable_flag: bool| {
let mut s_rec = rec_s.clone();
s_rec["has_mutable"] = has_mutable_flag.into();
let rec_ty = serde_json::json!({"kind": "record", "id": rec_id});
let init = if rec_id == "struct.Outer" {
serde_json::json!({
"kind": "init_list",
"ty": rec_ty,
"value_category": "prvalue",
"inits": [{
"kind": "init_list",
"ty": {"kind": "record", "id": "struct.MutBox"},
"value_category": "prvalue",
"inits": [int_lit(0)]
}]
})
} else {
serde_json::json!({
"kind": "init_list",
"ty": rec_ty,
"value_category": "prvalue",
"inits": [int_lit(0)]
})
};
let member_n = serde_json::json!({
"kind": "member",
"ty": i32_ty(),
"value_category": "lvalue",
"base": {
"kind": "var_ref",
"ty": {"kind": "record", "id": "struct.MutBox"},
"value_category": "lvalue",
"var_id": 0,
"is_param": false,
"param_idx": null,
"is_ref_binding": false
},
"is_arrow": false,
"field_name": "n",
"record_id": "struct.MutBox",
"field_idx": 0,
"is_bitfield": false
});
let ret_expr = if write_field {
serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "unary_op",
"op": "pre_inc",
"ty": i32_ty(),
"value_category": "lvalue",
"sub": member_n
}
})
} else {
int_lit(1)
};
cxx20_bundle(
serde_json::json!([s_rec, rec_outer]),
serde_json::json!([{
"symbol": "_Z1fv",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "s",
"ty": rec_ty,
"is_static_const": true,
"init": init
},
{"kind": "return", "expr": ret_expr}
]
}
}]),
)
};
assert_unsupported(
lower_bundle_json(&make_fn("struct.MutBox", false, true), &Options::default()),
"mutable",
);
// Transitive `has_mutable` through an enclosing record.
assert_unsupported(
lower_bundle_json(&make_fn("struct.Outer", false, true), &Options::default()),
"mutable",
);
// Even without `has_mutable`, writing to a hoisted static fails closed.
assert_unsupported(
lower_bundle_json(&make_fn("struct.MutBox", true, false), &Options::default()),
"modified",
);
}
#[test]
fn cxx_conditional_trivial_temp_balances_storage_live_and_dead() {
// `return c ? S{1}.get() : 0;` where `S` has a trivial destructor.
let s_ty = serde_json::json!({"kind": "record", "id": "struct.S"});
let s_ptr_ty = serde_json::json!({
"kind": "ptr",
"pointee": s_ty,
"is_const": true,
"is_restrict": false,
"may_alias": false
});
let bundle = cxx20_bundle(
serde_json::json!([{
"id": "struct.S",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_trivially_copyable": true,
"fields": [{"name": "x", "offset_bits": 0, "bit_width": null, "ty": i32_ty()}]
}]),
serde_json::json!([
{
"symbol": "_Z1fb",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "c", "ty": {"kind": "bool"}}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "extend_int", "bits": 1}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "return",
"expr": {
"kind": "expr_with_cleanups",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "conditional",
"ty": i32_ty(),
"value_category": "prvalue",
"cond": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": {"kind": "bool"},
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": {"kind": "bool"},
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
},
"then_expr": {
"kind": "call",
"ty": i32_ty(),
"value_category": "prvalue",
"callee_symbol": "_ZNK1S3getEv",
"is_indirect": false,
"implicit_object": {
"kind": "materialize_temporary",
"ty": s_ty,
"value_category": "xvalue",
"lifetime_extended": false,
"sub": {
"kind": "init_list",
"ty": s_ty,
"value_category": "prvalue",
"inits": [int_lit(1)]
}
},
"implicit_object_is_ptr": false,
"args": [],
"param_is_ref": []
},
"else_expr": int_lit(0)
}
}
}]
}
},
{
"symbol": "_ZNK1S3getEv",
"unmangled_name": "get",
"method_kind": "method",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "this", "ty": s_ptr_ty, "is_this": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{"kind": "return", "expr": int_lit(1)}]
}
}
]),
);
let p = lower_bundle_json(&bundle, &Options::default()).expect("must lower");
let b = body(&p, "_Z1fb");
let s_temp = b
.locals
.iter()
.position(|l| l.ty == Ty::Record("struct.S".into()))
.expect("materialized S temporary");
assert_balanced_storage_on_all_paths(b, s_temp);
}
#[test]
fn c11_compound_literals_respect_substatement_scopes_and_reject_conditionals() {
let i32_ptr = serde_json::json!({
"kind": "ptr",
"pointee": i32_ty(),
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let compound_lit = serde_json::json!({
"kind": "compound_literal",
"ty": i32_ty(),
"value_category": "lvalue",
"is_file_scope": false,
"init": int_lit(1)
});
let addr_of_lit = serde_json::json!({
"kind": "unary_op",
"op": "addr_of",
"ty": i32_ptr,
"value_category": "prvalue",
"sub": compound_lit
});
// 1. `if (c) p = &(int){1}; return p != 0;`
let if_bundle = c11_bundle(
serde_json::json!([]),
serde_json::json!([{
"symbol": "if_subscope",
"unmangled_name": "if_subscope",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "c", "ty": i32_ty()}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 1,
"name": "p",
"ty": i32_ptr,
"init": {
"kind": "cast",
"cast_kind": "null_to_pointer",
"ty": i32_ptr,
"value_category": "prvalue",
"sub": int_lit(0)
}
},
{
"kind": "if",
"cond": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
},
"then_branch": {
"kind": "expr_stmt",
"expr": {
"kind": "binary_op",
"op": "assign",
"ty": i32_ptr,
"value_category": "prvalue",
"lhs": {
"kind": "var_ref",
"ty": i32_ptr,
"value_category": "lvalue",
"var_id": 1,
"is_param": false,
"param_idx": null
},
"rhs": addr_of_lit
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
);
let p_if = lower_bundle_json(&if_bundle, &Options::default()).expect("if_subscope must lower");
let b_if = body(&p_if, "if_subscope");
let lit_local = (0..b_if.locals.len())
.find(|&l| b_if.locals[l].debug_name.starts_with("tmp") && b_if.locals[l].ty == Ty::I32)
.expect("compound literal temp");
assert_balanced_storage_on_all_paths(b_if, lit_local);
// `StorageDead` must run in the `then` block, not the final return block.
let ret_bb = b_if.blocks.iter().find(|blk| blk.term == Terminator::Ret).unwrap();
assert!(!ret_bb.stmts.contains(&Stmt::StorageDead(lit_local)), "{b_if:?}");
// 2. `while (n--) sink(&(int){1});`
let while_bundle = c11_bundle(
serde_json::json!([]),
serde_json::json!([
{
"symbol": "while_subscope",
"unmangled_name": "while_subscope",
"is_definition": true,
"return_ty": {"kind": "void"},
"params": [{"name": "n", "ty": i32_ty()}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "while",
"cond": {
"kind": "unary_op",
"op": "post_dec",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
},
"body": {
"kind": "expr_stmt",
"expr": {
"kind": "call",
"ty": {"kind": "void"},
"value_category": "prvalue",
"callee_symbol": "sink",
"is_indirect": false,
"args": [addr_of_lit]
}
}
}]
}
},
{
"symbol": "sink",
"unmangled_name": "sink",
"is_definition": false,
"return_ty": {"kind": "void"},
"params": [{"name": "p", "ty": i32_ptr}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": null
}
]),
);
let p_w = lower_bundle_json(&while_bundle, &Options::default()).expect("while_subscope");
let b_w = body(&p_w, "while_subscope");
let w_lit = (0..b_w.locals.len())
.find(|&l| b_w.blocks.iter().any(|blk| blk.stmts.contains(&Stmt::StorageLive(l))))
.expect("while compound literal");
assert_balanced_storage_on_all_paths(b_w, w_lit);
// 3. Braceless `switch (x) case 0: sink(&(int){1});`
let switch_bundle = c11_bundle(
serde_json::json!([]),
serde_json::json!([
{
"symbol": "switch_subscope",
"unmangled_name": "switch_subscope",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "x", "ty": i32_ty()}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "switch",
"cond": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
},
"body": {
"kind": "case",
"value_str": "0",
"sub": {
"kind": "expr_stmt",
"expr": {
"kind": "call",
"ty": {"kind": "void"},
"value_category": "prvalue",
"callee_symbol": "sink",
"is_indirect": false,
"args": [addr_of_lit]
}
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
{
"symbol": "sink",
"unmangled_name": "sink",
"is_definition": false,
"return_ty": {"kind": "void"},
"params": [{"name": "p", "ty": i32_ptr}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": null
}
]),
);
let p_sw =
lower_bundle_json(&switch_bundle, &Options::default()).expect("switch_subscope must lower");
let b_sw = body(&p_sw, "switch_subscope");
let sw_lit = (0..b_sw.locals.len())
.find(|&l| b_sw.blocks.iter().any(|blk| blk.stmts.contains(&Stmt::StorageLive(l))))
.expect("switch compound literal");
assert_balanced_storage_on_all_paths(b_sw, sw_lit);
let sw_ret_bb = b_sw.blocks.iter().find(|blk| blk.term == Terminator::Ret).unwrap();
assert!(!sw_ret_bb.stmts.contains(&Stmt::StorageDead(sw_lit)), "{b_sw:?}");
// 4. `c ? &(int){1} : 0` must fail closed.
let cond_lit_bundle = c11_bundle(
serde_json::json!([]),
serde_json::json!([{
"symbol": "cond_lit",
"unmangled_name": "cond_lit",
"is_definition": true,
"return_ty": i32_ptr,
"params": [{"name": "c", "ty": i32_ty()}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "direct_ptr"}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "return",
"expr": {
"kind": "conditional",
"ty": i32_ptr,
"value_category": "prvalue",
"cond": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
},
"then_expr": addr_of_lit,
"else_expr": {
"kind": "cast",
"cast_kind": "null_to_pointer",
"ty": i32_ptr,
"value_category": "prvalue",
"sub": int_lit(0)
}
}
}]
}
}]),
);
assert_unsupported(
lower_bundle_json(&cond_lit_bundle, &Options::default()),
"conditionally evaluated compound literal",
);
}
#[test]
fn c11_bitfield_store_truncates_value_and_incdec_promotes_narrow_bitfield() {
use anneal_lower_cpp::ir::Proj;
let bf_rec = serde_json::json!({
"id": "struct.BF",
"is_union": false,
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{"name": "b3", "offset_bits": 0, "bit_width": 3, "ty": u32_ty()},
{"name": "b31", "offset_bits": 32, "bit_width": 31, "ty": u32_ty()}
]
});
let s_ptr_ty = serde_json::json!({
"kind": "ptr",
"pointee": {"kind": "record", "id": "struct.BF"},
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let s_ref = serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": s_ptr_ty,
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": s_ptr_ty,
"value_category": "lvalue",
"var_id": 0,
"is_param": true,
"param_idx": 0
}
});
let bf_member = |name: &str, idx: u32, off: u64, width: u64| {
serde_json::json!({
"kind": "member",
"ty": u32_ty(),
"value_category": "lvalue",
"base": s_ref,
"is_arrow": true,
"field_name": name,
"record_id": "struct.BF",
"field_idx": idx,
"is_bitfield": true,
"bit_offset": off,
"bit_width": width,
"field_is_signed": false
})
};
let bundle = c11_bundle(
serde_json::json!([bf_rec]),
serde_json::json!([{
"symbol": "bf_ops",
"unmangled_name": "bf_ops",
"is_definition": true,
"return_ty": u32_ty(),
"params": [{"name": "s", "ty": s_ptr_ty}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "expr_stmt",
"expr": {
"kind": "unary_op",
"op": "pre_inc",
"ty": u32_ty(),
"value_category": "prvalue",
"sub": bf_member("b31", 1, 32, 31)
}
},
{
"kind": "return",
"expr": {
"kind": "binary_op",
"op": "assign",
"ty": u32_ty(),
"value_category": "prvalue",
"lhs": bf_member("b3", 0, 0, 3),
"rhs": {
"kind": "int_lit",
"ty": u32_ty(),
"value_category": "prvalue",
"value_str": "10",
"bits": 32,
"signed": false
}
}
}
]
}
}]),
);
let p = lower_bundle_json(&bundle, &Options::default()).expect("bf_ops must lower");
let b = body(&p, "bf_ops");
// 1. `++s->b31` (`uint32_t b31 : 31`) must promote to signed `Ty::I32`!
assert!(
exprs(b).iter().any(|e| matches!(e, Expr::Binary(BinOp::Add, Ty::I32, ..))),
"31-bit unsigned bit-field increment must promote to signed int32: {b:?}"
);
// 2. `return (s->b3 = 10);` must write the bit-field FIRST and then read
// back the truncated bit-field place (not return the untruncated `10`)!
let stmts_vec: Vec<_> = stmts(b).collect();
let store_pos = stmts_vec
.iter()
.position(|s| {
matches!(s, Stmt::Assign(pl, _, Expr::ConstInt(_, _, _, 10))
if matches!(pl.projs.last(), Some(Proj::Bitfield(_, 0, 0, 3, false))))
})
.expect("bit-field store of 10");
let readback_pos = stmts_vec
.iter()
.position(|s| {
matches!(s, Stmt::Assign(dst, _, Expr::ReadPlace(src, _))
if dst.projs.is_empty()
&& matches!(src.projs.last(), Some(Proj::Bitfield(_, 0, 0, 3, false))))
})
.expect("truncated bit-field readback");
assert!(store_pos < readback_pos, "{stmts_vec:?}");
}
#[test]
fn rejects_unsequenced_nontrivial_temp_dtors() {
let log_ty = serde_json::json!({"kind": "record", "id": "struct.Log"});
let log_temp = |tag: i64| {
serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "member",
"ty": i32_ty(),
"value_category": "lvalue",
"base": {
"kind": "materialize_temporary",
"ty": log_ty,
"value_category": "xvalue",
"lifetime_extended": false,
"sub": {
"kind": "bind_temporary",
"ty": log_ty,
"value_category": "prvalue",
"dtor_symbol": "_ZN3LogD1Ev",
"sub": {
"kind": "init_list",
"ty": log_ty,
"value_category": "prvalue",
"inits": [int_lit(tag)]
}
}
},
"is_arrow": false,
"field_name": "tag",
"record_id": "struct.Log",
"field_idx": 0,
"is_bitfield": false
}
})
};
let make = |ret_expr: serde_json::Value| {
cxx20_bundle(
serde_json::json!([{
"id": "struct.Log",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_trivially_copyable": false,
"dtor_symbol": "_ZN3LogD1Ev",
"fields": [{"name": "tag", "offset_bits": 0, "bit_width": null, "ty": i32_ty()}]
}]),
serde_json::json!([
{
"symbol": "_Z4testv",
"unmangled_name": "test",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "return",
"expr": {
"kind": "expr_with_cleanups",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": ret_expr
}
}]
}
},
{
"symbol": "_ZN3LogD1Ev",
"unmangled_name": "~Log",
"method_kind": "dtor",
"is_definition": false,
"return_ty": {"kind": "void"},
"params": [{
"name": "this",
"is_this": true,
"ty": {
"kind": "ptr",
"pointee": log_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
}
}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": null
},
{
"symbol": "_Z4sinkii",
"unmangled_name": "sink",
"is_definition": false,
"return_ty": i32_ty(),
"params": [{"name": "a", "ty": i32_ty()}, {"name": "b", "ty": i32_ty()}],
"abi_witness": {
"cc": "c",
"param_passing": [
{"kind": "direct_int", "bits": 32},
{"kind": "direct_int", "bits": 32}
],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": null
}
]),
)
};
// 1. `Log{1}.tag + Log{2}.tag`
let add_expr = serde_json::json!({
"kind": "binary_op",
"op": "add",
"ty": i32_ty(),
"value_category": "prvalue",
"lhs": log_temp(1),
"rhs": log_temp(2)
});
assert!(matches!(
lower_bundle_json(&make(add_expr), &Options::default()),
Err(LowerError::UnsequencedSideEffects { .. })
));
// 2. `sink(Log{1}.tag, Log{2}.tag)`
let call_expr = serde_json::json!({
"kind": "call",
"ty": i32_ty(),
"value_category": "prvalue",
"callee_symbol": "_Z4sinkii",
"is_indirect": false,
"args": [log_temp(1), log_temp(2)],
"param_is_ref": [false, false]
});
assert!(matches!(
lower_bundle_json(&make(call_expr), &Options::default()),
Err(LowerError::UnsequencedSideEffects { .. })
));
}
#[test]
fn rejects_by_value_record_observing_this() {
let sp_ty = serde_json::json!({"kind": "record", "id": "struct.SelfPtr"});
let sp_ptr = serde_json::json!({
"kind": "ptr",
"pointee": sp_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let make_bundle = |has_flag: bool, include_ctor_body: bool| {
let mut funcs = vec![serde_json::json!({
"symbol": "_Z4makev",
"unmangled_name": "make",
"is_definition": true,
"return_ty": sp_ty,
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_ptr"}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "return",
"expr": {
"kind": "construct",
"ty": sp_ty,
"value_category": "prvalue",
"ctor_symbol": "_ZN7SelfPtrC1Ev",
"record_id": "struct.SelfPtr",
"is_trivial": false,
"is_default": true,
"construction_kind": "complete",
"args": [],
"param_is_ref": []
}
}]
}
})];
funcs.push(serde_json::json!({
"symbol": "_ZN7SelfPtrC1Ev",
"unmangled_name": "SelfPtr",
"method_kind": "ctor",
"is_trivial": false,
"is_definition": include_ctor_body,
"return_ty": {"kind": "void"},
"params": [{"name": "this", "ty": sp_ptr, "is_this": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"ctor_inits": if include_ctor_body {
serde_json::json!([{
"kind": "field",
"record_id": "struct.SelfPtr",
"field_idx": 0,
"init": {
"kind": "cxx_this",
"ty": sp_ptr,
"value_category": "prvalue"
}
}])
} else {
serde_json::json!([])
},
"body_stmt": if include_ctor_body {
serde_json::json!({"kind": "compound", "stmts": []})
} else {
serde_json::Value::Null
}
}));
cxx20_bundle(
serde_json::json!([{
"id": "struct.SelfPtr",
"is_union": false,
"size_bytes": 8,
"align_bytes": 8,
"is_trivially_copyable": true,
"has_address_dependent_ctor": has_flag,
"fields": [{"name": "self", "offset_bits": 0, "bit_width": null, "ty": sp_ptr}]
}]),
serde_json::Value::Array(funcs),
)
};
// Caught by `ctor_observes_this` even when `has_address_dependent_ctor` is
// false.
assert_unsupported(
lower_bundle_json(&make_bundle(false, true), &Options::default()),
"address-dependent constructor",
);
// Caught when a non-trivial constructor is bodiless (external).
assert_unsupported(
lower_bundle_json(&make_bundle(false, false), &Options::default()),
"address-dependent constructor",
);
// Caught by `has_address_dependent_ctor` from `anneal-clang-dump`.
assert_unsupported(
lower_bundle_json(&make_bundle(true, true), &Options::default()),
"address-dependent constructor",
);
}
#[test]
fn self_referential_partial_initializers_do_not_upfront_zero_init() {
use anneal_lower_cpp::ir::Proj;
let s_ty = serde_json::json!({"kind": "record", "id": "struct.Pair2"});
let arr_ty = serde_json::json!({"kind": "array", "elem": i32_ty(), "len": 3});
let bundle = c11_bundle(
serde_json::json!([{
"id": "struct.Pair2",
"is_union": false,
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{"name": "x", "offset_bits": 0, "bit_width": null, "ty": i32_ty()},
{"name": "y", "offset_bits": 32, "bit_width": null, "ty": i32_ty()}
]
}]),
serde_json::json!([{
"symbol": "self_init",
"unmangled_name": "self_init",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "s",
"ty": s_ty,
"init": {
"kind": "init_list",
"ty": s_ty,
"value_category": "prvalue",
"inits": [
{
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "member",
"ty": i32_ty(),
"value_category": "lvalue",
"base": {
"kind": "var_ref",
"ty": s_ty,
"value_category": "lvalue",
"var_id": 0,
"is_param": false,
"param_idx": null
},
"is_arrow": false,
"field_name": "y",
"record_id": "struct.Pair2",
"field_idx": 1,
"is_bitfield": false
}
},
{
"kind": "implicit_value_init",
"ty": i32_ty(),
"value_category": "prvalue"
}
]
}
},
{
"kind": "decl_stmt",
"var_id": 1,
"name": "a",
"ty": arr_ty,
"init": {
"kind": "init_list",
"ty": arr_ty,
"value_category": "prvalue",
"array_filler": {
"kind": "implicit_value_init",
"ty": i32_ty(),
"value_category": "prvalue"
},
"inits": [
int_lit(1),
{
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "array_subscript",
"ty": i32_ty(),
"value_category": "lvalue",
"base": {
"kind": "cast",
"cast_kind": "array_to_pointer_decay",
"ty": {
"kind": "ptr",
"pointee": i32_ty(),
"is_const": false,
"is_restrict": false,
"may_alias": false
},
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"ty": arr_ty,
"value_category": "lvalue",
"var_id": 1,
"is_param": false,
"param_idx": null
}
},
"idx": int_lit(2)
}
}
]
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
);
let p = lower_bundle_json(&bundle, &Options::default()).expect("self_init must lower");
let b = body(&p, "self_init");
let s_loc = local(b, "s");
let a_loc = local(b, "a");
let stmts_vec: Vec<_> = stmts(b).collect();
// No whole-object `ZeroInit(s)` or `ZeroInit(a)` may exist!
assert!(
!stmts_vec
.iter()
.any(|st| matches!(st, Stmt::ZeroInit(pl, _) if pl.projs.is_empty() && (pl.base == s_loc || pl.base == a_loc))),
"whole-object ZeroInit would mask uninitialized self-read UB: {stmts_vec:?}"
);
// `s.x = s.y` must execute BEFORE `ZeroInit(s.y)`!
let sx_assign = stmts_vec
.iter()
.position(|st| {
matches!(st, Stmt::Assign(pl, _, Expr::ReadPlace(rp, _))
if pl.base == s_loc
&& matches!(pl.projs.as_slice(), [Proj::Field(_, 0, _)])
&& rp.base == s_loc
&& matches!(rp.projs.as_slice(), [Proj::Field(_, 1, _)]))
})
.expect("s.x = s.y");
let sy_zero = stmts_vec
.iter()
.position(|st| {
matches!(st, Stmt::ZeroInit(pl, _)
if pl.base == s_loc && matches!(pl.projs.as_slice(), [Proj::Field(_, 1, _)]))
})
.expect("ZeroInit(s.y)");
assert!(sx_assign < sy_zero, "{stmts_vec:?}");
// `a[1] = a[2]` must execute BEFORE `ZeroInit(a[2])`!
let a1_assign = stmts_vec
.iter()
.position(|st| {
matches!(st, Stmt::Assign(pl, _, Expr::ReadPlace(rp, _))
if pl.base == a_loc && rp.base == a_loc)
})
.expect("a[1] = a[2]");
let a2_zero = stmts_vec
.iter()
.position(|st| matches!(st, Stmt::ZeroInit(pl, _) if pl.base == a_loc))
.expect("ZeroInit(a[2])");
assert!(a1_assign < a2_zero, "{stmts_vec:?}");
}
#[test]
fn cxx_lvalue_trivial_assign_lowers_without_declared_operator_callee() {
// `c = (a = b); return (a = b).x;` with `Pair::operator=` omitted from
// `bundle.functions` (as `anneal-clang-dump` emits trivial assignments).
let pair_ty = serde_json::json!({"kind": "record", "id": "struct.Pair"});
let var = |id: u32| {
serde_json::json!({
"kind": "var_ref",
"ty": pair_ty,
"value_category": "lvalue",
"var_id": id,
"is_param": false,
"param_idx": null,
"is_ref_binding": false
})
};
let triv_assign = |lhs: serde_json::Value, rhs: serde_json::Value| {
serde_json::json!({
"kind": "call",
"ty": pair_ty,
"value_category": "lvalue",
"callee_symbol": "_ZN4PairaSERKS_",
"is_indirect": false,
"implicit_object": lhs,
"implicit_object_is_ptr": false,
"args": [rhs],
"param_is_ref": [true],
"returns_ref": true,
"trivial_assign": true
})
};
let init_pair = |x: i64| {
serde_json::json!({
"kind": "init_list",
"ty": pair_ty,
"value_category": "prvalue",
"inits": [int_lit(x)]
})
};
let bundle = cxx20_bundle(
serde_json::json!([{
"id": "struct.Pair",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_trivially_copyable": true,
"fields": [{"name": "x", "offset_bits": 0, "bit_width": null, "ty": i32_ty()}]
}]),
serde_json::json!([{
"symbol": "_Z12chain_assignv",
"unmangled_name": "chain_assign",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{"kind": "decl_stmt", "var_id": 0, "name": "a", "ty": pair_ty, "init": init_pair(1)},
{"kind": "decl_stmt", "var_id": 1, "name": "b", "ty": pair_ty, "init": init_pair(2)},
{"kind": "decl_stmt", "var_id": 2, "name": "c", "ty": pair_ty, "init": init_pair(3)},
{
"kind": "expr_stmt",
"expr": triv_assign(var(2), triv_assign(var(0), var(1)))
},
{
"kind": "return",
"expr": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "member",
"ty": i32_ty(),
"value_category": "lvalue",
"base": triv_assign(var(0), var(1)),
"is_arrow": false,
"field_name": "x",
"record_id": "struct.Pair",
"field_idx": 0,
"is_bitfield": false
}
}
}
]
}
}]),
);
let p = lower_bundle_json(&bundle, &Options::default())
.expect("lvalue trivial operator= must lower without _ZN4PairaSERKS_ in bundle.functions");
let b = body(&p, "_Z12chain_assignv");
let record_copies = stmts(b)
.filter(|s| matches!(s, Stmt::Assign(_, Ty::Record(r), _) if r == "struct.Pair"))
.count();
// `a = b` -> `c = a` -> `a = b` before `.x` = 3 record copies.
assert_eq!(record_copies, 3, "{b:?}");
}
// --------------------- Gate-2 Round 2 regressions --------------------------
#[test]
fn rejects_non_c11_c_dialects_and_admits_c11_gnu11() {
let fns = serde_json::json!([{
"symbol": "f",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{"kind": "return", "expr": int_lit(0)}]
}
}]);
for ok_std in ["c11", "gnu11"] {
let mut v: serde_json::Value =
serde_json::from_str(&c11_bundle(serde_json::json!([]), fns.clone())).unwrap();
v["lang_policy"]["lang_standard"] = ok_std.into();
lower_bundle_json(&v.to_string(), &Options::default())
.unwrap_or_else(|e| panic!("expected {ok_std} to lower, got {e}"));
}
for bad_std in ["c89", "c99", "gnu99", "c17", "gnu17", "c23", "objc:c11", "opencl:c11"] {
let mut v: serde_json::Value =
serde_json::from_str(&c11_bundle(serde_json::json!([]), fns.clone())).unwrap();
v["lang_policy"]["lang_standard"] = bad_std.into();
let err = lower_bundle_json(&v.to_string(), &Options::default()).unwrap_err();
assert!(
matches!(err, LowerError::UnsupportedLangPolicy { .. }),
"expected UnsupportedLangPolicy for {bad_std}, got {err:?}"
);
}
}
#[test]
fn rejects_volatile_global_read_under_lvalue_to_rvalue() {
let make_global_read = |global_ty: serde_json::Value| {
c11_bundle(
serde_json::json!([]),
serde_json::json!([{
"symbol": "read_g",
"unmangled_name": "read_g",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{
"kind": "return",
"expr": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "global_ref",
"symbol": "g",
"ty": global_ty,
"value_category": "lvalue"
}
}
}]
}
}]),
)
};
let vol_err = lower_bundle_json(
&make_global_read(serde_json::json!({"kind": "unsupported", "desc": "volatile int"})),
&Options::default(),
)
.unwrap_err();
assert!(
matches!(&vol_err, LowerError::UnsupportedConstruct { detail } if detail.contains("volatile")),
"expected volatile global read rejection, got {vol_err:?}"
);
let mismatch_err =
lower_bundle_json(&make_global_read(u32_ty()), &Options::default()).unwrap_err();
assert!(
matches!(mismatch_err, LowerError::Malformed { .. }),
"expected type mismatch rejection, got {mismatch_err:?}"
);
}
#[test]
fn rejects_array_of_class_with_dtor_temporary_and_compound_literal() {
let guard_rec = serde_json::json!({
"id": "struct.Guard",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_trivially_copyable": false,
"dtor_symbol": "_ZN5GuardD1Ev",
"fields": [{"name": "x", "offset_bits": 0, "bit_width": null, "ty": i32_ty()}]
});
let dtor_decl = serde_json::json!({
"symbol": "_ZN5GuardD1Ev",
"unmangled_name": "~Guard",
"is_definition": false,
"method_kind": "dtor",
"return_ty": {"kind": "void"},
"params": [{
"name": "this",
"is_this": true,
"ty": {"kind": "ptr", "pointee": {"kind": "record", "id": "struct.Guard"}, "is_const": false, "is_restrict": false, "may_alias": false}
}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
}
});
let guard_ty = serde_json::json!({"kind": "record", "id": "struct.Guard"});
let arr_ty = serde_json::json!({"kind": "array", "elem": guard_ty, "len": 2});
let nested_arr_ty = serde_json::json!({"kind": "array", "elem": arr_ty, "len": 1});
let init_guard = serde_json::json!({
"kind": "init_list",
"ty": guard_ty,
"value_category": "prvalue",
"inits": [int_lit(1)]
});
let init_arr = serde_json::json!({
"kind": "init_list",
"ty": arr_ty,
"value_category": "prvalue",
"inits": [init_guard.clone(), init_guard]
});
for sub_expr in [
// 1. MaterializeTemporary without dtor_symbol (old schema fallback).
serde_json::json!({
"kind": "materialize_temporary",
"ty": arr_ty,
"value_category": "xvalue",
"lifetime_extended": false,
"sub": init_arr
}),
// 2. CompoundLiteral of nested array-of-Guard.
serde_json::json!({
"kind": "compound_literal",
"ty": nested_arr_ty,
"value_category": "lvalue",
"is_file_scope": false,
"init": {
"kind": "init_list",
"ty": nested_arr_ty,
"value_category": "prvalue",
"inits": [init_arr]
}
}),
] {
let bundle = cxx20_bundle(
serde_json::json!([guard_rec]),
serde_json::json!([
dtor_decl,
{
"symbol": "_Z1fv",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{"kind": "expr_stmt", "expr": sub_expr},
{"kind": "return", "expr": int_lit(0)}
]
}
}
]),
);
let err = lower_bundle_json(&bundle, &Options { entry: Some("_Z1fv".into()) }).unwrap_err();
assert!(
matches!(err, LowerError::UnsupportedConstruct { .. }),
"expected array-of-dtor-class rejection, got {err:?}"
);
}
}
#[test]
fn elides_comma_and_conditional_class_initializers_and_rejects_value_copy() {
let guard_ty = serde_json::json!({"kind": "record", "id": "struct.Guard"});
let guard_ptr_ty = serde_json::json!({
"kind": "ptr",
"pointee": guard_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let records = serde_json::json!([{
"id": "struct.Guard",
"is_union": false,
"size_bytes": 8,
"align_bytes": 8,
"is_trivially_copyable": false,
"has_address_dependent_ctor": true,
"dtor_symbol": "_ZN5GuardD1Ev",
"fields": [{"name": "self_ptr", "offset_bits": 0, "bit_width": null, "ty": guard_ptr_ty}]
}]);
let ctor_decl = serde_json::json!({
"symbol": "_ZN5GuardC1Ev",
"unmangled_name": "Guard",
"is_definition": false,
"method_kind": "ctor",
"return_ty": {"kind": "void"},
"params": [{"name": "this", "is_this": true, "ty": guard_ptr_ty}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
}
});
let dtor_decl = serde_json::json!({
"symbol": "_ZN5GuardD1Ev",
"unmangled_name": "~Guard",
"is_definition": false,
"method_kind": "dtor",
"return_ty": {"kind": "void"},
"params": [{"name": "this", "is_this": true, "ty": guard_ptr_ty}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
}
});
let make_guard = serde_json::json!({
"kind": "bind_temporary",
"ty": guard_ty,
"value_category": "prvalue",
"dtor_symbol": "_ZN5GuardD1Ev",
"sub": {
"kind": "construct",
"ty": guard_ty,
"value_category": "prvalue",
"ctor_symbol": "_ZN5GuardC1Ev",
"record_id": "struct.Guard",
"is_trivial": false,
"is_copy_or_move": false,
"is_default": true,
"zero_init": false,
"construction_kind": "complete",
"param_is_ref": [],
"args": []
}
});
// 1. `Guard g = (0, Guard()); Guard h = c ? Guard() : Guard();` must elide
// directly into `g` and `h` (zero record `Stmt::Assign`s, exactly 2 dtor
// calls on exit for `h` then `g`).
let ok_bundle = cxx20_bundle(
records.clone(),
serde_json::json!([
ctor_decl,
dtor_decl,
{
"symbol": "_Z4initb",
"unmangled_name": "init",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "c", "ty": {"kind": "bool"}}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "extend_int", "bits": 1, "sign_ext": false}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "g",
"ty": guard_ty,
"dtor_symbol": "_ZN5GuardD1Ev",
"init": {
"kind": "expr_with_cleanups",
"ty": guard_ty,
"value_category": "prvalue",
"sub": {
"kind": "binary_op",
"op": "comma",
"ty": guard_ty,
"value_category": "prvalue",
"lhs": int_lit(0),
"rhs": make_guard
}
}
},
{
"kind": "decl_stmt",
"var_id": 1,
"name": "h",
"ty": guard_ty,
"dtor_symbol": "_ZN5GuardD1Ev",
"init": {
"kind": "expr_with_cleanups",
"ty": guard_ty,
"value_category": "prvalue",
"sub": {
"kind": "conditional",
"ty": guard_ty,
"value_category": "prvalue",
"cond": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": {"kind": "bool"},
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"var_id": 99,
"is_param": true,
"param_idx": 0,
"ty": {"kind": "bool"},
"value_category": "lvalue"
}
},
"then_expr": make_guard,
"else_expr": make_guard
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}
]),
);
let p = lower_bundle_json(&ok_bundle, &Options { entry: Some("_Z4initb".into()) })
.expect("comma and conditional guaranteed copy elision must lower in place");
let b = body(&p, "_Z4initb");
let record_assigns =
stmts(b).filter(|s| matches!(s, Stmt::Assign(_, Ty::Record(_), _))).count();
assert_eq!(record_assigns, 0, "no bitwise record copies may be emitted: {b:?}");
let dtor_calls = b
.blocks
.iter()
.filter(|blk| matches!(&blk.term, Terminator::Call(sym, ..) if sym == "_ZN5GuardD1Ev"))
.count();
assert_eq!(dtor_calls, 2, "expected exactly 2 scope-exit destructor calls (g and h): {b:?}");
// 2. Attempting to copy `Guard` by value via `LvalueToRvalue` into an
// initializer must fail closed (`not_copyable`).
let copy_bundle = cxx20_bundle(
records,
serde_json::json!([
ctor_decl,
dtor_decl,
{
"symbol": "_Z8bad_copyv",
"unmangled_name": "bad_copy",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "g1",
"ty": guard_ty,
"dtor_symbol": "_ZN5GuardD1Ev",
"init": make_guard
},
{
"kind": "decl_stmt",
"var_id": 1,
"name": "g2",
"ty": guard_ty,
"dtor_symbol": "_ZN5GuardD1Ev",
"init": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": guard_ty,
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"var_id": 0,
"is_param": false,
"ty": guard_ty,
"value_category": "lvalue"
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}
]),
);
let err = lower_bundle_json(&copy_bundle, &Options { entry: Some("_Z8bad_copyv".into()) })
.unwrap_err();
assert!(
matches!(err, LowerError::UnsupportedConstruct { .. }),
"expected bitwise copy of non-copyable Guard to fail closed, got {err:?}"
);
}
// --------------------- Gate-2 Round 3 regressions --------------------------
#[test]
fn rejects_union_dtor_member_dtors() {
let u_ty = serde_json::json!({"kind": "record", "id": "union.U"});
let u_ptr = serde_json::json!({
"kind": "ptr",
"pointee": u_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let bundle = cxx20_bundle(
serde_json::json!([
{
"id": "struct.Guard",
"is_union": false,
"is_cxx_record": true,
"is_trivially_copyable": false,
"has_non_trivial_dtor": true,
"dtor_symbol": "_ZN5GuardD1Ev",
"size_bytes": 4,
"align_bytes": 4,
"fields": [{"name": "x", "ty": i32_ty(), "offset_bits": 0}]
},
{
"id": "union.U",
"is_union": true,
"is_cxx_record": true,
"is_trivially_copyable": false,
"has_non_trivial_dtor": true,
"dtor_symbol": "_ZN1UD1Ev",
"size_bytes": 4,
"align_bytes": 4,
"fields": [
{
"name": "g",
"ty": {"kind": "record", "id": "struct.Guard"},
"offset_bits": 0
},
{"name": "n", "ty": i32_ty(), "offset_bits": 0}
]
}
]),
serde_json::json!([
{
"symbol": "_ZN5GuardD1Ev",
"unmangled_name": "~Guard",
"method_kind": "dtor",
"is_definition": false,
"return_ty": {"kind": "void"},
"params": [{"name": "this", "ty": {
"kind": "ptr",
"pointee": {"kind": "record", "id": "struct.Guard"},
"is_const": false,
"is_restrict": false,
"may_alias": false
}, "is_this": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
}
},
{
"symbol": "_ZN1UD1Ev",
"unmangled_name": "~U",
"method_kind": "dtor",
"is_definition": true,
"return_ty": {"kind": "void"},
"params": [{"name": "this", "ty": u_ptr, "is_this": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"member_dtors": [{
"record_id": "union.U",
"field_idx": 0,
"dtor_symbol": "_ZN5GuardD1Ev"
}],
"body_stmt": {"kind": "compound", "stmts": []}
}
]),
);
let err = lower_bundle_json(&bundle, &Options { entry: Some("_ZN1UD1Ev".into()) }).unwrap_err();
assert!(
matches!(err, LowerError::Malformed { .. }),
"expected union destructor with implicit member_dtors to fail closed, got {err:?}"
);
}
#[test]
fn decl_group_in_for_init_and_label_keeps_locals_live_until_scope_exit() {
// `for (int i = 0, j = 3; i < j; ) { lbl: int a = i, b = j; return a + b; }`
let var_rval = |id: u32| {
serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"var_id": id,
"is_param": false,
"ty": i32_ty(),
"value_category": "lvalue"
}
})
};
let bundle = c11_bundle(
serde_json::json!([]),
serde_json::json!([{
"symbol": "sum_pair",
"unmangled_name": "sum_pair",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "for",
"init": {
"kind": "decl_group",
"decls": [
{"kind": "decl_stmt", "var_id": 0, "name": "i", "ty": i32_ty(), "init": int_lit(1)},
{"kind": "decl_stmt", "var_id": 1, "name": "j", "ty": i32_ty(), "init": int_lit(4)}
]
},
"cond": {
"kind": "binary_op",
"op": "lt",
"ty": i32_ty(),
"value_category": "prvalue",
"lhs": var_rval(0),
"rhs": var_rval(1)
},
"body": {
"kind": "compound",
"stmts": [
{
"kind": "label",
"label": "lbl",
"sub": {
"kind": "decl_group",
"decls": [
{"kind": "decl_stmt", "var_id": 2, "name": "a", "ty": i32_ty(), "init": var_rval(0)},
{"kind": "decl_stmt", "var_id": 3, "name": "b", "ty": i32_ty(), "init": var_rval(1)}
]
}
},
{
"kind": "return",
"expr": {
"kind": "binary_op",
"op": "add",
"ty": i32_ty(),
"value_category": "prvalue",
"lhs": var_rval(2),
"rhs": var_rval(3)
}
}
]
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
);
let p = lower_bundle_json(&bundle, &Options::default())
.expect("decl_group in for-init and label must lower cleanly");
let b = body(&p, "sum_pair");
// Entry block bb0 initializes `i` (local 1) and `j` (local 2) and must
// NOT emit `StorageDead(1)` or `StorageDead(2)` before the loop header.
for s in &b.blocks[0].stmts {
assert!(
!matches!(s, Stmt::StorageDead(1 | 2)),
"for-init decl_group prematurely killed loop variable in bb0: {b:?}"
);
}
// Likewise, inside the labeled block before `return a + b`, `a` (local 3)
// and `b` (local 4) must remain live until `return` cleans up scopes.
let ret_bb = b
.blocks
.iter()
.find(|blk| matches!(blk.term, Terminator::Ret) && blk.stmts.len() >= 5)
.expect("expected return block reading a and b");
let assign_ret_pos = ret_bb
.stmts
.iter()
.position(|s| matches!(s, Stmt::Assign(pl, ..) if pl.base == 0))
.expect("assign to _0");
for s in &ret_bb.stmts[..assign_ret_pos] {
assert!(
!matches!(s, Stmt::StorageDead(3 | 4)),
"labeled decl_group prematurely killed local before return read: {ret_bb:?}"
);
}
}
#[test]
fn returned_reference_to_static_const_fails_closed() {
// Returning a C++ reference (directly or via `?:`) to a function-local
// `static const` variable escapes its address and must fail closed instead
// of hoisting to a stack local.
let ref_ty = serde_json::json!({
"kind": "ref",
"pointee": i32_ty(),
"is_const": true,
"is_rvalue": false,
"may_alias": false
});
for ret_expr in [
serde_json::json!({
"kind": "var_ref",
"var_id": 0,
"is_param": false,
"ty": i32_ty(),
"value_category": "lvalue"
}),
serde_json::json!({
"kind": "conditional",
"ty": i32_ty(),
"value_category": "lvalue",
"cond": {"kind": "bool_lit", "value": true, "ty": {"kind": "bool"}, "value_category": "prvalue"},
"then_expr": {
"kind": "var_ref",
"var_id": 0,
"is_param": false,
"ty": i32_ty(),
"value_category": "lvalue"
},
"else_expr": {
"kind": "var_ref",
"var_id": 1,
"is_param": true,
"param_idx": 0,
"is_ref_binding": true,
"ty": i32_ty(),
"value_category": "lvalue"
}
}),
] {
let bundle = cxx20_bundle(
serde_json::json!([]),
serde_json::json!([{
"symbol": "_Z5get_kRKi",
"unmangled_name": "get_k",
"is_definition": true,
"return_ty": ref_ty,
"params": [{"name": "other", "ty": ref_ty}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "direct_ptr"}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "k",
"ty": i32_ty(),
"is_static_const": true,
"init": int_lit(42)
},
{"kind": "return", "expr": ret_expr}
]
}
}]),
);
let err = lower_bundle_json(&bundle, &Options::default()).unwrap_err();
assert!(
matches!(err, LowerError::UnsupportedConstruct { .. }),
"expected returned reference to static const local to fail closed, got {err:?}"
);
}
}
#[test]
fn emits_little_endian_and_const_fields_params_and_locals() {
let rec_ty = serde_json::json!({"kind": "record", "id": "struct.Mixed"});
let rec_ptr_ty = serde_json::json!({
"kind": "ptr",
"pointee": rec_ty,
"is_const": true,
"is_restrict": false,
"may_alias": false
});
let bundle = c11_bundle(
serde_json::json!([{
"id": "struct.Mixed",
"is_union": false,
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{
"name": "ro",
"offset_bits": 0,
"bit_width": null,
"ty": i32_ty(),
"is_const": true
},
{
"name": "rw",
"offset_bits": 32,
"bit_width": null,
"ty": i32_ty(),
"is_const": false
}
]
}]),
serde_json::json!([{
"symbol": "read_mixed",
"unmangled_name": "read_mixed",
"is_definition": true,
"return_ty": i32_ty(),
"params": [
{"name": "p", "ty": rec_ptr_ty, "is_const": false},
{"name": "c_arg", "ty": i32_ty(), "is_const": true}
],
"abi_witness": {
"cc": "c",
"param_passing": [
{"kind": "direct_ptr"},
{"kind": "direct_int", "bits": 32}
],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 2,
"name": "c_loc",
"ty": i32_ty(),
"is_const": true,
"init": int_lit(7)
},
{
"kind": "decl_stmt",
"var_id": 3,
"name": "m_loc",
"ty": i32_ty(),
"is_const": false,
"init": int_lit(3)
},
{
"kind": "return",
"expr": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "member",
"record_id": "struct.Mixed",
"field_idx": 0,
"field_name": "ro",
"is_arrow": true,
"ty": i32_ty(),
"value_category": "lvalue",
"base": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": rec_ptr_ty,
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"var_id": 0,
"is_param": true,
"param_idx": 0,
"ty": rec_ptr_ty,
"value_category": "lvalue"
}
}
}
}
}
]
}
}]),
);
let prog = lower_bundle_json(&bundle, &Options::default()).expect("bundle must lower");
assert!(prog.policy.little_endian);
assert_eq!(prog.records.len(), 1);
assert!(prog.records[0].fields[0].is_const, "ro field must be const");
assert!(!prog.records[0].fields[1].is_const, "rw field must be non-const");
let locals = &prog.bodies[0].locals;
assert!(!locals[0].is_const, "return slot must be non-const");
assert!(!locals[1].is_const, "param p must be non-const");
assert!(locals[2].is_const, "param c_arg must be const");
assert!(locals[3].is_const, "local c_loc must be const");
assert!(!locals[4].is_const, "local m_loc must be non-const");
let lean = lower_bundle_json_to_lean(&bundle, &EmitOptions::default())
.expect("Lean emission must succeed");
assert!(lean.contains(" littleEndian := true\n"), "missing littleEndian in:\n{lean}");
assert!(
lean.contains(
" intAligns := { i8AlignLog2 := 0, i16AlignLog2 := 1, i32AlignLog2 := 2, \
i64AlignLog2 := 3, i128AlignLog2 := 4, ptrAlignLog2 := 3, \
aggregateAlignLog2 := 0 }\n"
),
"missing intAligns in:\n{lean}"
);
assert!(
lean.contains("name := \"ro\", offsetBits := 0, bitWidth := none, ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), isConst := true"),
"missing const field isConst := true in:\n{lean}"
);
assert!(
lean.contains("name := \"rw\", offsetBits := 32, bitWidth := none, ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), isConst := false"),
"missing non-const field isConst := false in:\n{lean}"
);
assert!(
lean.contains("-- _1: p\n { ty := (CppTy.ptr (CppTy.record \"struct.Mixed\") true false false), isParam := true, isConst := false }"),
"missing non-const param in:\n{lean}"
);
assert!(
lean.contains("-- _2: c_arg\n { ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), isParam := true, isConst := true }"),
"missing const param in:\n{lean}"
);
assert!(
lean.contains("-- _3: c_loc\n { ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), isParam := false, isConst := true }"),
"missing const local in:\n{lean}"
);
assert!(
lean.contains("-- _4: m_loc\n { ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), isParam := false, isConst := false }"),
"missing non-const local in:\n{lean}"
);
}
#[test]
fn rejects_missing_or_false_little_endian_and_missing_is_const() {
let base: serde_json::Value = serde_json::json!({
"schema_version": 1,
"tu_main_file": "synthetic.c",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": false,
"lang_standard": "c11",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": [{
"id": "struct.Box",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"fields": [{
"name": "v",
"offset_bits": 0,
"bit_width": null,
"ty": i32_ty(),
"is_const": false
}]
}],
"functions": [{
"symbol": "f",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "x", "ty": i32_ty(), "is_const": false}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 1,
"name": "y",
"ty": i32_ty(),
"is_const": false,
"init": int_lit(1)
},
{
"kind": "return",
"expr": {
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "var_ref",
"var_id": 1,
"is_param": false,
"ty": i32_ty(),
"value_category": "lvalue"
}
}
}
]
}
}]
});
// Baseline succeeds.
lower_bundle_json(&base.to_string(), &Options::default()).expect("baseline must lower");
// Big-endian (`little_endian: false`) fails closed as
// UnsupportedLangPolicy.
let mut big_endian = base.clone();
big_endian["lang_policy"]["little_endian"] = false.into();
assert!(
matches!(
lower_bundle_json(&big_endian.to_string(), &Options::default()),
Err(LowerError::UnsupportedLangPolicy { .. })
),
"expected UnsupportedLangPolicy for little_endian=false"
);
// Missing `little_endian` fails closed as Schema.
let mut no_endian = base.clone();
no_endian["lang_policy"].as_object_mut().unwrap().remove("little_endian");
assert!(
matches!(
lower_bundle_json(&no_endian.to_string(), &Options::default()),
Err(LowerError::Schema { .. })
),
"expected Schema error for missing little_endian"
);
// Missing `fields[].is_const` fails closed as Schema.
let mut no_field_const = base.clone();
no_field_const["records"][0]["fields"][0].as_object_mut().unwrap().remove("is_const");
assert!(
matches!(
lower_bundle_json(&no_field_const.to_string(), &Options::default()),
Err(LowerError::Schema { .. })
),
"expected Schema error for missing field is_const"
);
// Missing `params[].is_const` fails closed as Schema.
let mut no_param_const = base.clone();
no_param_const["functions"][0]["params"][0].as_object_mut().unwrap().remove("is_const");
assert!(
matches!(
lower_bundle_json(&no_param_const.to_string(), &Options::default()),
Err(LowerError::Schema { .. })
),
"expected Schema error for missing param is_const"
);
// Missing `decl_stmt.is_const` fails closed as Schema.
let mut no_decl_const = base.clone();
no_decl_const["functions"][0]["body_stmt"]["stmts"][0]
.as_object_mut()
.unwrap()
.remove("is_const");
assert!(
matches!(
lower_bundle_json(&no_decl_const.to_string(), &Options::default()),
Err(LowerError::Schema { .. })
),
"expected Schema error for missing decl_stmt is_const"
);
}
#[test]
fn const_compound_literal_and_materialized_temp_preserve_is_const() {
let arr_ty = serde_json::json!({"kind": "array", "elem": i32_ty(), "len": 1});
let const_i32_ptr = serde_json::json!({
"kind": "ptr",
"pointee": i32_ty(),
"is_const": true,
"is_restrict": false,
"may_alias": false
});
let mut_i32_ptr = serde_json::json!({
"kind": "ptr",
"pointee": i32_ty(),
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let make_cl_bundle = |is_const: Option<bool>| {
let mut cl = serde_json::json!({
"kind": "compound_literal",
"is_file_scope": false,
"ty": arr_ty,
"value_category": "lvalue",
"init": {
"kind": "init_list",
"is_const": is_const.unwrap_or(false),
"ty": arr_ty,
"value_category": "prvalue",
"inits": [int_lit(1)]
}
});
if let Some(c) = is_const {
cl.as_object_mut().unwrap().insert("is_const".into(), c.into());
}
serde_json::json!({
"schema_version": 1,
"tu_main_file": "cl.c",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": false,
"lang_standard": "c11",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": [],
"functions": [{
"symbol": "f",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "p",
"ty": mut_i32_ptr,
"is_const": false,
"init": {
"kind": "cast",
"cast_kind": "pointer_cast",
"ty": mut_i32_ptr,
"value_category": "prvalue",
"sub": {
"kind": "cast",
"cast_kind": "array_to_pointer_decay",
"ty": const_i32_ptr,
"value_category": "prvalue",
"sub": cl
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]
})
.to_string()
};
// Positive: const compound literal temp carries `isConst := true`.
let const_cl_json = make_cl_bundle(Some(true));
let prog_c = lower_bundle_json(&const_cl_json, &Options::default()).unwrap();
let cl_temp_c = prog_c.bodies[0]
.locals
.iter()
.find(|l| matches!(l.ty, Ty::Array(_, 1)))
.expect("array compound literal temp");
assert!(cl_temp_c.is_const, "const compound literal temp must be is_const");
let lean_c = lower_bundle_json_to_lean(&const_cl_json, &EmitOptions::default()).unwrap();
assert!(
lean_c.contains(
"{ ty := (CppTy.array (CppTy.int CppIntWidth.w32 Signedness.signed false) 1), \
isParam := false, isConst := true }"
),
"expected isConst := true on const compound literal temp:\n{lean_c}"
);
// Positive: non-const compound literal temp carries `isConst := false`.
let mut_cl_json = make_cl_bundle(Some(false));
let prog_m = lower_bundle_json(&mut_cl_json, &Options::default()).unwrap();
let cl_temp_m = prog_m.bodies[0]
.locals
.iter()
.find(|l| matches!(l.ty, Ty::Array(_, 1)))
.expect("array compound literal temp");
assert!(!cl_temp_m.is_const, "non-const compound literal temp must be non-const");
// Negative: missing `compound_literal.is_const` fails closed as Schema.
assert!(matches!(
lower_bundle_json(&make_cl_bundle(None), &Options::default()),
Err(LowerError::Schema { .. })
));
// C++20 `materialize_temporary`: const vs non-const + missing schema error.
let const_ref_ty = serde_json::json!({
"kind": "ref",
"pointee": i32_ty(),
"is_const": true,
"is_rvalue": false,
"may_alias": false
});
let make_mt_bundle = |is_const: Option<bool>| {
let mut mt = serde_json::json!({
"kind": "materialize_temporary",
"lifetime_extended": true,
"dtor_symbol": null,
"ty": i32_ty(),
"value_category": "lvalue",
"sub": int_lit(5)
});
if let Some(c) = is_const {
mt.as_object_mut().unwrap().insert("is_const".into(), c.into());
}
serde_json::json!({
"schema_version": 1,
"tu_main_file": "mt.cc",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": true,
"lang_standard": "c++20",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": [],
"functions": [{
"symbol": "_Z1fv",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "r",
"ty": const_ref_ty,
"is_const": false,
"is_ref": true,
"init": mt
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]
})
.to_string()
};
let const_mt_json = make_mt_bundle(Some(true));
let prog_mt_c = lower_bundle_json(&const_mt_json, &Options::default()).unwrap();
let mt_temp_c = prog_mt_c.bodies[0]
.locals
.iter()
.find(|l| l.debug_name.starts_with("tmp"))
.expect("materialized temp local");
assert!(mt_temp_c.is_const, "const materialized temp must be is_const");
let lean_mt = lower_bundle_json_to_lean(&const_mt_json, &EmitOptions::default()).unwrap();
assert!(
lean_mt.contains(
"-- _2: tmp1\n { ty := (CppTy.int CppIntWidth.w32 Signedness.signed false), \
isParam := false, isConst := true }"
),
"expected isConst := true on const materialized temp:\n{lean_mt}"
);
let prog_mt_m = lower_bundle_json(&make_mt_bundle(Some(false)), &Options::default()).unwrap();
let mt_temp_m = prog_mt_m.bodies[0]
.locals
.iter()
.find(|l| l.debug_name.starts_with("tmp"))
.expect("materialized temp local");
assert!(!mt_temp_m.is_const, "non-const materialized temp must be non-const");
assert!(matches!(
lower_bundle_json(&make_mt_bundle(None), &Options::default()),
Err(LowerError::Schema { .. })
));
}
#[test]
fn clang_fixtures_preserve_const_fields_params_locals_and_temps() {
// C11 real Clang-generated fixture.
let c_prog = lower_ok("pos_const_objects");
assert!(c_prog.policy.little_endian);
assert_eq!(c_prog.records.len(), 1);
let rec = &c_prog.records[0];
assert_eq!(rec.record_id, "struct.ConstMixed");
assert!(rec.fields[0].is_const, "ro field must be const");
assert!(!rec.fields[1].is_const, "rw field must be non-const");
assert!(rec.fields[2].is_const, "ro_arr const-element array field must be const");
let c_body = body(&c_prog, "pos_const_objects");
assert!(!c_body.locals[local(c_body, "p")].is_const);
assert!(c_body.locals[local(c_body, "c_arg")].is_const);
assert!(!c_body.locals[local(c_body, "m_arg")].is_const);
assert!(c_body.locals[local(c_body, "c_loc")].is_const);
assert!(!c_body.locals[local(c_body, "m_loc")].is_const);
let cl_arr_temps: Vec<bool> = c_body
.locals
.iter()
.filter(|l| matches!(l.ty, Ty::Array(_, 1)))
.map(|l| l.is_const)
.collect();
assert_eq!(cl_arr_temps, vec![true, false], "expected const then non-const compound literals");
// C++20 real Clang-generated fixture.
let cxx_prog = lower_ok("cxx_const_temp");
assert!(cxx_prog.policy.little_endian);
let box_rec = cxx_prog.records.iter().find(|r| r.record_id == "struct.Box").unwrap();
assert!(box_rec.fields[0].is_const, "Box::tag must be const");
assert!(!box_rec.fields[1].is_const, "Box::val must be non-const");
let entry = body(&cxx_prog, "_Z14cxx_const_tempRK3Boxi");
assert!(!entry.locals[local(entry, "b")].is_const);
assert!(entry.locals[local(entry, "k")].is_const);
let method = body(&cxx_prog, "_ZNK3Box9read_withEii");
assert!(method.locals[local(method, "this")].is_const);
assert!(method.locals[local(method, "bias")].is_const);
assert!(!method.locals[local(method, "delta")].is_const);
assert!(method.locals[local(method, "base")].is_const);
assert!(!method.locals[local(method, "acc")].is_const);
let mt_temps: Vec<bool> = method
.locals
.iter()
.filter(|l| l.debug_name.starts_with("tmp"))
.map(|l| l.is_const)
.collect();
assert_eq!(mt_temps, vec![true, false], "expected const then non-const materialized temps");
}
#[test]
fn rejects_const_objects_with_mutable_subobject_or_nontrivial_dtor() {
let s_ty = serde_json::json!({"kind": "record", "id": "struct.HasMut"});
let s_ref = serde_json::json!({
"kind": "ref",
"pointee": s_ty,
"is_const": true,
"is_rvalue": false,
"may_alias": false
});
let s_rec = serde_json::json!({
"id": "struct.HasMut",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_cxx_record": true,
"is_trivially_copyable": true,
"has_mutable": true,
"fields": [{
"name": "c",
"offset_bits": 0,
"bit_width": null,
"ty": i32_ty(),
"is_const": false
}]
});
let init_s = serde_json::json!({
"kind": "init_list",
"ty": s_ty,
"value_category": "prvalue",
"inits": [int_lit(0)]
});
// 1. Const local with `mutable` subobject fails closed; non-const passes.
let make_local_bundle = |is_const: bool| {
cxx20_bundle(
serde_json::json!([s_rec]),
serde_json::json!([{
"symbol": "_Z1fv",
"unmangled_name": "f",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "s",
"ty": s_ty,
"is_const": is_const,
"init": init_s
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
)
};
lower_bundle_json(&make_local_bundle(false), &Options::default())
.expect("non-const local with mutable subobject must lower");
assert_unsupported(lower_bundle_json(&make_local_bundle(true), &Options::default()), "mutable");
// 2. Const parameter with `mutable` subobject fails closed.
let const_param_bundle = cxx20_bundle(
serde_json::json!([s_rec]),
serde_json::json!([{
"symbol": "_Z1g6HasMut",
"unmangled_name": "g",
"is_definition": true,
"return_ty": i32_ty(),
"params": [{"name": "s", "ty": s_ty, "is_const": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{"kind": "return", "expr": int_lit(0)}]
}
}]),
);
assert_unsupported(lower_bundle_json(&const_param_bundle, &Options::default()), "mutable");
// 3. Const materialized temporary with `mutable` subobject fails closed.
let const_mt_bundle = cxx20_bundle(
serde_json::json!([s_rec]),
serde_json::json!([{
"symbol": "_Z1hv",
"unmangled_name": "h",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "r",
"ty": s_ref,
"is_const": false,
"is_ref": true,
"init": {
"kind": "materialize_temporary",
"is_const": true,
"lifetime_extended": true,
"dtor_symbol": null,
"ty": s_ty,
"value_category": "lvalue",
"sub": init_s
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
);
assert_unsupported(lower_bundle_json(&const_mt_bundle, &Options::default()), "mutable");
// 4. Const local or temporary with a non-trivial destructor fails closed
// (C++20 [class.dtor] lifts const during destruction).
let d_ty = serde_json::json!({"kind": "record", "id": "struct.HasDtor"});
let d_ptr = serde_json::json!({
"kind": "ptr",
"pointee": d_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let d_ref = serde_json::json!({
"kind": "ref",
"pointee": d_ty,
"is_const": true,
"is_rvalue": false,
"may_alias": false
});
let d_rec = serde_json::json!({
"id": "struct.HasDtor",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_cxx_record": true,
"is_trivially_copyable": false,
"dtor_symbol": "_ZN7HasDtorD1Ev",
"fields": [{
"name": "x",
"offset_bits": 0,
"bit_width": null,
"ty": i32_ty(),
"is_const": false
}]
});
let dtor_fn = serde_json::json!({
"symbol": "_ZN7HasDtorD1Ev",
"unmangled_name": "~HasDtor",
"is_definition": false,
"method_kind": "dtor",
"return_ty": {"kind": "void"},
"params": [{"name": "this", "ty": d_ptr, "is_this": true, "is_const": true}],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": null
});
let init_d = serde_json::json!({
"kind": "init_list",
"ty": d_ty,
"value_category": "prvalue",
"inits": [int_lit(1)]
});
let make_dtor_local_bundle = |is_const: bool| {
cxx20_bundle(
serde_json::json!([d_rec]),
serde_json::json!([
{
"symbol": "_Z2dfv",
"unmangled_name": "df",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "d",
"ty": d_ty,
"is_const": is_const,
"dtor_symbol": "_ZN7HasDtorD1Ev",
"init": init_d
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
dtor_fn
]),
)
};
lower_bundle_json(&make_dtor_local_bundle(false), &Options::default())
.expect("non-const local with dtor must lower");
assert_unsupported(
lower_bundle_json(&make_dtor_local_bundle(true), &Options::default()),
"destructor",
);
let const_dtor_mt_bundle = cxx20_bundle(
serde_json::json!([d_rec]),
serde_json::json!([
{
"symbol": "_Z2dgv",
"unmangled_name": "dg",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "r",
"ty": d_ref,
"is_const": false,
"is_ref": true,
"init": {
"kind": "materialize_temporary",
"is_const": true,
"lifetime_extended": true,
"dtor_symbol": "_ZN7HasDtorD1Ev",
"ty": d_ty,
"value_category": "lvalue",
"sub": init_d
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
dtor_fn
]),
);
assert_unsupported(lower_bundle_json(&const_dtor_mt_bundle, &Options::default()), "destructor");
// 5. Hoisted `static const` local (scalar record or array of records)
// with a non-trivial destructor fails closed whether `dtor_symbol` is set
// on the declaration or only on the record definition.
let d_arr_ty = serde_json::json!({"kind": "array", "elem": d_ty, "len": 1});
let init_d_arr = serde_json::json!({
"kind": "init_list",
"ty": d_arr_ty,
"value_category": "prvalue",
"inits": [init_d]
});
for (decl_ty, decl_init, decl_dtor) in [
(d_ty.clone(), init_d.clone(), serde_json::json!("_ZN7HasDtorD1Ev")),
(d_ty.clone(), init_d.clone(), serde_json::Value::Null),
(d_arr_ty, init_d_arr, serde_json::json!("<array>")),
] {
let static_dtor_bundle = cxx20_bundle(
serde_json::json!([d_rec]),
serde_json::json!([
{
"symbol": "_Z3sdfv",
"unmangled_name": "sdf",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "decl_stmt",
"var_id": 0,
"name": "sd",
"ty": decl_ty,
"is_const": true,
"is_static_const": true,
"dtor_symbol": decl_dtor,
"init": decl_init
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
dtor_fn
]),
);
assert_unsupported(
lower_bundle_json(&static_dtor_bundle, &Options::default()),
"destructor",
);
}
// 6. Discarded C++ prvalue `BindTemporary` wrapping a `const` compound
// literal with a non-trivial destructor (even when outer `bind_temporary`
// is non-const) fails closed; same for a `const` prvalue `InitList` of a
// `mutable`-subobject record; and a `const` prvalue `Construct` under
// `ConstructorConversion` preserves `isConst := true`.
for bt_const in [false, true] {
let bt_cl_dtor = cxx20_bundle(
serde_json::json!([d_rec]),
serde_json::json!([
{
"symbol": "_Z3btfv",
"unmangled_name": "btf",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "expr_stmt",
"expr": {
"kind": "expr_with_cleanups",
"ty": {"kind": "void"},
"value_category": "prvalue",
"sub": {
"kind": "cast",
"cast_kind": "to_void",
"ty": {"kind": "void"},
"value_category": "prvalue",
"sub": {
"kind": "bind_temporary",
"is_const": bt_const,
"dtor_symbol": "_ZN7HasDtorD1Ev",
"ty": d_ty,
"value_category": "prvalue",
"sub": {
"kind": "compound_literal",
"is_file_scope": false,
"is_const": true,
"ty": d_ty,
"value_category": "prvalue",
"init": init_d
}
}
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
dtor_fn
]),
);
assert_unsupported(lower_bundle_json(&bt_cl_dtor, &Options::default()), "destructor");
}
let const_mut_init = cxx20_bundle(
serde_json::json!([s_rec]),
serde_json::json!([{
"symbol": "_Z3cmiv",
"unmangled_name": "cmi",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "expr_stmt",
"expr": {
"kind": "init_list",
"is_const": true,
"ty": s_ty,
"value_category": "prvalue",
"inits": [int_lit(0)]
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
}]),
);
assert_unsupported(lower_bundle_json(&const_mut_init, &Options::default()), "mutable");
let cs_ty = serde_json::json!({"kind": "record", "id": "struct.CS"});
let cs_ptr = serde_json::json!({
"kind": "ptr",
"pointee": cs_ty,
"is_const": false,
"is_restrict": false,
"may_alias": false
});
let cs_rec = serde_json::json!({
"id": "struct.CS",
"is_union": false,
"size_bytes": 4,
"align_bytes": 4,
"is_cxx_record": true,
"is_trivially_copyable": true,
"fields": [{
"name": "x",
"offset_bits": 0,
"bit_width": null,
"ty": i32_ty(),
"is_const": false
}]
});
let cs_ctor_fn = serde_json::json!({
"symbol": "_ZN2CSC1Ei",
"unmangled_name": "CS",
"is_definition": false,
"method_kind": "ctor",
"return_ty": {"kind": "void"},
"params": [
{"name": "this", "ty": cs_ptr, "is_this": true, "is_const": true},
{"name": "v", "ty": i32_ty(), "is_const": false}
],
"abi_witness": {
"cc": "c",
"param_passing": [{"kind": "direct_ptr"}, {"kind": "direct_int", "bits": 32}],
"return_passing": {"kind": "ignore"}
},
"body_stmt": null
});
let const_ctor_prvalue = cxx20_bundle(
serde_json::json!([cs_rec]),
serde_json::json!([
{
"symbol": "_Z3cpvv",
"unmangled_name": "cpv",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [
{
"kind": "expr_stmt",
"expr": {
"kind": "cast",
"cast_kind": "constructor_conversion",
"is_const": true,
"ty": cs_ty,
"value_category": "prvalue",
"sub": {
"kind": "construct",
"is_const": true,
"ctor_symbol": "_ZN2CSC1Ei",
"record_id": "struct.CS",
"args": [int_lit(1)],
"param_is_ref": [false],
"is_trivial": false,
"is_copy_or_move": false,
"is_default": false,
"zero_init": false,
"is_array_construct": false,
"construction_kind": "complete",
"ty": cs_ty,
"value_category": "prvalue"
}
}
},
{"kind": "return", "expr": int_lit(0)}
]
}
},
cs_ctor_fn
]),
);
let cpv_prog = lower_bundle_json(&const_ctor_prvalue, &Options::default()).unwrap();
let cpv_temp = cpv_prog.bodies[0]
.locals
.iter()
.find(|l| matches!(&l.ty, Ty::Record(r) if r == "struct.CS"))
.expect("constructed CS temporary");
assert!(cpv_temp.is_const, "const prvalue construct temporary must be is_const");
let cpv_lean = lower_bundle_json_to_lean(&const_ctor_prvalue, &EmitOptions::default()).unwrap();
assert!(
cpv_lean
.contains("{ ty := (CppTy.record \"struct.CS\"), isParam := false, isConst := true }"),
"expected isConst := true on const prvalue construct temporary:\n{cpv_lean}"
);
// 7. Missing `is_const` on `bind_temporary`, `construct`, or `init_list`
// fails closed with `LowerError::Schema`.
for bad_expr in [
serde_json::json!({
"kind": "init_list",
"ty": cs_ty,
"value_category": "prvalue",
"inits": [int_lit(0)]
}),
serde_json::json!({
"kind": "construct",
"ctor_symbol": "_ZN2CSC1Ei",
"record_id": "struct.CS",
"args": [int_lit(1)],
"param_is_ref": [false],
"is_trivial": false,
"ty": cs_ty,
"value_category": "prvalue"
}),
serde_json::json!({
"kind": "bind_temporary",
"dtor_symbol": "_ZN7HasDtorD1Ev",
"ty": d_ty,
"value_category": "prvalue",
"sub": {
"kind": "init_list",
"is_const": false,
"ty": d_ty,
"value_category": "prvalue",
"inits": [int_lit(0)]
}
}),
] {
let missing = serde_json::json!({
"schema_version": 1,
"tu_main_file": "missing.cc",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"is_cplusplus": true,
"lang_standard": "c++20",
"pointer_width_bits": 64,
"char_is_signed": true,
"strict_aliasing": false,
"signed_overflow": "iso_ub",
"exceptions_enabled": false,
"fast_math": false,
"little_endian": true
},
"records": [],
"functions": [{
"symbol": "_Z1mv",
"unmangled_name": "m",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": {
"kind": "compound",
"stmts": [{"kind": "expr_stmt", "expr": bad_expr}]
}
}]
})
.to_string();
assert!(
matches!(
lower_bundle_json(&missing, &Options::default()),
Err(LowerError::Schema { .. })
),
"expected Schema error for missing is_const"
);
}
}
#[test]
fn const_record_call_in_loop_uses_non_const_call_slot_and_scoped_const_object() {
// Re-executing `const P mk()` in a loop must not leave an `isConst`
// call-result temporary without `StorageLive`/`StorageDead` (which would
// trigger false UB on the second iteration), while any materialized `const`
// temporary or `const` local initialized from `mk()` still carries
// `isConst := true` with paired `StorageLive`/`StorageDead`.
let p_ty = serde_json::json!({"kind": "record", "id": "struct.P"});
let p_rec = serde_json::json!({
"id": "struct.P",
"is_union": false,
"size_bytes": 8,
"align_bytes": 4,
"is_cxx_record": true,
"is_trivially_copyable": true,
"fields": [
{"name": "a", "offset_bits": 0, "bit_width": null, "ty": i32_ty(), "is_const": false},
{"name": "b", "offset_bits": 32, "bit_width": null, "ty": i32_ty(), "is_const": false}
]
});
let mk_decl = serde_json::json!({
"symbol": "_Z2mkv",
"unmangled_name": "mk",
"is_definition": false,
"return_ty": p_ty,
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 64}
},
"body_stmt": null
});
let mk_call = serde_json::json!({
"kind": "call",
"is_const": true,
"ty": p_ty,
"value_category": "prvalue",
"callee_symbol": "_Z2mkv",
"is_indirect": false,
"args": [],
"param_is_ref": [],
"returns_ref": false
});
let var_i = serde_json::json!({
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 1,
"is_param": false,
"param_idx": null,
"is_ref_binding": false
});
let read_i = serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": var_i
});
let var_sum = serde_json::json!({
"kind": "var_ref",
"ty": i32_ty(),
"value_category": "lvalue",
"var_id": 2,
"is_param": false,
"param_idx": null,
"is_ref_binding": false
});
let read_sum = serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": var_sum
});
let for_loop = |body_stmts: serde_json::Value| {
serde_json::json!({
"kind": "compound",
"stmts": [
{"kind": "decl_stmt", "var_id": 2, "name": "sum", "ty": i32_ty(), "is_const": false, "init": int_lit(0)},
{
"kind": "for",
"init": {"kind": "decl_stmt", "var_id": 1, "name": "i", "ty": i32_ty(), "is_const": false, "init": int_lit(0)},
"cond": {
"kind": "binary_op",
"op": "lt",
"ty": {"kind": "bool"},
"value_category": "prvalue",
"lhs": read_i,
"rhs": int_lit(2)
},
"inc": {
"kind": "unary_op",
"op": "pre_inc",
"ty": i32_ty(),
"value_category": "lvalue",
"sub": var_i
},
"body": {"kind": "compound", "stmts": body_stmts}
},
{"kind": "return", "expr": read_sum}
]
})
};
let add_to_sum = |rhs: serde_json::Value| {
serde_json::json!({
"kind": "expr_stmt",
"expr": {
"kind": "binary_op",
"op": "add_assign",
"ty": i32_ty(),
"value_category": "lvalue",
"compute_lhs_ty": i32_ty(),
"compute_result_ty": i32_ty(),
"lhs": var_sum,
"rhs": rhs
}
})
};
let read_member_a = |base: serde_json::Value| {
serde_json::json!({
"kind": "cast",
"cast_kind": "lvalue_to_rvalue",
"ty": i32_ty(),
"value_category": "prvalue",
"sub": {
"kind": "member",
"ty": i32_ty(),
"value_category": "lvalue",
"base": base,
"is_arrow": false,
"field_name": "a",
"record_id": "struct.P",
"field_idx": 0,
"is_bitfield": false
}
})
};
// Case 1: `for (...) { P p = mk(); sum += p.a; }`
let var_p = serde_json::json!({
"kind": "var_ref",
"ty": p_ty,
"value_category": "lvalue",
"var_id": 3,
"is_param": false,
"param_idx": null,
"is_ref_binding": false
});
let fn_local = serde_json::json!({
"symbol": "_Z9loop_copyv",
"unmangled_name": "loop_copy",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": for_loop(serde_json::json!([
{"kind": "decl_stmt", "var_id": 3, "name": "p", "ty": p_ty, "is_const": false, "init": mk_call},
add_to_sum(read_member_a(var_p))
]))
});
// Case 2: `for (...) { sum += mk().a; }` (materialized `const` temporary)
let fn_temp = serde_json::json!({
"symbol": "_Z9loop_tempv",
"unmangled_name": "loop_temp",
"is_definition": true,
"return_ty": i32_ty(),
"params": [],
"abi_witness": {
"cc": "c",
"param_passing": [],
"return_passing": {"kind": "direct_int", "bits": 32}
},
"body_stmt": for_loop(serde_json::json!([
add_to_sum(read_member_a(serde_json::json!({
"kind": "materialize_temporary",
"is_const": true,
"lifetime_extended": false,
"ty": p_ty,
"value_category": "lvalue",
"sub": mk_call
})))
]))
});
let bundle =
cxx20_bundle(serde_json::json!([p_rec]), serde_json::json!([fn_local, fn_temp, mk_decl]));
let prog = lower_bundle_json(&bundle, &Options::default()).unwrap();
// Every `Terminator::Call` destination local must be non-const, and every
// `is_const` non-param local must have paired `StorageLive`/`StorageDead`.
for sym in ["_Z9loop_copyv", "_Z9loop_tempv"] {
let b = body(&prog, sym);
let mut saw_call_dst = false;
for blk in &b.blocks {
if let anneal_lower_cpp::ir::Terminator::Call(callee, _, Some((dst, _)), _) = &blk.term
{
if callee == "_Z2mkv" {
saw_call_dst = true;
assert!(
!b.locals[dst.base].is_const,
"{sym}: call return-holder local {} must be non-const",
dst.base
);
}
}
}
assert!(saw_call_dst, "{sym}: expected call to _Z2mkv");
for (idx, decl) in b.locals.iter().enumerate() {
if idx == 0 || decl.is_param || !decl.is_const {
continue;
}
let has_live = stmts(b).any(|s| matches!(s, Stmt::StorageLive(l) if *l == idx));
let has_dead = stmts(b).any(|s| matches!(s, Stmt::StorageDead(l) if *l == idx));
assert!(
has_live && has_dead,
"{sym}: const local {idx} must have paired StorageLive and StorageDead"
);
}
}
// In `loop_temp`, the materialized `const` temporary itself must still be
// `is_const: true`.
let temp_body = body(&prog, "_Z9loop_tempv");
assert!(
temp_body.locals.iter().any(|l| !l.is_param
&& l.is_const
&& matches!(&l.ty, Ty::Record(r) if r == "struct.P")),
"expected materialized const temporary for mk().a in loop_temp"
);
}