diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a0eb4d6..457a959a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to `trace` are documented in this file. ## Unreleased +### Track nested container elements + +Callback and pointer values stored in nested modeled containers now reach +chained subscripts, modeled accessors, and nested range-for loops. Named inner +containers copy their element summaries, and map inserts carry only the +mapped values of compatible entries. See [Container elements](docs/CXX.md#container-elements). + ### Use the derived solver budget in canonical evaluation The canonical evaluation profile pinned `TRACE_SOLVE_BUDGET_POPS=850000`, diff --git a/crates/trace-analysis/src/pag.rs b/crates/trace-analysis/src/pag.rs index 3821c1de..3ccb9008 100644 --- a/crates/trace-analysis/src/pag.rs +++ b/crates/trace-analysis/src/pag.rs @@ -3,6 +3,7 @@ use crate::ipc::detect_ipc_pairs_with_models; use crate::summaries::{Effect, EffectGroup, FnModelSet, ModelLookup}; use indexmap::IndexMap; use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; +use std::sync::Arc; use trace_ir::{ CallSite, ContainerOwner, FieldId, FlowConstraint, FnId, LocId, PagNodeId, Program, ReturnFlow, StorageClass, TargetId, TypeDesc, TypeId, VarId, @@ -768,18 +769,30 @@ impl Pag { element: TypeId, target: Option, ) -> LocId { - let (var, name) = match owner { - ContainerOwner::Variable(var) => { - (Some(*var), program.symbols.variable(*var).name.clone()) + fn owner_var(owner: &ContainerOwner) -> Option { + match owner { + ContainerOwner::Variable(var) => Some(*var), + ContainerOwner::Field { .. } => None, + ContainerOwner::Nested { parent, .. } => owner_var(parent), } - ContainerOwner::Field { class, name } => { - let class = match program.types.get(*class).desc.as_ref() { - TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => name, - _ => unreachable!("container member has an aggregate owner"), - }; - (None, format!("{class}.{name}")) + } + fn owner_name(program: &Program, owner: &ContainerOwner) -> String { + match owner { + ContainerOwner::Variable(var) => program.symbols.variable(*var).name.clone(), + ContainerOwner::Field { class, name } => { + let class = match program.types.get(*class).desc.as_ref() { + TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => name, + _ => unreachable!("container member has an aggregate owner"), + }; + format!("{class}.{name}") + } + ContainerOwner::Nested { parent, instance } => { + format!("{}[{instance}]", owner_name(program, parent)) + } } - }; + } + let var = owner_var(owner); + let name = owner_name(program, owner); let fn_id = var.and_then(|var| program.symbols.variable(var).fn_id); let desc = if let Some(owner) = fn_id { format!("elements:{}::{name}", program.symbols.function(owner).name) @@ -856,20 +869,39 @@ impl Pag { owner, element, } => { - let (owner, target) = match owner { - ContainerOwner::Variable(var) => { - (owner.clone(), program.symbols.variable(*var).target) - } - ContainerOwner::Field { class, name } => { - let owner = ContainerOwner::Field { + fn canonical_owner( + program: &Program, + owner: &ContainerOwner, + ) -> ContainerOwner { + match owner { + ContainerOwner::Variable(var) => ContainerOwner::Variable(*var), + ContainerOwner::Field { class, name } => ContainerOwner::Field { class: program.types.tag_identity(*class), name: name.clone(), - }; + }, + ContainerOwner::Nested { parent, instance } => ContainerOwner::Nested { + parent: Arc::new(canonical_owner(program, parent)), + instance: instance.clone(), + }, + } + } + fn owner_target( + program: &Program, + owner: &ContainerOwner, + dst: VarId, + ) -> Option { + match owner { + ContainerOwner::Variable(var) => program.symbols.variable(*var).target, // Target merging scopes all retained variables, // including the temporary holding this cell's address. - (owner, program.symbols.variable(*dst).target) + ContainerOwner::Field { .. } => program.symbols.variable(dst).target, + ContainerOwner::Nested { parent, .. } => { + owner_target(program, parent, dst) + } } - }; + } + let owner = canonical_owner(program, owner); + let target = owner_target(program, &owner, *dst); let loc = *container_elements .entry((target, owner.clone(), *element)) .or_insert_with(|| { diff --git a/crates/trace-cli/tests/it/cpp_cases.rs b/crates/trace-cli/tests/it/cpp_cases.rs index 73371a98..78d3eba7 100644 --- a/crates/trace-cli/tests/it/cpp_cases.rs +++ b/crates/trace-cli/tests/it/cpp_cases.rs @@ -7,7 +7,7 @@ use std::sync::OnceLock; use common::{default_opts, fixture, fn_name, has_any_edge, has_edge, must_not_have_edge}; use trace_analysis::{analyze, AnalysisResult, ResolutionKind}; -use trace_ir::{FnId, Linkage, Program}; +use trace_ir::{FnId, Linkage, Program, TypeDesc}; use trace_parse::build_program; fn direct_targets(program: &Program, analysis: &AnalysisResult, caller: &str) -> Vec { @@ -762,6 +762,745 @@ fn container_lookup_preserves_ownership_and_callable_values() { ); } +#[test] +fn nested_container_elements_flow_through_subscripts_and_ranges() { + let root = fixture("cpp_nested_containers"); + let program = &build_program(&root, &default_opts(&root)).expect("build"); + let (_, analysis) = analyze(program); + for (caller, expected) in [ + ("vector_direct", &["alpha"][..]), + ("vector_braced_insertion", &["alpha"][..]), + ("vector_emplace", &["alpha"][..]), + ("vector_braced_multi_emplace", &["alpha", "beta"][..]), + ("vector_braced_multi_push", &["alpha", "beta"][..]), + ("vector_map_push_braced", &["alpha"][..]), + ("vector_map_push_multi", &["alpha", "beta"][..]), + ("vector_braced_range", &["alpha", "beta"][..]), + ("vector_named_range", &["alpha"][..]), + ("vector_field_range", &["alpha"][..]), + ("vector_isolation", &["alpha"][..]), + ("map_map_subscript", &["alpha", "beta"][..]), + ("map_vector_subscript", &["alpha", "beta"][..]), + ("map_insert_single_pair", &["alpha", "beta"][..]), + ("vector_map_range", &["alpha", "beta"][..]), + ("vector_insert_ambiguous", &["alpha", "beta"][..]), + ("vector_descendant_copy", &["alpha"][..]), + ("alias_descendant_copy", &["alpha"][..]), + ("vector_typed_brace_copy", &["alpha"][..]), + ("vector_nested_allocator", &["alpha", "beta"][..]), + ("vector_nested_allocator_mixed", &["alpha", "beta"][..]), + ("vector_nested_ordinary_constructor", &["alpha"][..]), + ("vector_explicit_inner_allocator", &["alpha"][..]), + ("vector_braced_copy_allocator", &["alpha"][..]), + ("vector_mixed_allocator_copy", &["alpha"][..]), + ("vector_one_element_list", &["alpha"][..]), + ("vector_triple_braced", &["alpha"][..]), + ("vector_named_inner_braced_copy", &["alpha"][..]), + ("map_named_pair_insert", &["alpha"][..]), + ("map_at_chain", &["alpha", "beta"][..]), + ("vector_double_braced_push", &["alpha"][..]), + ("vector_braced_named_copy", &["alpha"][..]), + ("map_braced_named_insert", &["alpha"][..]), + ("map_initializer_named", &["alpha"][..]), + ("map_typed_pair_compound_insert", &["alpha", "beta"][..]), + ("map_pair_compound_entry_list_insert", &["alpha"][..]), + ("map_callback_alias_key_multi_insert", &["beta"][..]), + ("map_const_key_insert", &["alpha"][..]), + ("map_allocator_entry_list", &["alpha", "beta"][..]), + ("map_aggregate_key_multi_insert", &["alpha", "beta"][..]), + ("map_typed_pair_initializer", &["alpha"][..]), + ("vector_map_typed_pair_initializer", &["alpha"][..]), + ("map_allocator_aggregate_key", &["alpha", "beta"][..]), + ("map_mixed_pair_insert", &["alpha", "beta"][..]), + ("map_three_entry_named_insert", &["alpha", "beta"][..]), + ("map_insert_inner_allocator_one", &["alpha"][..]), + ("map_insert_triple_single", &["alpha", "beta"][..]), + ("map_pair_key_map_single", &["alpha", "beta"][..]), + ("vector_position_named_inner", &["alpha", "beta"][..]), + ("vector_position_inner_lists", &["alpha", "beta"][..]), + ("vector_const_alias_typed_inner", &["alpha"][..]), + ("map_const_pair_alias_insert", &["alpha"][..]), + ("map_initializer_mixed_named", &["alpha", "beta"][..]), + ("map_initializer_mixed_make_pair", &["alpha", "beta"][..]), + ("map_insert_named_first", &["alpha", "beta"][..]), + ("map_insert_make_pair_first", &["alpha", "beta"][..]), + ("map_aggregate_key_single_pair", &["beta"][..]), + ("map_const_callback_alias_key", &["beta"][..]), + ("map_pair_empty_key_insert", &["alpha"][..]), + ("map_pair_empty_key_initializer", &["alpha", "beta"][..]), + ("map_direct_typed_pair_non_nested", &["alpha"][..]), + ("map_pair_key_callback_non_nested", &["alpha"][..]), + ("map_pair_callback_key_non_nested", &["alpha"][..]), + ("map_named_pair_key_non_nested", &["alpha"][..]), + ("map_make_pair_key_non_nested", &["alpha"][..]), + ("map_braced_mapped_non_nested", &["alpha"][..]), + ("map_pair_key_as_entry_non_nested", &[][..]), + ("map_make_pair_key_as_entry_non_nested", &[][..]), + ("map_insert_widening_keys", &["alpha", "beta"][..]), + ("map_insert_converting_class_keys", &["alpha", "beta"][..]), + ("map_insert_qualified_callback_keys", &["alpha", "beta"][..]), + ("map_insert_qualified_pointer_keys", &["alpha", "beta"][..]), + ("map_numeric_key_initializer", &["alpha"][..]), + ("map_numeric_key_insert", &["alpha"][..]), + ("empty_brace_with_nondefault_key", &[][..]), + ("inner_container_conversions", &["alpha"][..]), + ("explicit_subscript_macro", &["alpha"][..]), + ("move_inner_callbacks", &["alpha", "beta"][..]), + ("copy_list_with_allocator", &["alpha"][..]), + ("copy_map_with_allocator", &["alpha"][..]), + ("map_pair_struct_key", &[][..]), + ("map_make_pair_enum_key", &[][..]), + ("map_nested_pair_key", &[][..]), + ("map_pair_container_key", &[][..]), + ("map_pair_key_entries", &["alpha", "beta"][..]), + ("map_aggregate_key_allocator_copy", &["alpha"][..]), + ("map_class_key_from_callback", &["alpha"][..]), + ("map_insert_braced_then_unmodeled", &["alpha"][..]), + ("map_insert_unmodeled_then_braced", &["alpha"][..]), + ("pair_container_field_copy", &["alpha"][..]), + ("pair_container_field_assignment", &["alpha"][..]), + ("map_empty_inner_brace_without_initializer", &["alpha"][..]), + ("map_initializer_default_entry", &["alpha", "beta"][..]), + ("map_initializer_unmodeled_pair", &["alpha"][..]), + ("map_copy_list_pair_key", &["alpha"][..]), + ("vector_allocator_extended_copy", &["alpha"][..]), + ("vector_empty_map_without_initializer", &["alpha"][..]), + ("map_entry_conversion", &["alpha"][..]), + ("vector_returned_inner", &["beta"][..]), + ("map_insert_braced_then_pair_return", &["alpha"][..]), + ("vector_initializer_allocator_copy", &["alpha", "beta"][..]), + ("vector_parenthesized_typed_inner", &["alpha", "beta"][..]), + ("map_converting_pair_key", &["alpha"][..]), + ("map_convertible_mapped_value", &["alpha"][..]), + ("map_single_pair_empty_mapped", &[][..]), + ("map_initializer_trailing_empty", &["alpha"][..]), + ("map_initializer_trailing_empty_nested", &["alpha"][..]), + ("vector_braced_typed_temporary_copy", &["alpha"][..]), + ("map_insert_empty_then_make_pair", &["alpha"][..]), + ("vector_callback_param_spelling", &["alpha"][..]), + ("map_initializer_aggregate_trailing_empty", &["alpha"][..]), + ( + "map_initializer_aggregate_trailing_empty_nested", + &["alpha"][..], + ), + ("map_insert_inner_call_aggregate_key", &["alpha"][..]), + ("vector_braced_typed_named_copy", &["alpha"][..]), + ("vector_braced_typed_allocator_copy", &["alpha"][..]), + ("vector_braced_typed_temporary_initializer", &["alpha"][..]), + ("map_pair_compound_key", &["alpha"][..]), + ("map_three_level_single_pair", &["alpha"][..]), + ("map_insert_aggregate_key_empty_mapped", &[][..]), + ("map_insert_pair_key_integer_variable", &[][..]), + ("map_parenthesized_pair_compound", &["alpha"][..]), + ("map_insert_parenthesized_pair_compound", &["alpha"][..]), + ("vector_initializer_list_temporary", &["alpha", "beta"][..]), + ("map_initializer_list_temporary", &["alpha", "beta"][..]), + ( + "map_insert_initializer_list_temporary", + &["alpha", "beta"][..], + ), + ("map_single_unmodeled_mapped", &[][..]), + ("reference_alias_range", &["alpha"][..]), + ("ignored_nested_accessor_macro", &["alpha"][..]), + ("ignored_accessor_assignment", &["alpha"][..]), + ("ignored_accessor_macro", &["alpha"][..]), + ("ignored_accessor_range", &["alpha"][..]), + ("ignored_range_bracket", &["alpha"][..]), + ("map_pair_key_insert", &["alpha", "beta"][..]), + ("map_pair_key_entry", &["alpha", "beta"][..]), + ("map_callback_pair_key_entry", &["alpha", "beta"][..]), + ("map_vector_pair_key_entry", &["alpha", "beta"][..]), + ("map_class_key_insert", &["alpha", "beta"][..]), + ("map_pair_braced_insert", &["alpha", "beta"][..]), + ("map_pair_named_insert", &["alpha"][..]), + ("vector_allocator_braced_push", &["alpha", "beta"][..]), + ("vector_typed_inner_brace", &["alpha", "beta"][..]), + ("vector_at_chain", &["alpha", "beta"][..]), + ("map_insert_allocator", &["alpha", "beta"][..]), + ("map_typed_mapped_entry", &["alpha", "beta"][..]), + ("map_callback_key_insert", &["beta"][..]), + ("map_pair_braced_copy", &["alpha"][..]), + ("map_pair_typed_brace", &["alpha", "beta"][..]), + ("ignored_typed_insert", &["alpha"][..]), + ("ignored_named_payload", &["alpha"][..]), + ("map_without_subscript_model", &["alpha"][..]), + ("map_inner_without_initializer", &["alpha"][..]), + ("typed_reference_range", &["alpha"][..]), + ("by_value_range_isolation", &["alpha"][..]), + ("nested_ignored_bracket", &["alpha"][..]), + ("ignored_range_field_subscript", &["alpha"][..]), + ("ignored_nested_field_bracket", &["alpha"][..]), + ("ignored_method_macro", &["alpha"][..]), + ("use_shared_slots_store", &["alpha"][..]), + ("use_shared_slots_read", &["alpha"][..]), + ("read_slots", &["alpha"][..]), + ("unevaluated_nested", &[][..]), + ] { + let mut targets: Vec<_> = analysis + .call_edges + .iter() + .filter(|edge| fn_name(program, edge.caller) == caller) + .map(|edge| fn_name(program, edge.callee)) + .filter(|name| matches!(name.as_str(), "alpha" | "beta" | "unrelated")) + .collect(); + targets.sort_unstable(); + targets.dedup(); + assert_eq!(targets, expected, "{caller}"); + } + assert!(has_any_edge( + program, + &analysis, + "pointer_range", + "Handler::run" + )); + assert!(must_not_have_edge( + program, + &analysis, + "pointer_range", + "OtherHandler::run" + )); + assert!(has_any_edge( + program, + &analysis, + "copy_callback_parameter_cv", + "int_callback" + )); + assert!(has_any_edge( + program, + &analysis, + "copy_callback_pointer_parameter_cv", + "pointer_callback" + )); + assert!(must_not_have_edge( + program, + &analysis, + "copy_callback_pointer_parameter_cv", + "const_pointer_callback" + )); +} + +#[test] +fn function_pointer_alias_cv_qualification_merges_existing_qualifiers() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("main.cpp"), + r#" +using ConstCallback = void (*const)(int *); +using VolatileCallback = void (*volatile)(int *); +using RepeatedConstCallback = const ConstCallback; +using ConstVolatileCallback = volatile ConstCallback; +using VolatileConstCallback = const VolatileCallback; +using Slot = void (*const *)(int *); +using ConstSlot = const Slot; +using ConstVolatileSlot = volatile ConstSlot; +using ReturningSlot = int *(*const *)(int *); +using ConstReturningSlot = const ReturningSlot; +using Slots = void (*[2 * 3])(int *); +using ConstSlots = const Slots; +using WrittenSlots = void (*const[2 * 3])(int *); +using RefSlot = void (*const *&)(int *); +using ConstRefSlot = const RefSlot; +using VolatileRefSlot = volatile RefSlot; +using ConstReferentSlot = void (*const *const &)(int *); +using VolatileConstReferentSlot = volatile ConstReferentSlot; +using RvalueRefSlot = void (*const *&&)(int *); +using CvRvalueRefSlot = const volatile RvalueRefSlot; +"#, + ) + .unwrap(); + + let program = build_program(dir.path(), &default_opts(dir.path())).expect("build"); + for (name, expected) in [ + ("ConstCallback", "void(*const)(int*)"), + ("RepeatedConstCallback", "void(*const)(int*)"), + ("ConstVolatileCallback", "void(*const volatile)(int*)"), + ("VolatileConstCallback", "void(*const volatile)(int*)"), + ("Slot", "void(*const*)(int*)"), + ("ConstSlot", "void(*const*const)(int*)"), + ("ConstVolatileSlot", "void(*const*const volatile)(int*)"), + ("ConstReturningSlot", "int*(*const*const)(int*)"), + ("ConstSlots", "void(*const[2*3])(int*)"), + ("WrittenSlots", "void(*const[2*3])(int*)"), + ("ConstRefSlot", "void(*const*&)(int*)"), + ("VolatileRefSlot", "void(*const*&)(int*)"), + ("VolatileConstReferentSlot", "void(*const*const&)(int*)"), + ("CvRvalueRefSlot", "void(*const*&&)(int*)"), + ] { + assert_eq!( + program.types.alias_type_spelling(name).map(AsRef::as_ref), + Some(expected), + "{name}" + ); + } +} + +#[test] +fn nested_container_copy_distinguishes_outer_function_pointer_cv() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("main.cpp"), + r#" +using Callback = void (*)(); +using Slot = void (*const *)(int *); +using ConstSlot = const Slot; +using Slots = void (*[2 * 3])(int *); +using ConstSlots = const Slots; +using WrittenSlots = void (*const[2 * 3])(int *); +using RefSlot = void (*const *&)(int *); + +template struct Box { + Value value{}; + Box() = default; + template Box(const Box&) : value{} {} + void put(Value next) { value = next; } + Value& get() { return value; } +}; + +void alpha() {} +void beta() {} +void use_boxes() { + Box source; + Box matching; + source.put(alpha); + matching.put(beta); + Box> outer; + outer.put(source); + outer.put(matching); + outer.get().get()(); +} + +void use_array_slots() { + Box source; + source.put(alpha); + Box> outer; + outer.put(source); + outer.get().get()(); +} + +void use_reference_slots() { + using LocalRefSlot = RefSlot; + Box source; + source.put(alpha); + Box> outer; + outer.put(source); + outer.get().get()(); +} +"#, + ) + .unwrap(); + let model = dir.path().join("box.toml"); + std::fs::write( + &model, + r#" +[[container]] +name = "Box" +element = 1 +operations = [ + { kind = "store", method = "put", arity = 1, value = 0 }, + { kind = "access", method = "get", arity = 0 }, +] +"#, + ) + .unwrap(); + let db = common::cli_analyze(dir.path(), &["--models", model.to_str().unwrap()]); + let conn = rusqlite::Connection::open(db.path()).unwrap(); + let mut query = conn + .prepare( + "SELECT callee.name FROM raw_call_edges AS edge \ + JOIN raw_functions AS caller ON caller.id = edge.caller_fn_id \ + JOIN raw_functions AS callee ON callee.id = edge.callee_fn_id \ + WHERE caller.name = ?1 AND edge.resolution = 'indirect' \ + ORDER BY callee.name", + ) + .unwrap(); + for (caller, expected) in [ + ("use_boxes", "beta"), + ("use_array_slots", "alpha"), + ("use_reference_slots", "alpha"), + ] { + let targets = query + .query_map([caller], |row| row.get::<_, String>(0)) + .unwrap() + .collect::>>() + .unwrap(); + assert_eq!(targets, [expected], "{caller}"); + } +} + +#[test] +fn pair_shaped_map_keys_do_not_contribute_mapped_callbacks() { + let dir = tempfile::tempdir().unwrap(); + std::fs::copy( + fixture("cpp_nested_containers").join("nested_containers.h"), + dir.path().join("nested_containers.h"), + ) + .unwrap(); + // Exercise lowering of incomplete or ill-typed code, as during edits. + std::fs::write( + dir.path().join("main.cpp"), + r#" +#include "nested_containers.h" +void alpha() {} +void unrelated() {} + +void nested_initializer() { + std::pair key{1, unrelated}; + std::vector, Callback>> outer = {{key, {}}}; + outer[0][key](); +} + +void mixed_initializer() { + std::pair key{1, unrelated}; + std::map, Callback> callbacks = {{{1, unrelated}, alpha}, key}; + callbacks[key](); +} + +void insert_with_invalid_mapped_brace() { + std::pair key{1, unrelated}; + std::map, Callback> callbacks; + callbacks[key] = alpha; + callbacks.insert({key, {1, 2}}); + callbacks.insert({std::make_pair(2, unrelated), {1, 2}}); + callbacks[key](); +} +"#, + ) + .unwrap(); + + let program = &build_program(dir.path(), &default_opts(dir.path())).expect("build"); + let (_, analysis) = analyze(program); + for caller in [ + "nested_initializer", + "mixed_initializer", + "insert_with_invalid_mapped_brace", + ] { + assert!( + must_not_have_edge(program, &analysis, caller, "unrelated"), + "{caller}" + ); + } + assert!(has_any_edge( + program, + &analysis, + "insert_with_invalid_mapped_brace", + "alpha" + )); +} + +#[test] +fn nested_subscript_macro_is_ignored_at_each_bracket() { + let root = fixture("cpp_nested_containers"); + let opts = default_opts(&root).with_ignored_macros(["OUTER_INDEX".to_owned()]); + let program = &build_program(&root, &opts).expect("build"); + let (_, analysis) = analyze(program); + assert!(must_not_have_edge( + program, + &analysis, + "nested_ignored_bracket", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_range_bracket", + "alpha" + )); +} + +#[test] +fn nested_range_field_macros_and_unevaluated_sites_are_preserved() { + let root = fixture("cpp_nested_containers"); + let opts = default_opts(&root).with_ignored_macros([ + "SLOT".to_owned(), + "METHOD".to_owned(), + "INNER".to_owned(), + "PAYLOAD".to_owned(), + "AT_METHOD".to_owned(), + "IDX".to_owned(), + "EXPLICIT_SLOT".to_owned(), + ]); + let program = &build_program(&root, &opts).expect("build"); + let (_, analysis) = analyze(program); + assert!(must_not_have_edge( + program, + &analysis, + "explicit_subscript_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_range_field_subscript", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_nested_field_bracket", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_method_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_typed_insert", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_named_payload", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_accessor_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_accessor_range", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_nested_accessor_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_accessor_assignment", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_receiver_chain_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_accessor_receiver_chain_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_parenthesized_receiver_chain_macro", + "alpha" + )); + assert!(must_not_have_edge( + program, + &analysis, + "ignored_range_pointer_macro", + "alpha" + )); + + let program = &build_program(&root, &default_opts(&root)).expect("build"); + for (name, expected) in [ + ("unevaluated_nested", 2), + ("unevaluated_at_chain", 1), + ("unevaluated_chained_accessor", 2), + ] { + let caller = *program + .symbols + .functions_named(name) + .first() + .expect("function"); + let sites: Vec<_> = program + .symbols + .call_sites + .iter() + .filter(|site| site.caller == caller && site.callee_name.contains("operator[]")) + .collect(); + assert_eq!(sites.len(), expected, "{name}: {sites:#?}"); + let positions: std::collections::BTreeSet<_> = sites + .iter() + .map(|site| (site.span.line, site.span.col)) + .collect(); + assert_eq!(positions.len(), expected, "{name}: {sites:#?}"); + assert!(sites.iter().all(|site| site.unevaluated), "{name}"); + } +} + +#[test] +fn map_three_level_single_pair_reads_mapped_container_once() { + let root = fixture("cpp_nested_containers"); + let program = &build_program(&root, &default_opts(&root)).expect("build"); + let (_, analysis) = analyze(program); + let count = analysis + .call_edges + .iter() + .filter(|edge| { + fn_name(program, edge.caller) == "map_three_level_single_pair" + && fn_name(program, edge.callee) == "alpha" + }) + .count(); + assert_eq!(count, 1, "mapped container read more than once"); +} + +#[test] +fn nested_container_models_gate_each_bracket_and_inner_initializer() { + let root = fixture("cpp_nested_containers"); + let dir = tempfile::tempdir().unwrap(); + let map_models = dir.path().join("map.toml"); + std::fs::write( + &map_models, + r#" +[[container]] +name = "std::map" +element = 1 +operations = [ + { kind = "store", method = "insert", arity = 1, value = 0, entry = 1 }, +] +"#, + ) + .unwrap(); + let map_access_models = dir.path().join("map_access.toml"); + std::fs::write( + &map_access_models, + r#" +[[container]] +name = "std::map" +element = 1 +operations = [ + { kind = "store", method = "insert", arity = 1, value = 0, entry = 1 }, + { kind = "access", method = "operator[]", arity = 1 }, +] +"#, + ) + .unwrap(); + let vector_models = dir.path().join("vector.toml"); + std::fs::write( + &vector_models, + r#" +[[container]] +name = "std::vector" +element = 0 +operations = [ + { kind = "store", method = "push_back", arity = 1, value = 0 }, + { kind = "access", method = "operator[]", arity = 1 }, +] +"#, + ) + .unwrap(); + let custom_models = dir.path().join("custom.toml"); + std::fs::write( + &custom_models, + r#" +[[container]] +name = "app::Custom" +element = 1 +operations = [ + { kind = "store", method = "insert", arity = 1, value = 0, entry = 1 }, + { kind = "access", method = "operator[]", arity = 1 }, +] +"#, + ) + .unwrap(); + let reaches_alpha = |models: &std::path::Path, caller: &str| { + let db = common::cli_analyze(&root, &["--models", models.to_str().unwrap()]); + let conn = rusqlite::Connection::open(db.path()).unwrap(); + conn.query_row( + "SELECT COUNT(*) FROM raw_call_edges AS edge \ + JOIN raw_functions AS caller ON caller.id = edge.caller_fn_id \ + JOIN raw_functions AS callee ON callee.id = edge.callee_fn_id \ + WHERE caller.name = ?1 AND callee.name = 'alpha'", + [caller], + |row| row.get::<_, i64>(0), + ) + .unwrap() + > 0 + }; + assert!(!reaches_alpha(&map_models, "map_without_subscript_model")); + assert!(!reaches_alpha( + &vector_models, + "map_inner_without_initializer" + )); + // `{}` value-initializes an inner container even when its model does not + // provide an initializer-list constructor, so the rest of the outer list + // must still be modeled. + assert!(reaches_alpha( + &vector_models, + "map_empty_inner_brace_without_initializer" + )); + // `{}` default-constructs an associative inner container too, even when + // the map model does not opt into `initializer_list`. + assert!(reaches_alpha( + &map_access_models, + "vector_empty_map_without_initializer" + )); + assert!(reaches_alpha(&custom_models, "custom_entry_insert")); +} + +#[test] +fn deep_specialization_alias_chains_keep_default_and_explicit_allocators_bounded() { + let dir = tempfile::tempdir().unwrap(); + let header = + std::fs::read_to_string(fixture("cpp_nested_containers").join("nested_containers.h")) + .unwrap(); + std::fs::write(dir.path().join("nested_containers.h"), header).unwrap(); + let mut main = String::from("#include \"nested_containers.h\"\nvoid alpha() {}\n"); + const LAST_LEVEL: usize = 27; + let access = "[0]".repeat(LAST_LEVEL + 1); + for (prefix, explicit) in [("Implicit", false), ("Explicit", true)] { + main.push_str(&format!("using {prefix}0 = std::vector;\n")); + for level in 1..=LAST_LEVEL { + let previous = format!("{prefix}{}", level - 1); + let allocator = if explicit { + format!(", std::allocator<{previous}>") + } else { + String::new() + }; + main.push_str(&format!( + "using {prefix}{level} = std::vector<{previous}{allocator}>;\n" + )); + } + main.push_str(&format!("void use_{prefix}() {{ {prefix}{LAST_LEVEL} value; value{access} = alpha; value{access}(); }}\n")); + } + main.push_str(&format!("void copy_across_spellings() {{ Implicit{LAST_LEVEL} inner; inner{access} = alpha; std::vector outer; outer.push_back(inner); outer[0]{access}(); }}\n")); + std::fs::write(dir.path().join("main.cpp"), main).unwrap(); + + let started = std::time::Instant::now(); + let program = build_program(dir.path(), &default_opts(dir.path())).expect("build"); + assert!( + started.elapsed() < std::time::Duration::from_secs(5), + "nested alias canonicalization took {:?}", + started.elapsed() + ); + let longest = program + .types + .all() + .iter() + .filter_map(|info| match info.desc.as_ref() { + TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => Some(name.len()), + _ => None, + }) + .max() + .unwrap_or(0); + assert!( + longest < 16_384, + "expanded specialization alias grew to {longest} characters" + ); + let (_, analysis) = analyze(&program); + for caller in ["use_Implicit", "use_Explicit", "copy_across_spellings"] { + assert!( + has_any_edge(&program, &analysis, caller, "alpha"), + "{caller}" + ); + } +} + #[test] fn cpp_declared_wrapper_keeps_template_arguments_for_pointee_calls() { let (program, analysis) = cpp_declared_wrapper(); diff --git a/crates/trace-ir/src/flow.rs b/crates/trace-ir/src/flow.rs index 2ab9fbb6..cf51e550 100644 --- a/crates/trace-ir/src/flow.rs +++ b/crates/trace-ir/src/flow.rs @@ -28,7 +28,28 @@ pub enum ReturnFlow { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ContainerOwner { Variable(VarId), - Field { class: TypeId, name: Arc }, + Field { + class: TypeId, + name: Arc, + }, + /// The elements carried by containers stored in another container's + /// element cell. `instance` is the inner container specialization, so + /// nested containers of distinct types keep distinct cells. + Nested { + parent: Arc, + instance: Arc, + }, +} + +/// The variable that owns a container cell, if the owner is rooted in one. +/// A field-owned cell has no variable; a nested cell follows its parent so +/// TU-local header storage replays the initializer with the root variable. +fn container_owner_var(owner: &ContainerOwner) -> Option { + match owner { + ContainerOwner::Variable(var) => Some(*var), + ContainerOwner::Field { .. } => None, + ContainerOwner::Nested { parent, .. } => container_owner_var(parent), + } } /// Statement-level flow facts extracted during IR lowering. @@ -112,10 +133,9 @@ impl FlowConstraint { | FlowConstraint::AddrOfVar { dst, src } | FlowConstraint::UnwrapPointer { dst, src } => (dst, Some(src)), FlowConstraint::GepField { dst, base, .. } => (dst, Some(base)), - FlowConstraint::ContainerElement { dst, ref owner, .. } => match owner { - ContainerOwner::Variable(var) => (dst, Some(*var)), - ContainerOwner::Field { .. } => (dst, None), - }, + FlowConstraint::ContainerElement { dst, ref owner, .. } => { + (dst, container_owner_var(owner)) + } FlowConstraint::CallReturnIndirect { dst, callee_var } => (dst, Some(callee_var)), FlowConstraint::ArrayFnMember { array, .. } => (array, None), FlowConstraint::AddrOfFn { dst, .. } diff --git a/crates/trace-parse/src/container_elements.rs b/crates/trace-parse/src/container_elements.rs index 5ee4a2a9..21cec192 100644 --- a/crates/trace-parse/src/container_elements.rs +++ b/crates/trace-parse/src/container_elements.rs @@ -1,6 +1,6 @@ use super::*; use std::ops::RangeInclusive; -use std::sync::{mpsc, OnceLock}; +use std::sync::{mpsc, Arc, OnceLock}; use trace_ir::{ ContainerModel, ContainerOperation, ContainerOwner, ContainerTemplateDefault, ContainerTemplateDefaults, TypeId, @@ -182,6 +182,124 @@ fn list_constructors<'a>( signatures.chain(symbols) } +fn list_constructor_accepts( + program: &Program, + ctx: &LowerContext, + owner: &str, + model: &ContainerModel, + arity: usize, + value_initialized_allocator: bool, +) -> bool { + if program.types.is_struct_defined(owner) { + list_constructors(program, owner, model) + .any(|ctor| ctor.accepts(arity, value_initialized_allocator)) + } else { + canonical_declarations(ctx) + .and_then(|decls| decls.list_constructors.get(owner)) + .is_some_and(|ctors| { + ctors + .iter() + .any(|ctor| ctor.accepts(arity, value_initialized_allocator)) + }) + } +} + +/// Whether an inner clause can call an ordinary constructor (for example the +/// count/value constructor of a vector) even though its contents are not +/// modeled as container elements. +fn ordinary_constructor_accepts( + program: &Program, + ctx: &LowerContext, + source: &str, + owner: &str, + model: &ContainerModel, + node: Node, +) -> bool { + let argc = if node.cached_kind() == "initializer_list" { + let mut cursor = node.walk(); + node.named_children(&mut cursor) + .filter(|child| child.cached_kind() != "comment") + .count() + } else { + arguments(node).map_or(0, |args| args.len()) + }; + // `{}` value-initializes any modeled container through its default + // constructor, not just a sequence container and not necessarily through + // `std::initializer_list`. + if argc == 0 { + return true; + } + // Count/value and size constructors are only relevant for sequence + // containers; treating any 2-argument constructor as an ordinary match + // would accept map compare/iterator constructors too. + if !matches!( + canonical_std_class(&model.name).as_str(), + "std::vector" | "std::deque" | "std::list" | "std::forward_list" + ) { + return false; + } + let first = if node.cached_kind() == "initializer_list" { + let mut cursor = node.walk(); + let first = node + .named_children(&mut cursor) + .find(|child| child.cached_kind() != "comment"); + first + } else { + arguments(node).and_then(|args| args.first().copied()) + }; + let Some(first) = first.map(peel_expression) else { + return false; + }; + if !integer_offset_type( + program, + ctx, + &arithmetic_operand_desc(program, ctx, source, first, true), + ) { + return false; + } + let declared: Vec<_> = declared_members_upward(program, owner, &trace_ir::MethodKind::Ctor) + .into_iter() + .filter(|&id| { + method_explicit_arity(program, id) + .is_some_and(|arity| arity_takes(program.symbols.function(id), arity, argc)) + }) + .collect(); + let signatures = program.types.constructor_signatures(owner); + let accepts_signature = |signature: &trace_ir::ConstructorSignature| { + let fixed = signature.parameters.len(); + let minimum = fixed.saturating_sub(signature.default_args as usize); + argc >= minimum + && (signature.variadic || argc <= fixed) + && signature.parameters.first().is_some_and(|param| { + let desc = if signature.references.first() == Some(&true) { + param.pointee().unwrap_or(param) + } else { + param.as_ref() + }; + integer_offset_type(program, ctx, desc) + }) + }; + if declared.iter().any(|&id| { + program + .symbols + .explicit_params(program.symbols.function(id)) + .and_then(|params| params.get(0)) + .is_some_and(|ty| { + integer_offset_type(program, ctx, program.types.get(ty).desc.as_ref()) + }) + }) || signatures.iter().any(accepts_signature) + { + return true; + } + // Canonical-prelude standard containers have no local body. Their indexed + // signatures are unavailable here, but the sequence count constructor is + // part of the modeled API, so keep the clause viable. + !program.types.is_struct_defined(owner) + && argc <= 3 + && signatures.is_empty() + && declared_members_upward(program, owner, &trace_ir::MethodKind::Ctor).is_empty() +} + pub(super) struct BracedConstructors { pub targets: Vec, pub wrap_list: bool, @@ -198,7 +316,7 @@ pub(super) fn braced_constructor_targets( let elements = Elements::for_var(program, ctx, var)?; let class = elements.class(); let model = ctx.container_models.get(class)?; - if !model.initializer_list || copies_container(program, ctx, source, init, class) { + if !model.initializer_list || copies_container(program, ctx, source, init, &elements.instance) { return None; } let owner = member_lookup_owner(program, ctx, &elements.instance); @@ -289,9 +407,13 @@ fn list_initialization<'t>( init: Node<'t>, accepts: impl Fn(usize, bool) -> bool, ) -> Option> { - let viable = |values, argc, value_initialized_allocator| { + let key = model + .initializer_entry + .and_then(|_| elements.map_key()) + .map(|key| canonical_alias_spelling(program, ctx, key)); + let viable = |values, argc, value_initialized_allocator, allow_empty_entry| { (accepts(argc, value_initialized_allocator) - && !copies_container(program, ctx, source, values, elements.class())) + && !copies_container(program, ctx, source, values, &elements.instance)) .then_some(())?; let uncertain = list_element_conversions( program, @@ -299,7 +421,9 @@ fn list_initialization<'t>( source, values, model.initializer_entry, + key.as_deref(), &elements.element, + allow_empty_entry, )?; Some(ListInitialization { values, @@ -316,21 +440,27 @@ fn list_initialization<'t>( .named_children(&mut allocator.walk()) .any(|child| child.cached_kind() != "comment") { - // C++ first tries the entire outer list as one argument. - // For example, {{alpha}, {}} holds alpha and a null callback. - return viable(init, 1, false).or_else(|| viable(values, 2, true)); + // A trailing empty brace is an allocator only when the + // first clause is itself a whole list of entries. When it + // is a single entry, C++ reads the whole list as two + // entries, the second default-constructed. + let entry_list = viable(values, 2, true, true); + if entry_list.is_some() { + return viable(init, 1, false, false).or(entry_list); + } + return viable(init, 1, false, true); } if allocator_argument(program, ctx, source, elements, model, allocator) { - return viable(values, 2, false).or_else(|| viable(init, 1, false)); + return viable(values, 2, false, true).or_else(|| viable(init, 1, false, true)); } } - viable(init, 1, false) + viable(init, 1, false, true) } "argument_list" => { let args = arguments(init)?; let values = *args.first()?; (values.cached_kind() == "initializer_list").then_some(())?; - viable(values, args.len(), false) + viable(values, args.len(), false, true) } _ => None, } @@ -358,7 +488,7 @@ fn allocator_argument( let arg = peel_expression(arg); let spelling = if arg.cached_kind() == "compound_literal_expression" { arg.cached_field("type") - .and_then(|ty| type_spelling_for(program, ctx, source, ty, ty, 0)) + .and_then(|ty| type_spelling_node(program, ctx, source, ty)) } else { match known_arg_type(program, ctx, source, arg) { TypeDesc::Struct { name, .. } => Some(name), @@ -369,8 +499,12 @@ fn allocator_argument( return false; }; let matches_instantiation = model.initializer_allocator.is_some_and(|position| { - trace_ir::split_instance(&elements.instance) - .is_some_and(|(_, args)| args.get(position) == Some(&spelling.as_str())) + trace_ir::split_instance(&elements.instance).is_some_and(|(_, args)| { + args.get(position).is_some_and(|arg| { + canonical_specialization(program, ctx, arg) + == canonical_specialization(program, ctx, &spelling) + }) + }) }); matches_instantiation || { let owner = member_lookup_owner(program, ctx, &elements.instance); @@ -395,15 +529,848 @@ fn allocator_argument( } } +/// Canonical specialization spelling with recorded aliases expanded, so the +/// same C++ type compared on both sides of a copy reaches its descendant +/// cells even when the source and destination store different spellings. +fn canonical_specialization(program: &Program, ctx: &LowerContext, spelling: &str) -> String { + canonical_specialization_at(program, ctx, spelling, 0, true) +} + +/// Expand recorded aliases without collapsing the whitespace of an ordinary +/// scalar or pointer spelling (`const int`, `void (*)()`). +fn canonical_alias_spelling(program: &Program, ctx: &LowerContext, spelling: &str) -> String { + canonical_alias_spelling_at(program, ctx, spelling.trim(), 0) +} + +fn canonical_alias_spelling_at( + program: &Program, + ctx: &LowerContext, + spelling: &str, + depth: u32, +) -> String { + // A cv-qualified key alias (`const CallbackKey`) still names the same + // alias for key-shape classification. + let spelling = without_leading_cv(spelling); + if depth >= 64 { + return spelling.to_owned(); + } + if let Some(alias) = program.types.alias_type_spelling(spelling) { + if alias.trim() != spelling { + return canonical_alias_spelling_at(program, ctx, alias.trim(), depth + 1); + } + } + if let Some(desc) = program.types.resolve_alias(spelling) { + return canonical_desc_at(program, ctx, desc, depth + 1, false); + } + spelling.to_owned() +} + +/// Long specialization identities are replaced by a stable digest. This +/// bounds an alias chain that would otherwise duplicate the previous spelling +/// into both the element and default-allocator slots at every level. The +/// digest is an internal identity key, not a display spelling. +const COMPACT_IDENTITY_THRESHOLD: usize = 4_096; + +/// A leaf spelling has no template arguments to walk. Collapse spacing the +/// same way registered specialization keys do, and treat `void (*)()` and +/// `void (*)(void)` as the same function-pointer type. +fn normalize_leaf_spelling(spelling: &str) -> String { + normalize_spacing(spelling).replace("(void)", "()") +} + +fn compact_identity(spelling: &str) -> String { + let mut hash = 0xcbf2_9ce4_8422_2325u64; + for byte in spelling.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("#{hash:016x}") +} + +fn maybe_compact_identity(spelling: String) -> String { + if spelling.len() > COMPACT_IDENTITY_THRESHOLD { + compact_identity(&spelling) + } else { + spelling + } +} + +fn canonical_specialization_at( + program: &Program, + ctx: &LowerContext, + spelling: &str, + depth: u32, + strip_cv: bool, +) -> String { + // Leading cv-qualification does not change the outer container's element + // identity, but it does distinguish template arguments such as + // `std::vector` from `std::vector`. + let spelling = if strip_cv { + without_leading_cv(spelling.trim()).trim() + } else { + spelling.trim() + }; + if depth >= 64 { + return normalize_leaf_spelling(spelling); + } + if let Some(alias) = program.types.alias_type_spelling(spelling) { + if alias.trim() != spelling { + return canonical_specialization_at(program, ctx, alias, depth + 1, strip_cv); + } + } + if let Some(desc) = program.types.resolve_alias(spelling) { + return canonical_desc_at(program, ctx, desc, depth + 1, strip_cv); + } + let Some((class, args)) = trace_ir::split_instance(spelling) else { + return normalize_leaf_spelling(spelling); + }; + let canonical_class = canonical_std_class(class); + let owner = ctx + .container_models + .get(&canonical_class) + .and_then(|model| { + indexed_owner(program, model).or_else(|| { + canonical_declarations(ctx)? + .owners + .get(&model.name) + .map(String::as_str) + }) + }) + .unwrap_or(canonical_class.as_str()); + let mut args: Vec = args + .iter() + .map(|arg| { + maybe_compact_identity(canonical_specialization_at( + program, + ctx, + arg, + depth + 1, + false, + )) + }) + .collect(); + // Fill template defaults that the written spelling omitted, so an + // explicit default allocator and its omission share one identity. The + // canonical prelude carries defaults when the declaration is absent here. + if let Some(defaults) = class_template_defaults(program, ctx, class) { + while let Some(value) = defaults + .get(&args.len()) + .and_then(|default| default.bind(&args)) + { + args.push(maybe_compact_identity(canonical_specialization_at( + program, + ctx, + &value, + depth + 1, + false, + ))); + } + } + maybe_compact_identity(format!("{owner}<{}>", args.join(","))) +} + +fn canonical_desc_at( + program: &Program, + ctx: &LowerContext, + desc: &TypeDesc, + depth: u32, + strip_cv: bool, +) -> String { + if depth >= 64 { + return canonical_scalar(desc).unwrap_or_else(|| format!("{desc:?}").replace(' ', "")); + } + match desc { + TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => { + canonical_specialization_at(program, ctx, name, depth + 1, strip_cv) + } + TypeDesc::Ptr(inner) => match inner.as_ref() { + TypeDesc::FnPtr { ret, params } => { + canonical_fn_ptr_at(program, ctx, ret, params, depth + 1) + } + _ => format!( + "{}*", + canonical_desc_at(program, ctx, inner, depth + 1, false) + ), + }, + TypeDesc::Array { elem, .. } => { + format!( + "{}[]", + canonical_desc_at(program, ctx, elem, depth + 1, false) + ) + } + TypeDesc::FnPtr { ret, params } => { + canonical_fn_ptr_at(program, ctx, ret, params, depth + 1) + } + other => canonical_scalar(other).unwrap_or_else(|| format!("{other:?}").replace(' ', "")), + } +} + +fn canonical_scalar(desc: &TypeDesc) -> Option { + Some( + match desc { + TypeDesc::Void => "void", + TypeDesc::Char => "char", + TypeDesc::Bool => "bool", + TypeDesc::Short => "short", + TypeDesc::Int => "int", + TypeDesc::Long => "long", + TypeDesc::LongLong => "long long", + TypeDesc::Float => "float", + TypeDesc::Double => "double", + TypeDesc::SizeT => "size_t", + TypeDesc::Unknown => "unknown", + TypeDesc::Ellipsis => "...", + _ => return None, + } + .to_owned(), + ) +} + +fn canonical_fn_ptr_at( + program: &Program, + ctx: &LowerContext, + ret: &TypeDesc, + params: &[TypeDesc], + depth: u32, +) -> String { + // `void (*)()` and `void (*)(void)` are the same type. + let params: Vec<_> = if matches!(params, [TypeDesc::Void]) { + Vec::new() + } else { + params + .iter() + .map(|param| canonical_desc_at(program, ctx, param, depth + 1, false)) + .collect() + }; + format!( + "{}(*)({})", + canonical_desc_at(program, ctx, ret, depth + 1, false), + params.join(",") + ) +} + +/// A descriptor naming a modeled container, whose braced form must be +/// interpreted at the inner container level rather than as a scalar element. +fn modeled_container_desc(ctx: &LowerContext, desc: &TypeDesc) -> bool { + let TypeDesc::Struct { name, .. } = desc else { + return false; + }; + ctx.container_models + .get( + name.split_once('<') + .map_or(name.as_str(), |(class, _)| class), + ) + .is_some() +} + +/// A multi-clause braced key only fits an aggregate/pair key. A scalar, +/// pointer or function-pointer key takes a single braced element (or none). +fn key_braced_accepts( + program: &Program, + ctx: &LowerContext, + source: &str, + node: Node, + spelling: Option<&str>, +) -> bool { + let Some(spelling) = spelling else { + return true; + }; + let node = peel_expression(node); + let (bare, suffix) = trace_ir::split_pointer_suffix(spelling); + let pointer_like = !suffix.trim().is_empty(); + let bare = bare.trim(); + // Only a specialization whose closing `>` ends the spelling has a class + // base. A function-pointer key returning `Foo` must keep its `(*` + // declarator instead of being truncated at the return type's `<`. + let base = trace_ir::split_instance(bare) + .map_or(bare, |(base, _)| base) + .trim(); + let base = without_leading_cv(base); + let pair = canonical_std_class(base) == "std::pair"; + let enum_lookup = |name: &str| program.types.enum_is_scoped(name); + let aggregate = !pointer_like + && !is_fundamental_type_name(base) + && !base.contains("(*") + && !base.contains("(&") + // An unscoped enum reads as an integer in the expression probe below. + // Its enumerators still initialize an enum key without a constructor. + && resolve_function_named_with_imports(program, ctx, base, enum_lookup, enum_lookup) + .is_none(); + let mut cursor = node.walk(); + let clauses = node.cached_kind().eq("initializer_list").then(|| { + node.named_children(&mut cursor) + .filter(|clause| clause.cached_kind() != "comment") + .count() + }); + if pointer_like { + // A pointer key takes one expression (including null); it cannot be + // initialized from a multi-clause braced list. + return clauses.is_none_or(|clauses| clauses <= 1); + } + let Some(clauses) = clauses else { + if pair || aggregate { + let argument = key_argument_desc(program, ctx, source, node); + return key_type_may_convert( + program, + ctx, + &argument, + spelling, + is_null_constant(source, node), + ); + } + return true; + }; + if pair { + match clauses { + // `{}` value-initializes a default-constructible pair key. + 0 => true, + 2 => true, + // A single clause copy-list-initializes the pair key from a + // compatible same-type expression (`{key}`). + 1 => { + let mut cursor = node.walk(); + let clause = node + .named_children(&mut cursor) + .find(|clause| clause.cached_kind() != "comment"); + clause.is_some_and(|clause| { + key_type_may_convert( + program, + ctx, + &key_argument_desc(program, ctx, source, clause), + spelling, + false, + ) + }) + } + _ => false, + } + } else { + clauses <= 1 || aggregate + } +} + +/// Whether a descriptor names the type `spelling`, including a primary-template +/// layout that kept its base name but carries the instantiated fields. +fn desc_matches_type_spelling( + program: &Program, + ctx: &LowerContext, + desc: &TypeDesc, + spelling: &str, +) -> bool { + if class_spelling_of_desc(desc).is_some_and(|name| { + canonical_specialization(program, ctx, name) + == canonical_specialization(program, ctx, spelling) + }) { + return true; + } + let (TypeDesc::Struct { name, fields }, Some((class, args))) = + (desc, trace_ir::split_instance(spelling)) + else { + return false; + }; + name == class + && fields.len() == args.len() + && fields.iter().zip(args).all(|((_, field), arg)| { + canonical_desc_at(program, ctx, field, 0, false) + == canonical_specialization_at(program, ctx, arg, 0, false) + }) +} + +/// Preserve the pointer shape of a callable designator that the ordinary +/// expression type probe could leave unknown. +fn key_argument_desc(program: &Program, ctx: &LowerContext, source: &str, node: Node) -> TypeDesc { + let node = peel_expression(node); + let desc = receiver_desc(program, ctx, source, node) + .unwrap_or_else(|| arithmetic_operand_desc(program, ctx, source, node, true)); + if matches!(desc, TypeDesc::Unknown) + && (node.cached_kind() == "lambda_expression" + || fn_designator(source, node) + .is_some_and(|name| resolve_fn_ref(program, ctx, source, name).is_some())) + { + return TypeDesc::Ptr(Box::new(TypeDesc::Unknown)); + } + desc +} + +/// Whether an indexed key has a one-argument constructor whose parameter +/// could bind this argument. Both ordinary and types-only declarations count. +fn class_accepts_key_argument( + program: &Program, + ctx: &LowerContext, + class: &str, + arg: &TypeDesc, + null_constant: bool, +) -> bool { + let is_numeric = |desc: &TypeDesc| { + integer_offset_type(program, ctx, desc) + || matches!(desc, TypeDesc::Float | TypeDesc::Double) + }; + let accepts = |param: &TypeDesc, reference| { + let param = if reference { + param.pointee().unwrap_or(param) + } else { + param + }; + arg == param + || matches!(param, TypeDesc::Unknown) + || (is_numeric(arg) && is_numeric(param)) + || ((null_constant || arg.is_pointer_like() || matches!(arg, TypeDesc::Array { .. })) + && param.is_pointer_like()) + || (arg.is_pointer_like() && matches!(param, TypeDesc::Bool)) + || (arg.is_class_like() + && param.is_class_like() + && (trace_ir::may_name_same_type(arg, param) + || class_conversion_possible(program, arg, param))) + }; + let declared = declared_members_upward(program, class, &trace_ir::MethodKind::Ctor) + .into_iter() + .any(|id| { + let function = program.symbols.function(id); + method_explicit_arity(program, id).is_some_and(|arity| arity_takes(function, arity, 1)) + && program + .symbols + .explicit_params(function) + .and_then(|params| params.get(0)) + .is_some_and(|ty| { + accepts( + program.types.get(ty).desc.as_ref(), + function.reference_params.first() == Some(&true), + ) + }) + }); + declared + || program + .types + .constructor_signatures(class) + .iter() + .any(|signature| { + signature.parameters.first().is_some_and(|param| { + accepts(param, signature.references.first() == Some(&true)) + }) && signature + .parameters + .len() + .saturating_sub(signature.default_args as usize) + <= 1 + }) +} + +fn without_leading_cv(mut spelling: &str) -> &str { + loop { + let trimmed = spelling.trim_start(); + let rest = trimmed + .strip_prefix("const") + .or_else(|| trimmed.strip_prefix("volatile")); + match rest { + Some(rest) if rest.chars().next().is_some_and(char::is_whitespace) => spelling = rest, + _ => return trimmed, + } + } +} + +/// A conversion can make a list viable even when there is no source element +/// cell to copy. Class hierarchies can retain a template base's primary name. +fn inner_value_may_convert( + program: &Program, + ctx: &LowerContext, + desc: &TypeDesc, + expected: &str, +) -> bool { + let TypeDesc::Struct { name, .. } = desc else { + return matches!(desc, TypeDesc::Unknown); + }; + let expected_identity = canonical_specialization(program, ctx, expected); + canonical_specialization(program, ctx, name) == expected_identity + || program + .ancestor_closure(name) + .into_iter() + .skip(1) + .any(|(base, _)| { + canonical_specialization(program, ctx, base) == expected_identity + || base == receiver_lookup_name(expected).as_ref() + }) + || class_may_convert(program, desc) +} + +/// Whether a braced value can initialize a modeled inner container, including +/// its initializer-list or ordinary constructors and allocator clauses. +fn inner_container_viable( + program: &Program, + ctx: &LowerContext, + source: &str, + element: &TypeDesc, + node: Node, +) -> Option { + let TypeDesc::Struct { name, .. } = element else { + return None; + }; + let node = peel_expression(node); + if !matches!( + node.cached_kind(), + "initializer_list" | "argument_list" | "compound_literal_expression" + ) { + // A declared return type is enough to identify a container value even + // when lowering has no element cell for the expression; the cell is + // required only to emit a copy. + let has_cell = Elements::for_receiver(program, ctx, source, node).is_some_and(|from| { + canonical_specialization(program, ctx, &from.instance) + == canonical_specialization(program, ctx, name) + }); + return Some( + has_cell || { + let desc = receiver_desc(program, ctx, source, node) + .unwrap_or_else(|| known_arg_type(program, ctx, source, node)); + let known_callable = matches!(desc, TypeDesc::Unknown) + && (node.cached_kind() == "lambda_expression" + || fn_designator(source, node).is_some_and(|designator| { + resolve_fn_ref(program, ctx, source, designator).is_some() + })); + !known_callable && inner_value_may_convert(program, ctx, &desc, name) + }, + ); + } + // A single braced named container is a copy. `list_initialization` + // deliberately rejects it so the list reading cannot swallow the source, + // but the copy is still a viable inner value. + if copies_container(program, ctx, source, node, name) { + return Some(true); + } + let class = name + .split_once('<') + .map_or(name.as_str(), |(class, _)| class); + let model = ctx.container_models.get(class)?; + let synthetic = Elements::new(program, ctx, ContainerOwner::Variable(VarId(0)), element)?; + if node.cached_kind() == "compound_literal_expression" { + let ty = node.cached_field("type")?; + let spelling = type_spelling_node(program, ctx, source, ty)?; + let desc = TypeDesc::Struct { + name: spelling, + fields: Vec::new(), + }; + if inner_value_may_convert(program, ctx, &desc, name) { + return Some(true); + } + return Some( + model.initializer_list + && initializer_list_compound_brace(program, ctx, source, node, synthetic.element()) + .is_some(), + ); + } + if allocator_extended_copy(program, ctx, source, &synthetic, node).is_some() { + return Some(true); + } + let owner = member_lookup_owner(program, ctx, name); + if model.initializer_list + && list_initialization( + program, + ctx, + source, + &synthetic, + model, + node, + |arity, value_initialized_allocator| { + list_constructor_accepts( + program, + ctx, + &owner, + model, + arity, + value_initialized_allocator, + ) + }, + ) + .is_some() + { + return Some(true); + } + Some(ordinary_constructor_accepts( + program, ctx, source, &owner, model, node, + )) +} + +/// A viable entry may carry no modeled value, as with a default-initialized +/// entry or a call returning a pair. +enum PairEntry<'t> { + Mapped(StoredValue<'t>), + Unmodeled, +} + +fn pair_clause_entry<'t>( + program: &Program, + ctx: &LowerContext, + source: &str, + clause: Node<'t>, + entry: usize, + key: Option<&str>, + element: &TypeDesc, +) -> Option> { + let clause = peel_expression(clause); + if let Some(args) = make_pair_arguments(source, clause) { + let node = *args.get(entry)?; + if key.is_some() { + let first = key_argument_desc(program, ctx, source, args[0]); + if !pair_key_may_convert(program, ctx, &first, key) { + return None; + } + } + let viable = if modeled_container_desc(ctx, element) { + inner_container_viable(program, ctx, source, element, node) == Some(true) + } else { + let ty = receiver_desc(program, ctx, source, node) + .unwrap_or_else(|| known_arg_type(program, ctx, source, node)); + is_null_constant(source, node) + || node.cached_kind() == "lambda_expression" + || fn_designator(source, node) + .is_some_and(|name| resolve_fn_ref(program, ctx, source, name).is_some()) + || pair_member_matches_element(program, ctx, &ty, element) + }; + return viable.then_some(PairEntry::Mapped(StoredValue::Expression(node))); + } + if entry == 1 && is_name(clause) { + if let Some((var, pair)) = lookup_var_node(program, ctx, source, clause) + .and_then(|var| Some((var, pair_type(program, var)?))) + { + if field_in_pair(program, pair, "first").is_some_and(|(_, ty)| { + !pair_key_may_convert(program, ctx, program.types.get(ty).desc.as_ref(), key) + }) { + return None; + } + if let Some((field, ty)) = field_in_pair(program, pair, "second") { + return pair_member_matches_element( + program, + ctx, + program.types.get(ty).desc.as_ref(), + element, + ) + .then_some(PairEntry::Mapped(StoredValue::PairSecond( + clause, var, pair, field, ty, + ))); + } + } + } + pair_expression_matches_element(program, ctx, source, clause, key, element) + .then_some(PairEntry::Unmodeled) +} + +/// Whether a pair's mapped member descriptor fits the modeled element. +fn pair_member_matches_element( + program: &Program, + ctx: &LowerContext, + desc: &TypeDesc, + element: &TypeDesc, +) -> bool { + if modeled_container_desc(ctx, element) { + let TypeDesc::Struct { name: expected, .. } = element else { + return false; + }; + inner_value_may_convert(program, ctx, desc, expected) + } else { + matches!(desc, TypeDesc::Unknown) + || trace_ir::may_name_same_type(desc, element) + || (desc.is_pointer_like() && element.is_pointer_like()) + || (desc.is_class_like() && class_may_convert(program, desc)) + } +} + +/// Whether an unmodeled expression is a `std::pair` whose mapped member fits +/// the modeled element, so it can stand as one map entry without a stored +/// value. +fn pair_expression_matches_element( + program: &Program, + ctx: &LowerContext, + source: &str, + clause: Node, + key: Option<&str>, + element: &TypeDesc, +) -> bool { + let Some(desc) = receiver_desc(program, ctx, source, clause) else { + return false; + }; + // A class with a conversion operator (or an unresolved expression) may + // still convert to the entry pair type. Keep it viable without emitting + // flow for the value. + if matches!(desc, TypeDesc::Unknown) + || desc.is_class_like() && class_may_convert(program, &desc) + { + return true; + } + let TypeDesc::Struct { name, fields } = &desc else { + return false; + }; + let Some((class, args)) = trace_ir::split_instance(name) else { + return false; + }; + if !is_std_pair(class) || args.len() != 2 { + return false; + } + // A call result can retain the written specialization alongside a + // primary-template field layout. Use the written key in that case. + if key.is_some() + && !pair_key_may_convert( + program, + ctx, + &key_component_desc(program, ctx, args[0]), + key, + ) + { + return false; + } + if let Some((_, second)) = fields.iter().find(|(field, _)| field == "second") { + return pair_member_matches_element(program, ctx, second, element); + } + // A pair whose mapped member is not pointer-like or modeled may not carry + // a field layout; compare the written mapped template argument instead. + canonical_specialization_at(program, ctx, args[1], 0, false) + == canonical_desc_at(program, ctx, element, 0, false) +} + +fn pair_key_may_convert( + program: &Program, + ctx: &LowerContext, + first: &TypeDesc, + key: Option<&str>, +) -> bool { + key.is_none_or(|key| key_type_may_convert(program, ctx, first, key, false)) +} + +fn key_type_may_convert( + program: &Program, + ctx: &LowerContext, + arg: &TypeDesc, + key: &str, + null_constant: bool, +) -> bool { + key_type_may_convert_at(program, ctx, arg, key, null_constant, 0) +} + +/// A pair-shaped key is itself a possible list entry only if its first +/// member can initialize the entire key. Check converting pairs by component +/// so a shallower pair cannot stand in for a nested pair key. +fn key_type_may_convert_at( + program: &Program, + ctx: &LowerContext, + arg: &TypeDesc, + key: &str, + null_constant: bool, + depth: u32, +) -> bool { + if matches!(arg, TypeDesc::Unknown) || depth >= MAX_AST_WALK_DEPTH { + return true; + } + let (base, suffix) = trace_ir::split_pointer_suffix(key); + let base = without_leading_cv(trace_ir::strip_trailing_cv(base)); + let pointer_key = suffix.contains('*') || split_function_pointer_star(base).is_some(); + if pointer_key { + return null_constant + || arg.is_pointer_like() + || matches!(arg, TypeDesc::Array { .. }) + || class_may_convert(program, arg); + } + if arg.is_class_like() && desc_matches_type_spelling(program, ctx, arg, base) { + return true; + } + if let Some(expected) = pair_type_arguments(base) { + let component_fits = |from: &TypeDesc, to| { + let to = canonical_alias_spelling(program, ctx, to); + key_type_may_convert_at(program, ctx, from, &to, false, depth + 1) + }; + if let TypeDesc::Struct { name, fields } = arg { + if let Some(actual) = pair_type_arguments(name) { + return actual + .into_iter() + .zip(expected) + .all(|(from, to)| component_fits(&key_component_desc(program, ctx, from), to)) + || class_may_convert(program, arg); + } + if is_std_pair(name) { + // An instantiated pair with unmodeled members can keep its + // primary name. Use any member types the index still has. + return ["first", "second"] + .into_iter() + .zip(expected) + .all(|(member, to)| { + fields + .iter() + .find(|(name, _)| name == member) + .is_none_or(|(_, from)| component_fits(from, to)) + }); + } + } + return class_may_convert(program, arg); + } + if is_fundamental_type_name(base) { + return integer_offset_type(program, ctx, arg) + || matches!(arg, TypeDesc::Float | TypeDesc::Double) + || (base == "bool" && arg.is_pointer_like()) + || class_may_convert(program, arg); + } + if program.types.enum_is_scoped(base).is_some() { + return class_may_convert(program, arg); + } + let owner = receiver_lookup_name(base); + !program.types.is_struct_defined(&owner) + || class_may_convert(program, arg) + || matches!(arg, TypeDesc::Struct { name, .. } + if program.derives_from(&receiver_lookup_name(name), &owner)) + || class_accepts_key_argument(program, ctx, &owner, arg, null_constant) +} + +fn pair_type_arguments(spelling: &str) -> Option<[&str; 2]> { + let (class, args) = trace_ir::split_instance(spelling)?; + if !is_std_pair(class) { + return None; + } + args.try_into().ok() +} + +/// Pair descriptors can omit their field layouts. Recover enough of a written +/// component type to compare pointer, numeric, and structured key shapes. +fn key_component_desc(program: &Program, ctx: &LowerContext, spelling: &str) -> TypeDesc { + let spelling = canonical_alias_spelling(program, ctx, spelling); + let (bare, suffix) = trace_ir::split_pointer_suffix(&spelling); + let bare = trace_ir::strip_trailing_cv(bare); + if suffix.contains('*') || split_function_pointer_star(bare).is_some() || bare.ends_with(']') { + TypeDesc::Ptr(Box::new(TypeDesc::Unknown)) + } else if is_fundamental_type_name(bare) { + match bare { + "auto" | "nullptr_t" => TypeDesc::Unknown, + "void" => TypeDesc::Void, + _ => primitive_scalar_desc(bare).unwrap_or(TypeDesc::Int), + } + } else { + TypeDesc::Struct { + name: bare.to_owned(), + fields: Vec::new(), + } + } +} + +/// A known constructor set without a default overload rules out `{}` as +/// an entry. An implicit or unindexed constructor leaves it viable. +fn map_entry_can_default(program: &Program, key: Option<&str>, mapped: &TypeDesc) -> bool { + let can_default = |name: &str| { + let owner = receiver_lookup_name(name); + !program.types.has_declared_constructor(&owner) + || program.types.default_constructor(&owner).is_some() + }; + key.is_none_or(can_default) + && match mapped { + TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => can_default(name), + _ => true, + } +} + /// `None` for an incompatible clause, `Some(true)` for a conversion whose /// viability is unknown, and `Some(false)` for a viable list. +#[allow(clippy::too_many_arguments)] fn list_element_conversions( program: &Program, ctx: &LowerContext, source: &str, init: Node, entry: Option, + key: Option<&str>, element: &TypeDesc, + allow_empty_entry: bool, ) -> Option { // The modeled elements are pointers or callables. Arithmetic cannot // initialize one, except for a null pointer constant. Keep clauses of @@ -412,8 +1379,56 @@ fn list_element_conversions( let viable = init .named_children(&mut init.walk()) .filter(|value| value.cached_kind() != "comment") - .map(|value| braced_value(value, entry).unwrap_or(value)) - .all(|mut value| { + .map(|value| { + if entry.is_none() { + return Some(Some(value)); + } + let entry_node = compound_pair_brace(program, ctx, source, value).unwrap_or(value); + if entry_node.cached_kind() != "initializer_list" { + return pair_clause_entry( + program, + ctx, + source, + value, + entry.expect("map entry"), + key, + element, + ) + .is_some() + .then_some(None); + } + // A trailing empty allocator clause is classified separately. + if braced_clause_count(entry_node) == Some(0) { + return (allow_empty_entry && map_entry_can_default(program, key, element)) + .then_some(None); + } + let mapped = braced_value(entry_node, entry)?; + if let Some(key) = key { + let key_node = braced_value(entry_node, Some(0))?; + if !key_braced_accepts(program, ctx, source, key_node, Some(key)) { + return None; + } + } + Some(Some(mapped)) + }) + .all(|mapped| { + let Some(mapped) = mapped else { + return false; + }; + let Some(mut value) = mapped else { + return true; + }; + let root = value; + // Modeled inner containers validate their own brace via their + // initializer-list or ordinary constructors, whether it has one + // clause or several. + if modeled_container_desc(ctx, element) { + if inner_container_viable(program, ctx, source, element, root) == Some(true) { + uncertain = true; + return true; + } + return false; + } while value.cached_kind() == "initializer_list" { let mut cursor = value.walk(); let mut clauses = value @@ -467,14 +1482,16 @@ fn copies_container( ctx: &LowerContext, source: &str, init: Node, - class: &str, + instance: &str, ) -> bool { single_argument(init).is_some_and(|value| { receiver_desc(program, ctx, source, value) .as_ref() - .and_then(class_name_of_desc) - .as_deref() - == Some(class) + .and_then(class_spelling_of_desc) + .is_some_and(|name| { + canonical_specialization(program, ctx, name) + == canonical_specialization(program, ctx, instance) + }) }) } @@ -630,23 +1647,47 @@ pub(super) fn specialization( .named_children(&mut arguments.walk()) .filter(|n| n.cached_kind() != "comment") .nth(model.element)?; - if arg.cached_kind() != "type_descriptor" - || spelling_is_dependent(ctx, source, arg, node_text(source, &arg), Spelling::Source) + // With an explicit allocator the grammar may spell a simple element type + // as a bare identifier; accept a known type/alias there as well. + let type_node = if arg.cached_kind() == "type_descriptor" + || is_name(arg) + || matches!(arg.cached_kind(), "type_identifier" | "template_type") { + arg + } else { + return None; + }; + if spelling_is_dependent( + ctx, + source, + type_node, + node_text(source, &type_node), + Spelling::Source, + ) { return None; } - let decl = arg.cached_field("declarator"); + let decl = type_node.cached_field("declarator"); if decl.is_some_and(declares_reference) { return None; } - let base = type_desc_from_node(program, ctx, source, arg); + let base = type_desc_from_node(program, ctx, source, type_node); let element = abstract_declarator_shape(base, decl, true, ReferenceLayer::Pointer); + let type_text = type_node.cached_field("type").unwrap_or(type_node); let callable = matches!(element, TypeDesc::FnPtr { .. }) - && is_callable_wrapper(&normalize_qualified(node_text( - source, - &arg.cached_field("type")?, - ))); - if !callable && !matches!(element, TypeDesc::Ptr(_)) { + && is_callable_wrapper(&normalize_qualified(node_text(source, &type_text))); + // A container element may itself be a modeled container, so its stored + // callbacks stay addressable through the nested element cell. + let nested = modeled_container_desc(ctx, &element) + && matches!( + &element, + TypeDesc::Struct { name, .. } + if program.types.template_element(name).is_some() + || program + .types + .template_element(&canonical_specialization(program, ctx, name)) + .is_some() + ); + if !callable && !matches!(element, TypeDesc::Ptr(_)) && !nested { return None; } let class = if class == model.name && !model.declaration_aliases().is_empty() { @@ -661,7 +1702,7 @@ pub(super) fn specialization( } else { class }; - let cv = spelled_type_cv(program, ctx, node_text(source, &arg)); + let cv = spelled_type_cv(program, ctx, node_text(source, &type_node)); let mut args = template_argument_spellings(program, ctx, source, arguments, 0); complete_template_arguments(program, ctx, class, &mut args); let name = format!("{class}<{}>", args.join(",")); @@ -708,7 +1749,7 @@ pub(super) fn allocator_specialization( { return None; } - type_spelling_for(program, ctx, source, node, node, 0) + type_spelling_for(program, ctx, source, node, node, 0, true) } pub(super) fn is_std_pair(name: &str) -> bool { @@ -756,7 +1797,7 @@ pub(super) fn pair_specialization( )) }; let second = field_type(program, second)?; - if !second.is_pointer_like() { + if !second.is_pointer_like() && !modeled_container_desc(ctx, &second) { return None; } let first = field_type(program, first)?; @@ -826,6 +1867,33 @@ pub(super) fn lower_pair_initializer( .into_iter() .zip([*first_value, *second_value]) { + let desc = program.types.get(ty).desc.as_ref().clone(); + if modeled_container_desc(ctx, &desc) { + if let Some(elements) = Elements::for_field(program, ctx, pair, name, &desc) { + let handled = lower_operation(program, ctx, source, clause, |program, ctx| { + if node_is_from_ignored_macro(ctx, clause) { + return true; + } + if store_nested_braced(program, ctx, source, elements.clone(), clause) { + return true; + } + if let Some(braced) = + typed_inner_braces(program, ctx, source, clause, &elements) + { + if store_nested_braced(program, ctx, source, elements.clone(), braced) { + return true; + } + } + false + }); + if handled { + continue; + } + } + // The mapped slot is a modeled container; an unrecognized clause + // must not be stored into its field cell as a scalar element. + continue; + } let Some(value) = unwrap_braced_value(clause) else { continue; }; @@ -858,7 +1926,7 @@ fn pair_source(program: &Program, ctx: &LowerContext, source: &str, node: Node) pub(super) fn lower_pair_assignment( program: &mut Program, - ctx: &LowerContext, + ctx: &mut LowerContext, source: &str, node: Node, dst: VarId, @@ -876,11 +1944,12 @@ pub(super) fn lower_pair_assignment( } } -/// Different pair specializations have separate field summaries. Copy only -/// the corresponding pointer/callable slots through the usual field cells. +/// Different pair specializations have separate field summaries. Copy the +/// corresponding pointer/callable slots and modeled container elements +/// through the usual field cells. pub(super) fn copy_pair_fields( program: &mut Program, - ctx: &LowerContext, + ctx: &mut LowerContext, node: Node, dst: VarId, src: VarId, @@ -892,14 +1961,24 @@ pub(super) fn copy_pair_fields( return false; } let mut bases = None; + let mut copied = false; for name in ["first", "second"] { let Some(((dst_field, dst_ty), (src_field, src_ty))) = field_in_pair(program, dst_pair, name).zip(field_in_pair(program, src_pair, name)) else { continue; }; - let dst_desc = program.types.get(dst_ty).desc.as_ref(); - let src_desc = program.types.get(src_ty).desc.as_ref(); + let dst_desc = program.types.get(dst_ty).desc.as_ref().clone(); + let src_desc = program.types.get(src_ty).desc.as_ref().clone(); + if modeled_container_desc(ctx, &dst_desc) && modeled_container_desc(ctx, &src_desc) { + let from = Elements::for_field(program, ctx, src_pair, name, &src_desc); + let to = Elements::for_field(program, ctx, dst_pair, name, &dst_desc); + if let (Some(from), Some(to)) = (from, to) { + copy_container_elements(program, ctx, node, from, to); + copied = true; + } + continue; + } if !(dst_desc.is_pointer_like() && src_desc.is_pointer_like()) { continue; } @@ -913,8 +1992,9 @@ pub(super) fn copy_pair_fields( let value = emit_load(program, ctx, node, src, src_ty); let dst = alloc_gep_temp(program, ctx, node, dst_base, dst_field, name.into()); program.flow.push(FlowConstraint::Store { dst, src: value }); + copied = true; } - bases.is_some() + copied } pub(super) fn record_template_defaults( @@ -976,7 +2056,7 @@ fn template_type_default( ) .then_some(node) })?; - return type_spelling_for(program, ctx, source, node, ty, depth) + return type_spelling_for(program, ctx, source, node, ty, depth, true) .map(ContainerTemplateDefault::Type); } // Bind simple dependent type arguments, such as `allocator`. A @@ -999,27 +2079,58 @@ fn template_type_default( }) } +/// Defaults for a modeled class template under its written, normalized, or +/// indexed (inline-namespace) owner name. A forward declaration without +/// defaults must not hide the canonical prelude's full definition. +fn class_template_defaults<'a>( + program: &'a Program, + ctx: &'a LowerContext, + class: &str, +) -> Option<&'a ContainerTemplateDefaults> { + let canonical = canonical_std_class(class); + let owner = ctx.container_models.get(&canonical).and_then(|model| { + indexed_owner(program, model).or_else(|| { + canonical_declarations(ctx)? + .owners + .get(&model.name) + .map(String::as_str) + }) + }); + let mut keys: Vec<&str> = vec![class]; + if canonical != class { + keys.push(canonical.as_str()); + } + if let Some(owner) = owner { + if !keys.contains(&owner) { + keys.push(owner); + } + } + for key in keys { + if let Some(defaults) = program.types.container_template_defaults(key) { + return Some(defaults); + } + if !program.types.is_struct_defined(key) { + if let Some(defaults) = canonical_declarations(ctx).and_then(|d| d.defaults.get(key)) { + return Some(defaults); + } + } + } + None +} + fn complete_template_arguments( program: &Program, ctx: &LowerContext, class: &str, args: &mut Vec, ) { - let defaults = program - .types - .container_template_defaults(class) - .or_else(|| { - if program.types.is_struct_declared(class) { - return None; - } - canonical_declarations(ctx)?.defaults.get(class) - }); + let defaults = class_template_defaults(program, ctx, class); if let Some(defaults) = defaults { while let Some(arg) = defaults .get(&args.len()) .and_then(|default| default.bind(args)) { - args.push(arg); + args.push(bounded_template_argument(program, ctx, arg)); } } } @@ -1192,12 +2303,25 @@ fn template_argument_spellings( .named_children(&mut arguments.walk()) .filter(|n| n.cached_kind() != "comment") .map(|arg| { - type_spelling_at(program, ctx, source, arg, depth) - .unwrap_or_else(|| normalize_spacing(node_text(source, &arg))) + let spelling = type_spelling_at(program, ctx, source, arg, depth, true) + .unwrap_or_else(|| normalize_spacing(node_text(source, &arg))); + bounded_template_argument(program, ctx, spelling) }) .collect() } +/// Long arguments are shared by their canonical identity before an enclosing +/// specialization can duplicate them, including in written allocator slots. +/// The enclosing name stays parseable and the element descriptor still names +/// its separately registered specialization. +fn bounded_template_argument(program: &Program, ctx: &LowerContext, spelling: String) -> String { + if spelling.len() > COMPACT_IDENTITY_THRESHOLD { + canonical_specialization_at(program, ctx, &spelling, 0, false) + } else { + spelling + } +} + /// Keep the type's source qualifiers, signedness and declarator separate /// from the descriptor used for flow. Expand recorded aliases in their /// declaration scope before using the spelling as a specialization key. @@ -1207,27 +2331,163 @@ pub(super) fn type_spelling( source: &str, node: Node, ) -> Option { - type_spelling_at(program, ctx, source, node, 0) + type_spelling_at(program, ctx, source, node, 0, true) +} + +/// Spell the type named by a C-style `(T){...}` type descriptor or by a C++ +/// braced temporary's `T` node (`T{...}`), which is not a descriptor. +pub(super) fn type_spelling_node( + program: &Program, + ctx: &LowerContext, + source: &str, + node: Node, +) -> Option { + if node.cached_kind() == "type_descriptor" { + type_spelling(program, ctx, source, node) + } else { + type_spelling_for(program, ctx, source, node, node, 0, true) + } +} + +/// The alias's own spelling with default template arguments left implicit. +/// Expanding them into an alias that names another specialization would +/// duplicate the previous spelling in both the element and allocator slots +/// and grow exponentially down an alias chain. +pub(super) fn type_spelling_implicit_defaults( + program: &Program, + ctx: &LowerContext, + source: &str, + node: Node, +) -> Option { + type_spelling_at(program, ctx, source, node, 0, false) +} + +fn type_spelling_at( + program: &Program, + ctx: &LowerContext, + source: &str, + node: Node, + depth: u32, + fill_defaults: bool, +) -> Option { + if node.has_error() || depth >= MAX_AST_WALK_DEPTH { + return None; + } + type_spelling_for( + program, + ctx, + source, + node, + node.cached_field("type")?, + depth, + fill_defaults, + ) +} + +/// Split at the last `target` outside template arguments, parenthesized +/// declarators, and array bounds. +fn split_top_level(spelling: &str, target: char) -> Option<(&str, &str)> { + let mut angle = 0usize; + let mut paren = 0usize; + let mut bracket = 0usize; + let mut split = None; + for (index, ch) in spelling.char_indices() { + if ch == target && angle == 0 && paren == 0 && bracket == 0 { + split = Some(index); + } + match ch { + '[' => bracket += 1, + ']' => bracket = bracket.saturating_sub(1), + _ if bracket != 0 => continue, + '<' => angle += 1, + '>' => angle = angle.saturating_sub(1), + '(' => paren += 1, + ')' => paren = paren.saturating_sub(1), + _ => {} + } + } + split.map(|index| (&spelling[..index], &spelling[index + target.len_utf8()..])) +} + +/// Split at the outer pointer's `*` inside a function-pointer declarator. +/// In `void (*const *)(int *)` this is the last `*` in the declarator group. +fn split_function_pointer_star(spelling: &str) -> Option<(&str, &str)> { + let mut angle = 0usize; + let mut paren = 0usize; + let mut bracket = 0usize; + let mut group_start = 0; + let mut star = None; + for (index, ch) in spelling.char_indices() { + match ch { + '[' => bracket += 1, + ']' => bracket = bracket.saturating_sub(1), + _ if bracket != 0 => continue, + '<' => angle += 1, + '>' => angle = angle.saturating_sub(1), + '(' if angle == 0 => { + if paren == 0 { + group_start = index + 1; + } + paren += 1; + } + ')' if angle == 0 => { + paren = paren.saturating_sub(1); + if paren == 0 && star.is_some() { + break; + } + } + '*' if angle == 0 && paren == 1 => { + let prefix = spelling[group_start..index].trim(); + if star.is_some() || prefix.is_empty() || prefix.ends_with("::") { + star = Some(index); + } + } + _ => {} + } + } + star.map(|index| (&spelling[..index], &spelling[index + 1..])) +} + +fn split_outer_pointer_star(spelling: &str) -> Option<(&str, &str)> { + // A top-level star before the declarator belongs to the return type. + split_top_level(spelling, '*') + .into_iter() + .chain(split_function_pointer_star(spelling)) + .max_by_key(|(before, _)| before.len()) } -fn type_spelling_at( - program: &Program, - ctx: &LowerContext, - source: &str, - node: Node, - depth: u32, -) -> Option { - if node.has_error() || depth >= MAX_AST_WALK_DEPTH { - return None; +/// Function parameter types discard object cv, retaining qualifications on +/// referred-to objects, pointees and array elements. +fn parameter_type_spelling(spelling: String) -> String { + if split_top_level(&spelling, '&').is_some() || split_top_level(&spelling, '[').is_some() { + return spelling; } - type_spelling_for( - program, - ctx, - source, - node, - node.cached_field("type")?, - depth, - ) + if let Some((before, tail)) = split_outer_pointer_star(&spelling) { + if let Some((qualifiers, after)) = tail.split_once(')') { + if !qualifiers.contains('&') { + let declarator = &spelling[before.len()..before.len() + 1 + qualifiers.len()]; + return format!("{before}{}){after}", strip_trailing_cv(declarator)); + } + return spelling; + } + return strip_trailing_cv(&spelling).to_owned(); + } + strip_trailing_cv(without_leading_cv(&spelling)).to_owned() +} + +pub(super) fn has_top_level(spelling: &str, target: char) -> bool { + let mut depth = 0usize; + for ch in spelling.chars() { + match ch { + '<' => depth += 1, + '>' => depth = depth.saturating_sub(1), + _ => {} + } + if ch == target && depth == 0 { + return true; + } + } + false } fn type_spelling_for( @@ -1237,6 +2497,7 @@ fn type_spelling_for( node: Node, ty: Node, depth: u32, + fill_defaults: bool, ) -> Option { let before = source[node.start_byte()..ty.start_byte()].trim(); let before = before.strip_prefix("typedef").unwrap_or(before).trim(); @@ -1255,8 +2516,13 @@ fn type_spelling_for( let raw = node_text(source, &named).trim(); let alias = if !raw.contains('<') { let name = normalize_qualified(raw); + let adds_cv = qualifiers.constant || qualifiers.volatile; let resolved = if let Some(alias) = local_alias_info(ctx, &name) { - Some((alias.type_spelling.as_deref(), alias.qualification)) + Some(( + alias.type_spelling.as_deref(), + alias.qualification, + adds_cv && alias.reference.is_some(), + )) } else { find_alias_in_scope(program, ctx, &name, |candidate, _| { program.types.resolve_alias(candidate)?; @@ -1269,10 +2535,15 @@ fn type_spelling_for( .types .alias_qualification(candidate) .unwrap_or_default(), + adds_cv && program.types.alias_is_reference(candidate), )) }) }; - resolved.and_then(|(spelling, cv)| { + resolved.and_then(|(spelling, cv, ignore_cv)| { + // A reference alias keeps the referent's existing qualification. + if ignore_cv { + qualifiers = TypeQualifiers::default(); + } if spelling.is_none() { // Class aliases can carry cv without having a stored type spelling. qualifiers.constant |= cv.object_const; @@ -1283,20 +2554,22 @@ fn type_spelling_for( None }; let head = if let Some(alias) = alias { - if let Some((pointee, tail)) = alias.rsplit_once('*') { + if let Some((pointee, tail)) = split_outer_pointer_star(alias) { // A qualifier on a pointer alias decorates the outer pointer. let mut pointer = qualifiers; - if pointer.take_prefix(tail).is_empty() { + let remainder = pointer.take_prefix(tail); + if remainder.is_empty() { qualifiers = TypeQualifiers::default(); format!("{pointee}*{}", pointer.spelling()) - } else if alias.contains('(') - && (!after.is_empty() || !qualifiers.spelling().is_empty()) - { + } else if has_top_level(alias, '(') && !qualifiers.spelling().is_empty() { + qualifiers = TypeQualifiers::default(); + format!("{pointee}*{} {remainder}", pointer.spelling()) + } else if has_top_level(alias, '(') && !after.is_empty() { format!("({alias})") } else { alias.to_owned() } - } else if alias.contains('(') && !after.is_empty() { + } else if has_top_level(alias, '(') && !after.is_empty() { format!("({alias})") } else { alias.to_owned() @@ -1311,7 +2584,7 @@ fn type_spelling_for( { let mut args_spelling = template_argument_spellings(program, ctx, source, args, depth + 1); - if ctx.container_models.get(&class).is_some() { + if fill_defaults && ctx.container_models.get(&class).is_some() { complete_template_arguments(program, ctx, &class, &mut args_spelling); } format!( @@ -1372,8 +2645,10 @@ fn declarator_spelling( edits.push((part.byte_range(), String::new())); } else if let Some(params) = part.cached_field("parameters") { for param in params.named_children(&mut params.walk()) { - if let Some(spelling) = type_spelling_at(program, ctx, source, param, depth + 1) { - edits.push((param.byte_range(), spelling)); + if let Some(spelling) = + type_spelling_at(program, ctx, source, param, depth + 1, true) + { + edits.push((param.byte_range(), parameter_type_spelling(spelling))); } } } @@ -1472,6 +2747,7 @@ fn builtin_type_spelling(raw: &str, qualifiers: &mut TypeQualifiers) -> Option { Expression(Node<'t>), - PairSecond(Node<'t>, VarId, FieldId, TypeId), + /// A named pair's `second` member: node, pair variable, pair type, + /// member field, and member type. + PairSecond(Node<'t>, VarId, TypeId, FieldId, TypeId), } /// A modeled container field of an object selected from an array or pointer. @@ -1508,15 +2786,25 @@ pub(super) fn subscript_field( impl Elements { fn for_var(program: &Program, ctx: &LowerContext, var: VarId) -> Option { + let ty = program.symbols.variable(var).type_id; + let mut desc = program.types.get(ty).desc.as_ref(); + // A reference alias lowers to a pointer type. Its address is still the + // referenced container's cell, so unwrap that layer before recording + // or resolving a nested range owner. + if ctx.reference_vars.contains(&var) { + if let TypeDesc::Ptr(inner) = desc { + desc = inner.as_ref(); + } + } + // A recorded nested range binding names the referenced container's + // element cell even when the loop variable is an explicit reference. + if let Some(owner) = ctx.nested_container_owners.get(&var) { + return Self::new(program, ctx, owner.clone(), desc); + } if ctx.reference_vars.contains(&var) { return None; } - let ty = program.symbols.variable(var).type_id; - Self::new( - program, - ContainerOwner::Variable(var), - program.types.get(ty).desc.as_ref(), - ) + Self::new(program, ctx, ContainerOwner::Variable(var), desc) } fn for_receiver( @@ -1541,12 +2829,41 @@ impl Elements { return Self::for_var(program, ctx, lookup_var_node(program, ctx, source, recv)?); } "field_expression" => { + let field_node = recv.cached_field("field")?; + if node_is_from_ignored_macro(ctx, recv) + || node_is_from_ignored_macro(ctx, field_node) + { + return None; + } if let Some(var) = static_member_access(program, ctx, source, recv) { return Self::for_var(program, ctx, var); } let base = recv.cached_field("argument")?; - let name = node_text(source, &recv.cached_field("field")?); + // The field token is checked above, but an ignored bracket or + // accessor in the base chain must stop the read too + // (`holders IDX->slots`, `holders.AT_METHOD(0)->slots`). + if receiver_chain_ignored(ctx, source, base) { + return None; + } + let name = node_text(source, &field_node); let arrow = is_arrow_access(recv); + // A named standard pair's specialized layout carries the + // mapped member type; resolve its container member directly + // instead of the primary template's dependent field. + if !arrow { + if let Some(var) = lookup_var_node(program, ctx, source, base) { + if let Some(pair) = pair_type(program, var) { + if let Some((_, ty)) = field_in_pair(program, pair, name) { + let desc = program.types.get(ty).desc.as_ref().clone(); + if let Some(elements) = + Self::for_field(program, ctx, pair, name, &desc) + { + return Some(elements); + } + } + } + } + } let field = (!arrow) .then(|| subscript_field(program, ctx, source, base, name)) .flatten() @@ -1556,24 +2873,101 @@ impl Elements { })?; (field, name) } + "call_expression" => { + // An ignored accessor must not resolve through its return temp + // either. + if node_is_from_ignored_macro(ctx, recv) + || method_is_from_ignored_macro(ctx, source, recv) + { + return None; + } + if is_std_move(source, recv) { + return Self::for_receiver( + program, + ctx, + source, + *call_arg_nodes(recv).first()?, + ); + } + // A modeled accessor (`at`, `front`, `back`) returns an element + // of its receiver, so descend into that receiver's nested cell. + // Keep the descent in an unevaluated chain so the site emitter + // records every bracket; the method token has its own macro + // provenance. + if let Some(inner) = ctx + .container_access_owners + .borrow() + .get(&recv.id()) + .cloned() + { + return Some(inner); + } + if let Some(Access::Direct(elements)) = access(program, ctx, source, recv) { + return elements.remember_nested_receiver(program, ctx, recv); + } + // Otherwise a call result materializes a return temp; when its + // type is a modeled container, its cell is the only safe + // storage. The callee's element summary remains a follow-up. + let temp = ctx.call_return_dst.borrow().get(&recv.id()).copied()?; + return Self::for_var(program, ctx, temp); + } + "subscript_expression" => { + // Each bracket in a chain carries its own macro provenance; + // an ignored bracket must stop the read even when the outer + // expression is written outside the macro. Evaluation is + // checked when flow is emitted, so unevaluated chains still + // record every site. + if node_is_from_ignored_macro(ctx, recv) || subscript_bracket_ignored(ctx, recv) { + return None; + } + if let Some(inner) = ctx + .container_access_owners + .borrow() + .get(&recv.id()) + .cloned() + { + return Some(inner); + } + let container = match access(program, ctx, source, recv)? { + Access::Direct(elements) => elements, + Access::Iterator { .. } => return None, + }; + return container.remember_nested_receiver(program, ctx, recv); + } _ => return None, }; Self::for_field( program, + ctx, field.owner_type_id, name, program.types.get(field.type_id).desc.as_ref(), ) } + fn remember_nested_receiver( + &self, + program: &Program, + ctx: &LowerContext, + node: Node, + ) -> Option { + let inner = self.nested(program, ctx)?; + ctx.container_access_owners + .borrow_mut() + .insert(node.id(), inner.clone()); + Some(inner) + } + fn for_field( program: &Program, + ctx: &LowerContext, class: trace_ir::TypeId, name: &str, desc: &TypeDesc, ) -> Option { Self::new( program, + ctx, ContainerOwner::Field { class, name: name.into(), @@ -1582,118 +2976,516 @@ impl Elements { ) } - fn new(program: &Program, owner: ContainerOwner, desc: &TypeDesc) -> Option { + fn new( + program: &Program, + ctx: &LowerContext, + owner: ContainerOwner, + desc: &TypeDesc, + ) -> Option { let TypeDesc::Struct { name, .. } = desc else { return None; }; - let element = program.types.template_element(name)?.clone(); - name.split_once('<')?; + // A specialization spelled through an alias may be registered under + // its expanded identity; use that key so the same C++ type shares its + // element cell across spellings. Check the exact key first: rebuilding + // the canonical spelling is expensive for deeply nested types. + let canonical; + let instance = if program.types.template_element(name).is_some() { + name.as_str() + } else { + canonical = canonical_specialization(program, ctx, name); + if program.types.template_element(&canonical).is_some() { + canonical.as_str() + } else { + return None; + } + }; + let element = program.types.template_element(instance)?.clone(); + instance.split_once('<')?; Some(Self { owner, - instance: name.clone(), + instance: instance.to_owned(), element, }) } - fn class(&self) -> &str { - self.instance - .split_once('<') - .expect("container specialization") - .0 + fn class(&self) -> &str { + self.instance + .split_once('<') + .expect("container specialization") + .0 + } + + /// Only standard map layouts identify template argument zero as the key. + fn map_key(&self) -> Option<&str> { + if !matches!( + canonical_std_class(self.class()).as_str(), + "std::map" | "std::unordered_map" | "std::multimap" | "std::unordered_multimap" + ) { + return None; + } + trace_ir::split_instance(&self.instance)?.1.first().copied() + } + + pub(super) fn owner(&self) -> &ContainerOwner { + &self.owner + } + + /// The elements carried by containers stored in this container's element + /// cell. Only a modeled element type nests; a plain callable or pointer + /// element keeps the ordinary element cell. + pub(super) fn nested(&self, program: &Program, ctx: &LowerContext) -> Option { + let TypeDesc::Struct { name, .. } = &self.element else { + return None; + }; + // The nested cell key uses the canonical specialization identity, so + // two TUs that spell an equivalent inner type differently (for + // example an explicit default allocator) share one cell after merge. + let canonical = canonical_specialization(program, ctx, name); + let owner = ContainerOwner::Nested { + parent: Arc::new(self.owner.clone()), + instance: Arc::from(canonical.as_str()), + }; + let mut inner = Self::new(program, ctx, owner.clone(), &self.element)?; + inner.owner = owner; + ctx.container_models.get(inner.class())?; + Some(inner) + } + + /// The stored element descriptor. Placeholder deduction uses it so an + /// `auto` loop variable gets the element type the container model + /// resolved, including a function-pointer alias the spelling walk cannot + /// classify. + pub(super) fn element(&self) -> &TypeDesc { + &self.element + } + + /// Qualification recorded beside the element descriptor (const object or + /// pointee). A range-for variable carries it so overload resolution sees + /// `for (auto h : std::vector)` as a `T const*`. + pub(super) fn cv(&self, program: &Program) -> trace_ir::CvQualification { + program + .types + .template_element_cv(&self.instance) + .unwrap_or_default() + } + + fn address(&self, program: &mut Program, dst: VarId) -> trace_ir::TypeId { + let element = program.types.intern(self.element.clone()); + program.flow.push(FlowConstraint::ContainerElement { + dst, + owner: self.owner.clone(), + element, + }); + element + } + + fn store_values<'t>( + self, + program: &mut Program, + ctx: &mut LowerContext, + source: &str, + at: Node, + values: impl IntoIterator>, + ) { + let nested = self.nested(program, ctx); + let mut cell = None; + for stored in values { + let value = match stored { + StoredValue::Expression(value) | StoredValue::PairSecond(value, ..) => value, + }; + if node_is_from_ignored_macro(ctx, value) { + continue; + } + if let Some(inner) = &nested { + if let Some(braced) = typed_inner_braces(program, ctx, source, value, inner) { + store_nested_braced(program, ctx, source, inner.clone(), braced); + continue; + } + if let StoredValue::PairSecond(_, _, pair, _, member_ty) = &stored { + let desc = program.types.get(*member_ty).desc.as_ref().clone(); + if let Some(from) = Elements::for_field(program, ctx, *pair, "second", &desc) + .filter(|from| ctx.container_models.get(from.class()).is_some()) + { + lower_operation(program, ctx, source, value, |program, ctx| { + copy_container_elements(program, ctx, value, from, inner.clone()); + }); + continue; + } + } + if matches!(value.cached_kind(), "initializer_list" | "argument_list") { + store_nested_braced(program, ctx, source, inner.clone(), value); + continue; + } + + if let Some(from) = Elements::for_receiver(program, ctx, source, value) + .filter(|from| ctx.container_models.get(from.class()).is_some()) + { + lower_operation(program, ctx, source, value, |program, ctx| { + copy_container_elements(program, ctx, value, from, inner.clone()); + }); + continue; + } + } + // A nested element cell holds only inner containers or validated + // inner elements. An unrecognized outer value must not be written + // into it as if it were an inner element. + if nested.is_some() { + continue; + } + // The nested walker preserves braces while descending; unwrap the + // innermost scalar braces the way the outer list path does. + let value = if nested.is_none() + && matches!(value.cached_kind(), "initializer_list" | "argument_list") + { + match unwrap_braced_value(value) { + Some(value) => value, + None => continue, + } + } else { + value + }; + let (address, element) = *cell.get_or_insert_with(|| { + let ty = program.types.ptr_to(self.element.clone()); + let address = alloc_load_temp(program, ctx, at, ty); + let element = self.address(program, address); + (address, element) + }); + lower_operation(program, ctx, source, value, |program, ctx| { + if let StoredValue::PairSecond(_, var, _, field, ty) = stored { + let base = addr_of_temp(program, ctx, value, var); + let cell = alloc_gep_temp(program, ctx, value, base, field, "second".into()); + let src = emit_load(program, ctx, value, cell, ty); + program + .flow + .push(FlowConstraint::Store { dst: address, src }); + return; + } + let value = peel_value_casts(program, ctx, source, value); + let cached = ctx.call_return_dst.borrow().get(&value.id()).copied(); + if let Some(src) = cached { + program + .flow + .push(FlowConstraint::Store { dst: address, src }); + } else if value.cached_kind() == "field_expression" + || implicit_this(program, ctx, source, value).is_some() + { + if let Some(src) = operand_value(program, ctx, source, value) { + program + .flow + .push(FlowConstraint::Store { dst: address, src }); + } + } else { + emit_store_to_location(program, ctx, source, at, address, value, Some(element)); + } + }); + } + } +} + +/// Store a braced value for an inner container: a constructor list when the +/// element type accepts one, otherwise a copy of a named inner container. +fn store_nested_braced( + program: &mut Program, + ctx: &mut LowerContext, + source: &str, + elements: Elements, + node: Node, +) -> bool { + // A single braced named container is a copy even when the inner list + // could also accept it as one element; test the canonical type first. + if let Some(candidate) = unwrap_braced_value(node) { + if node_is_from_ignored_macro(ctx, candidate) { + return true; + } + if let Some(from) = Elements::for_receiver(program, ctx, source, candidate).filter(|from| { + let a = canonical_specialization(program, ctx, &from.instance); + let b = canonical_specialization(program, ctx, &elements.instance); + + ctx.container_models.get(from.class()).is_some() && a == b + }) { + lower_operation(program, ctx, source, node, |program, ctx| { + copy_container_elements(program, ctx, node, from, elements); + }); + return true; + } + } + // `{source, allocator}` invokes the allocator-extended copy constructor. + // Recognize the matching source container before reading the brace as an + // initializer list of inner elements. + if let Some(copy_source) = allocator_extended_copy(program, ctx, source, &elements, node) { + match copy_source { + AllocatorCopySource::Cell(from) => { + lower_operation(program, ctx, source, node, |program, ctx| { + copy_container_elements(program, ctx, node, from, elements); + }); + } + AllocatorCopySource::Temporary(candidate) => { + if let Some(braced) = typed_inner_braces(program, ctx, source, candidate, &elements) + { + store_nested_braced(program, ctx, source, elements.clone(), braced); + } + } + } + return true; + } + // A typed temporary of the matching inner specialization (`{T{...}}`) + // is a copy source; store its initializer into the destination cell. + if let Some(braced) = unwrap_braced_value(node) + .and_then(|candidate| typed_inner_braces(program, ctx, source, candidate, &elements)) + { + if store_nested_braced(program, ctx, source, elements.clone(), braced) { + return true; + } + } + lower_list_initializer(program, ctx, source, elements, node) +} + +/// Whether a clause names an allocator that can extend the container's copy +/// constructor. An empty clause value-initializes the allocator. +fn allocator_clause_compatible( + program: &Program, + ctx: &LowerContext, + source: &str, + elements: &Elements, + model: &ContainerModel, + allocator: Node, +) -> bool { + let allocator = peel_expression(allocator); + if braced_clause_count(allocator) == Some(0) { + return true; + } + if allocator.cached_kind() == "argument_list" + && arguments(allocator).is_none_or(|args| args.is_empty()) + { + return true; + } + if allocator_argument(program, ctx, source, elements, model, allocator) { + return true; + } + let Some(expected) = copy_allocator_spelling(elements, model) else { + return false; + }; + let actual = match allocator.cached_kind() { + "compound_literal_expression" => allocator + .cached_field("type") + .and_then(|ty| type_spelling_node(program, ctx, source, ty)), + _ => { + let ty = known_arg_type(program, ctx, source, allocator); + class_spelling_of_desc(&ty).map(str::to_owned) + } + }; + actual.is_some_and(|actual| { + canonical_specialization(program, ctx, &actual) + == canonical_specialization(program, ctx, &expected) + }) +} + +/// The copy constructor uses the allocator bound by the specialization. +/// Standard containers can have this parameter without modeling an +/// initializer-list overload with an allocator. +fn copy_allocator_spelling<'a>( + elements: &'a Elements, + model: &ContainerModel, +) -> Option> { + let (_, args) = trace_ir::split_instance(&elements.instance)?; + let class = canonical_std_class(elements.class()); + let standard_position = match class.as_str() { + "std::vector" | "std::deque" | "std::list" | "std::forward_list" => Some(1), + "std::set" | "std::multiset" => Some(2), + "std::unordered_set" | "std::unordered_multiset" | "std::map" | "std::multimap" => Some(3), + "std::unordered_map" | "std::unordered_multimap" => Some(4), + _ => None, + }; + let position = model.initializer_allocator.or(standard_position)?; + if let Some(bound) = args.get(position) { + return Some(Cow::Borrowed(bound)); + } + // Template defaults with a dependent const key may be missing from the + // declaration index. The standard allocator still has its specified type. + standard_position?; + let value = if let Some(key) = elements.map_key() { + format!("std::pair<{},{}>", const_value_spelling(key), args.get(1)?) + } else { + args.first()?.to_string() + }; + Some(Cow::Owned(format!("std::allocator<{value}>"))) +} + +fn const_value_spelling(spelling: &str) -> String { + let mut qualifiers = TypeQualifiers { + constant: true, + ..TypeQualifiers::default() + }; + if let Some((pointee, tail)) = split_outer_pointer_star(spelling) { + let remainder = qualifiers.take_prefix(tail); + return format!("{pointee}*{} {remainder}", qualifiers.spelling()); + } + let value = qualifiers.take_prefix(spelling); + format!("{} {value}", qualifiers.spelling()) +} + +enum AllocatorCopySource<'t> { + /// A named container whose element cell can be copied. + Cell(Elements), + /// A typed temporary or type-only match with no element cell; a typed + /// temporary's initializer is lowered into the destination instead. + Temporary(Node<'t>), +} + +/// The source of an allocator-extended copy (`{source, allocator}`) when the +/// clause shape and allocator fit `elements`. +fn allocator_extended_copy<'t>( + program: &Program, + ctx: &LowerContext, + source: &str, + elements: &Elements, + node: Node<'t>, +) -> Option> { + if node.cached_kind() != "initializer_list" { + return None; + } + let mut cursor = node.walk(); + let clauses: Vec<_> = node + .named_children(&mut cursor) + .filter(|clause| clause.cached_kind() != "comment") + .collect(); + let [source_clause, allocator] = clauses.as_slice() else { + return None; + }; + let candidate = unwrap_braced_value(*source_clause)?; + if node_is_from_ignored_macro(ctx, candidate) { + return None; + } + let model = ctx.container_models.get(elements.class())?; + if !allocator_clause_compatible(program, ctx, source, elements, model, *allocator) { + return None; + } + if let Some(from) = Elements::for_receiver(program, ctx, source, candidate).filter(|from| { + let a = canonical_specialization(program, ctx, &from.instance); + let b = canonical_specialization(program, ctx, &elements.instance); + ctx.container_models.get(from.class()).is_some() && a == b + }) { + return Some(AllocatorCopySource::Cell(from)); + } + let typed = typed_inner_braces(program, ctx, source, candidate, elements).is_some() + || receiver_desc(program, ctx, source, candidate) + .as_ref() + .and_then(class_spelling_of_desc) + .is_some_and(|name| { + canonical_specialization(program, ctx, name) + == canonical_specialization(program, ctx, &elements.instance) + }); + typed.then_some(AllocatorCopySource::Temporary(candidate)) +} + +/// The braced payload of a `std::initializer_list{...}` temporary when +/// `T` matches the expected inner element. Such a temporary initializes the +/// inner container's element list even though its type is not the container. +fn initializer_list_compound_brace<'t>( + program: &Program, + ctx: &LowerContext, + source: &str, + node: Node<'t>, + expected: &TypeDesc, +) -> Option> { + let node = peel_expression(node); + if node.cached_kind() != "compound_literal_expression" { + return None; } - - /// The stored element descriptor. Placeholder deduction uses it so an - /// `auto` loop variable gets the element type the container model - /// resolved, including a function-pointer alias the spelling walk cannot - /// classify. - pub(super) fn element(&self) -> &TypeDesc { - &self.element + let ty = node.cached_field("type")?; + let spelling = type_spelling_node(program, ctx, source, ty)?; + let (class, args) = trace_ir::split_instance(&spelling)?; + if canonical_std_class(without_leading_cv(class)) != "std::initializer_list" || args.len() != 1 + { + return None; } - - /// Qualification recorded beside the element descriptor (const object or - /// pointee). A range-for variable carries it so overload resolution sees - /// `for (auto h : std::vector)` as a `T const*`. - pub(super) fn cv(&self, program: &Program) -> trace_ir::CvQualification { - program - .types - .template_element_cv(&self.instance) - .unwrap_or_default() + if canonical_specialization_at(program, ctx, args[0], 0, false) + != canonical_desc_at(program, ctx, expected, 0, false) + { + return None; } + node.cached_field("value") + .filter(|value| value.cached_kind() == "initializer_list") +} - fn address(self, program: &mut Program, dst: VarId) -> trace_ir::TypeId { - let element = program.types.intern(self.element); - program.flow.push(FlowConstraint::ContainerElement { - dst, - owner: self.owner, - element, - }); - element +/// A typed braced temporary (`std::vector{...}`) that names the expected +/// inner container. Outer initializers and mapped slots reach `store_values` +/// without the insertion path's earlier unwrapping. +fn typed_inner_braces<'a>( + program: &Program, + ctx: &LowerContext, + source: &'a str, + value: Node<'a>, + inner: &Elements, +) -> Option> { + let value = peel_expression(value); + if value.cached_kind() != "compound_literal_expression" { + return None; } - - fn store<'t>( - self, - program: &mut Program, - ctx: &mut LowerContext, - source: &str, - at: Node, - values: impl IntoIterator>, - ) { - self.store_values( - program, - ctx, - source, - at, - values.into_iter().map(StoredValue::Expression), - ); + let ty = value.cached_field("type")?; + if node_is_from_ignored_macro(ctx, ty) { + return None; } + let spelling = type_spelling_node(program, ctx, source, ty)?; + if canonical_specialization(program, ctx, &spelling) + == canonical_specialization(program, ctx, &inner.instance) + { + return value + .cached_field("value") + .filter(|value| value.cached_kind() == "initializer_list"); + } + let brace = initializer_list_compound_brace(program, ctx, source, value, inner.element())?; + let model = ctx.container_models.get(inner.class())?; + model.initializer_list.then_some(brace) +} - fn store_values<'t>( - self, - program: &mut Program, - ctx: &mut LowerContext, - source: &str, - at: Node, - values: impl IntoIterator>, - ) { - let ty = program.types.ptr_to(self.element.clone()); - let address = alloc_load_temp(program, ctx, at, ty); - let element = self.address(program, address); - for stored in values { - let value = match stored { - StoredValue::Expression(value) | StoredValue::PairSecond(value, ..) => value, - }; - if node_is_from_ignored_macro(ctx, value) { - continue; - } - lower_operation(program, ctx, source, value, |program, ctx| { - if let StoredValue::PairSecond(_, var, field, ty) = stored { - let base = addr_of_temp(program, ctx, value, var); - let cell = alloc_gep_temp(program, ctx, value, base, field, "second".into()); - let src = emit_load(program, ctx, value, cell, ty); - program - .flow - .push(FlowConstraint::Store { dst: address, src }); - return; - } - let value = peel_value_casts(program, ctx, source, value); - let cached = ctx.call_return_dst.borrow().get(&value.id()).copied(); - if let Some(src) = cached { - program - .flow - .push(FlowConstraint::Store { dst: address, src }); - } else if value.cached_kind() == "field_expression" - || implicit_this(program, ctx, source, value).is_some() - { - if let Some(src) = operand_value(program, ctx, source, value) { - program - .flow - .push(FlowConstraint::Store { dst: address, src }); - } - } else { - emit_store_to_location(program, ctx, source, at, address, value, Some(element)); - } - }); - } +/// Seed a by-value range copy's own cells from the source container. The copy +/// must not alias the source: writing to the loop variable cannot change what +/// a later read of the outer container returns. +pub(super) fn copy_into_range_var( + program: &mut Program, + ctx: &mut LowerContext, + at: Node, + from: Elements, + var: VarId, +) { + let Some(to) = Elements::for_var(program, ctx, var) else { + return; + }; + copy_container_elements(program, ctx, at, from, to); +} + +/// A container value stored in another container: copy the inner element +/// cell's contents into the nested cell, then recurse through matching +/// descendant cells so a three-level container keeps its deepest callbacks. +/// Loads and stores are monotone, so a later insertion into the inner +/// container still reaches the nested read. +fn copy_container_elements( + program: &mut Program, + ctx: &mut LowerContext, + at: Node, + from: Elements, + to: Elements, +) { + let from_canonical = canonical_specialization(program, ctx, &from.instance); + let to_canonical = canonical_specialization(program, ctx, &to.instance); + if from_canonical != to_canonical { + return; + } + let from_pointer = program.types.ptr_to(from.element.clone()); + let from_address = alloc_load_temp(program, ctx, at, from_pointer); + let from_element = from.address(program, from_address); + let to_pointer = program.types.ptr_to(to.element.clone()); + let to_address = alloc_load_temp(program, ctx, at, to_pointer); + to.address(program, to_address); + let loaded = emit_load(program, ctx, at, from_address, from_element); + program.flow.push(FlowConstraint::Store { + dst: to_address, + src: loaded, + }); + if let (Some(from_deep), Some(to_deep)) = (from.nested(program, ctx), to.nested(program, ctx)) { + copy_container_elements(program, ctx, at, from_deep, to_deep); } } @@ -1816,6 +3608,30 @@ fn member_call<'a>(source: &'a str, node: Node<'a>) -> Option<(Node<'a>, Cow<'a, )) } +pub(super) fn method_is_from_ignored_macro(ctx: &LowerContext, source: &str, call: Node) -> bool { + if ctx.ignored_macros.is_empty() { + return false; + } + if let Some(op) = call + .has_error() + .then(|| explicit_member_operator_call(call, source)) + .flatten() + { + return node_is_from_ignored_macro(ctx, op.op_node) + || node_is_from_ignored_macro(ctx, op.punct_node); + } + call.cached_field("function") + .and_then(|func| func.cached_field("field")) + .is_some_and(|field| { + let field = if field.cached_kind() == "template_method" { + field.cached_field("name").unwrap_or(field) + } else { + field + }; + node_is_from_ignored_macro(ctx, field) + }) +} + fn arguments(args: Node) -> Option> { args.named_children(&mut args.walk()) .filter(|arg| arg.cached_kind() != "comment") @@ -2153,90 +3969,363 @@ fn evaluated(ctx: &LowerContext, source: &str, mut node: Node) -> bool { true } -fn subscript_occurrence<'t>(node: Node<'t>, ctx: &LowerContext) -> Option> { - if ctx.line_map.is_none() || node.cached_kind() != "subscript_expression" { +fn subscript_bracket<'t>(node: Node<'t>) -> Option> { + if node.cached_kind() != "subscript_expression" { return None; } let indices = node.cached_field("indices")?; let mut cursor = indices.walk(); let token = indices .children(&mut cursor) - .find(|token| token.cached_kind() == "[" && node_has_expansion_location(ctx, *token)); + .find(|token| token.cached_kind() == "["); token } +fn subscript_occurrence<'t>(node: Node<'t>, ctx: &LowerContext) -> Option> { + ctx.line_map.as_ref()?; + subscript_bracket(node).filter(|token| node_has_expansion_location(ctx, *token)) +} + +/// Whether a receiver chain reaches an earlier subscript through a field, +/// call or pointer wrapper. Such wrappers share the chain's expression start, +/// so an outer bracket needs its own occurrence anchor. +fn has_subscript_base(mut node: Node) -> bool { + loop { + node = peel_expression(node); + node = match node.cached_kind() { + "subscript_expression" => return true, + "field_expression" | "pointer_expression" => { + let Some(argument) = node.cached_field("argument") else { + return false; + }; + argument + } + "call_expression" => { + let Some(argument) = node + .cached_field("function") + .and_then(|function| function.cached_field("argument")) + else { + return false; + }; + argument + } + _ => return false, + }; + } +} + +pub(super) fn subscript_bracket_ignored(ctx: &LowerContext, node: Node) -> bool { + subscript_occurrence(node, ctx).is_some_and(|token| node_is_from_ignored_macro(ctx, token)) +} + +/// Whether an ignored macro spells any bracket, accessor, or field token in a +/// receiver chain. Resolving a field's element owner by type would otherwise +/// bypass an ignored bracket or accessor in its base. +pub(super) fn receiver_chain_ignored(ctx: &LowerContext, source: &str, node: Node) -> bool { + if ctx.ignored_macros.is_empty() { + return false; + } + if node_is_from_ignored_macro(ctx, node) { + return true; + } + let node = peel_expression(node); + if node_is_from_ignored_macro(ctx, node) { + return true; + } + match node.cached_kind() { + // An explicit dereference forwards to the pointer expression that + // spells the ignored bracket or accessor. + "pointer_expression" => node + .cached_field("argument") + .is_some_and(|argument| receiver_chain_ignored(ctx, source, argument)), + "subscript_expression" => { + subscript_bracket_ignored(ctx, node) + || node + .cached_field("argument") + .is_some_and(|base| receiver_chain_ignored(ctx, source, base)) + } + "call_expression" => { + method_is_from_ignored_macro(ctx, source, node) + || node + .cached_field("function") + .and_then(|function| function.cached_field("argument")) + .or_else(|| { + node.has_error() + .then(|| explicit_member_operator_call(node, source)) + .flatten() + .map(|op| op.receiver) + }) + .is_some_and(|base| receiver_chain_ignored(ctx, source, base)) + } + "field_expression" => { + node.cached_field("field") + .is_some_and(|field| node_is_from_ignored_macro(ctx, field)) + || node + .cached_field("argument") + .is_some_and(|base| receiver_chain_ignored(ctx, source, base)) + } + _ => false, + } +} + pub(super) fn effects_allowed(ctx: &LowerContext, source: &str, node: Node) -> bool { evaluated(ctx, source, node) && (ctx.ignored_macros.is_empty() - || !subscript_occurrence(node, ctx) - .is_some_and(|token| node_is_from_ignored_macro(ctx, token))) + || (!subscript_bracket_ignored(ctx, node) + && !method_is_from_ignored_macro(ctx, source, node))) } -fn inserted_values<'t>( +fn braced_clause_count(node: Node) -> Option { + (node.cached_kind() == "initializer_list").then(|| { + node.named_children(&mut node.walk()) + .filter(|child| child.cached_kind() != "comment") + .count() + }) +} + +/// The brace of a typed `std::pair{...}` compound literal. A pair literal is +/// one map entry, never an outer initializer list of entries. +fn compound_pair_brace<'t>( program: &Program, ctx: &LowerContext, source: &str, - arg: Node<'t>, + node: Node<'t>, +) -> Option> { + let node = peel_expression(node); + if node.cached_kind() != "compound_literal_expression" { + return None; + } + let spelling = node + .cached_field("type") + .and_then(|ty| type_spelling_node(program, ctx, source, ty))?; + let base = spelling + .split_once('<') + .map_or(spelling.as_str(), |(base, _)| base); + let base = without_leading_cv(base); + (canonical_std_class(base) == "std::pair").then_some(())?; + node.cached_field("value") + .filter(|value| value.cached_kind() == "initializer_list") +} + +struct InsertionOptions<'a> { entry: Option, list_overload: bool, + preserve_braces: bool, + /// A map `insert` accepts one `{key, mapped}` pair argument; a map + /// initializer list accepts only entries. + allow_single_pair: bool, + mapped: &'a TypeDesc, + /// The map key's specialization spelling, for validating the key clause + /// of a single-pair reading. + key: Option<&'a str>, +} + +fn make_pair_arguments<'t>(source: &str, node: Node<'t>) -> Option<[Node<'t>; 2]> { + if node.cached_kind() != "call_expression" { + return None; + } + let callee = node.cached_field("function")?; + let name = normalize_qualified(node_text(source, &callee)); + if !matches!( + name.trim_start_matches("::"), + "std::make_pair" | "std::__1::make_pair" + ) { + return None; + } + arguments(node.cached_field("arguments")?)?.try_into().ok() +} + +fn inserted_values<'t>( + program: &Program, + ctx: &LowerContext, + source: &str, + arg: Node<'t>, + options: InsertionOptions<'_>, values: &mut Vec>, ) { - let arg = peel_expression(arg); + let entry = options.entry; + let list_overload = options.list_overload; + let preserve_braces = options.preserve_braces; + let key_spelling = options + .key + .map(|key| canonical_alias_spelling(program, ctx, key)); + let clause_braced_value = |node, position| { + let node = compound_pair_brace(program, ctx, source, node).unwrap_or(node); + braced_value(node, position) + }; + let single_entry_viable = |candidate: Node| { + preserve_braces + && inner_container_viable(program, ctx, source, options.mapped, candidate) == Some(true) + }; + let pair_entry = |clause, entry| { + pair_clause_entry( + program, + ctx, + source, + clause, + entry, + key_spelling.as_deref(), + options.mapped, + ) + }; + let key_viable = |arg| { + if entry.is_none() { + return true; + } + let Some(key) = clause_braced_value(arg, Some(0)) else { + return true; + }; + key_braced_accepts(program, ctx, source, key, key_spelling.as_deref()) + }; + let list_entry = |clause, entry| { + if braced_clause_count(clause) == Some(0) { + return map_entry_can_default(program, key_spelling.as_deref(), options.mapped) + .then_some(PairEntry::Unmodeled); + } + if let Some(mapped) = clause_braced_value(clause, Some(entry)) { + return (key_viable(clause) && (!preserve_braces || single_entry_viable(mapped))) + .then_some(PairEntry::Mapped(StoredValue::Expression(mapped))); + } + pair_entry(clause, entry) + }; + let original = peel_expression(arg); + if node_is_from_ignored_macro(ctx, original) + || original + .cached_field("type") + .is_some_and(|ty| node_is_from_ignored_macro(ctx, ty)) + { + return; + } + // Only an initializer_list compound literal collapses into the outer + // list branch. A typed std::pair literal is always one entry, so its + // brace stays separate for the single-pair reading below. + let initializer_list_literal = preserve_braces + && original.cached_kind() == "compound_literal_expression" + && original + .cached_field("type") + .and_then(|ty| type_spelling_node(program, ctx, source, ty)) + .is_some_and(|spelling| { + let base = spelling + .split_once('<') + .map_or(spelling.as_str(), |(base, _)| base); + canonical_std_class(without_leading_cv(base)) == "std::initializer_list" + }); + let arg = if initializer_list_literal { + original + .cached_field("value") + .filter(|value| value.cached_kind() == "initializer_list") + .unwrap_or(original) + } else { + original + }; + let pair_brace = compound_pair_brace(program, ctx, source, original); if node_is_from_ignored_macro(ctx, arg) { return; } if list_overload && arg.cached_kind() == "initializer_list" { - let mut cursor = arg.walk(); - // A map initializer list is a list of entries. Treat the argument - // as one pair when its clauses are the key and the mapped value. - if entry.is_none() - || arg + if let Some(entry) = entry { + // Read each map clause independently: a mixed list may hold + // braced entries and named or make_pair entries, and one bad + // clause must not discard the others. + let mut cursor = arg.walk(); + let entries: Vec<_> = arg .named_children(&mut cursor) - .filter(|node| node.cached_kind() != "comment") - .all(|clause| braced_value(clause, entry).is_some()) - { + .filter(|clause| { + clause.cached_kind() != "comment" && !node_is_from_ignored_macro(ctx, *clause) + }) + .map(|clause| list_entry(clause, entry)) + .collect(); + // A `{key, mapped}` pair whose mapped initializer itself has two + // clauses must be read as one pair unless every clause is a + // viable map entry. + let all_clauses_entries = !entries.is_empty() && entries.iter().all(Option::is_some); + if options.allow_single_pair + && !all_clauses_entries + && braced_clause_count(arg) == Some(entry + 1) + && key_viable(arg) + { + let mapped = braced_value(arg, Some(entry)).expect("mapped clause"); + if preserve_braces { + if single_entry_viable(mapped) { + values.push(StoredValue::Expression(mapped)); + } + return; + } + // An empty brace value-initializes the mapped callback. + if braced_clause_count(mapped) == Some(0) { + return; + } + if let Some(value) = unwrap_braced_value(mapped) { + values.push(StoredValue::Expression(value)); + return; + } + } values.extend( - arg.named_children(&mut cursor) - .filter(|node| node.cached_kind() != "comment") - .filter_map(|clause| { - unwrap_braced_value(braced_value(clause, entry)?) - .map(StoredValue::Expression) + entries + .into_iter() + .flatten() + .filter_map(|entry| match entry { + PairEntry::Mapped(value) => Some(value), + PairEntry::Unmodeled => None, }), ); return; - } - } - if let Some(value) = braced_value(arg, entry).and_then(unwrap_braced_value) { - values.push(StoredValue::Expression(value)); - } else if let Some(position) = entry { - if arg.cached_kind() == "call_expression" { - if let Some(callee) = arg.cached_field("function") { - let name = normalize_qualified(node_text(source, &callee)); - if matches!( - name.trim_start_matches("::"), - "std::make_pair" | "std::__1::make_pair" - ) { - if let Some([first, second]) = arg - .cached_field("arguments") - .and_then(arguments) - .and_then(|args| <[Node; 2]>::try_from(args).ok()) - { - values.extend( - [first, second] - .get(position) - .copied() - .map(StoredValue::Expression), - ); + } else { + // A position insert may initialize one inner container + // (`insert(pos, {{1, alpha}, {2, beta}})`) or a list of inner + // containers (`insert(pos, {inner1, inner2})`). Keep the whole + // brace only when its clauses are not each inner containers. + let mut cursor = arg.walk(); + let clauses: Vec<_> = arg + .named_children(&mut cursor) + .filter(|node| node.cached_kind() != "comment") + .collect(); + let active: Vec<_> = clauses + .iter() + .filter(|clause| !node_is_from_ignored_macro(ctx, **clause)) + .collect(); + let all_clauses_inner = + !active.is_empty() && active.iter().all(|clause| single_entry_viable(**clause)); + if preserve_braces && single_entry_viable(arg) && !all_clauses_inner { + values.push(StoredValue::Expression(arg)); + } else { + for clause in clauses { + if node_is_from_ignored_macro(ctx, clause) { + continue; + } + if preserve_braces { + values.push(StoredValue::Expression(clause)); + } else if let Some(value) = unwrap_braced_value(clause) { + values.push(StoredValue::Expression(value)); } } } - } else if position == 1 && is_name(arg) { - if let Some(var) = lookup_var_node(program, ctx, source, arg) { - if let Some((field, ty)) = pair_field(program, var, "second") { - values.push(StoredValue::PairSecond(arg, var, field, ty)); - } + return; + } + } + // A braced argument that initializes an inner container keeps its braces + // so `store_values` can interpret it at the inner level. This also covers + // the single-pair map spelling `insert({key, {alpha, beta}})`. + if preserve_braces { + let node = pair_brace.unwrap_or(arg); + if let Some(value) = braced_value(node, entry) { + if entry.is_none() || (key_viable(node) && single_entry_viable(value)) { + values.push(StoredValue::Expression(value)); } + return; + } + } + let node = entry.and(pair_brace).unwrap_or(arg); + if let Some(value) = braced_value(node, entry).and_then(unwrap_braced_value) { + // A multi-clause braced key cannot initialize a scalar/pointer key, + // so this is not a single pair; do not read its mapped clause. + if entry.is_none() || key_viable(node) { + values.push(StoredValue::Expression(value)); } + } else if let Some(PairEntry::Mapped(value)) = + entry.and_then(|position| pair_entry(arg, position)) + { + values.push(value); } } @@ -2273,7 +4362,9 @@ pub(super) fn lower_insertion( }; let arity = args.len(); if !evaluated(ctx, source, call) + || node_is_from_ignored_macro(ctx, call) || node_is_from_ignored_macro(ctx, recv) + || method_is_from_ignored_macro(ctx, source, call) || !model .operations .iter() @@ -2295,6 +4386,8 @@ pub(super) fn lower_insertion( if !matched { return; } + let preserve_braces = elements.nested(program, ctx).is_some(); + let key = elements.map_key(); let mut values = Vec::new(); for op in model .operations @@ -2307,12 +4400,19 @@ pub(super) fn lower_insertion( ctx, source, args[*value], - *entry, - matches!(method.as_ref(), "insert" | "insert_after"), + InsertionOptions { + entry: *entry, + list_overload: matches!(method.as_ref(), "insert" | "insert_after"), + preserve_braces, + allow_single_pair: true, + mapped: elements.element(), + key, + }, &mut values, ); } } + if !values.is_empty() { elements.store_values(program, ctx, source, call, values); } @@ -2332,7 +4432,16 @@ pub(super) fn lower_subscript_call( return; }; let macro_token = subscript_occurrence(node, ctx); - let occurrence = macro_token.unwrap_or(node); + // Chained subscripts share their expression start, which would coalesce + // their call records during merge. Anchor an intermediate receiver's site + // at its own bracket so every level keeps a distinct source identity. + let occurrence = macro_token + .or_else(|| { + has_subscript_base(receiver) + .then(|| subscript_bracket(node)) + .flatten() + }) + .unwrap_or(node); let Some(Access::Direct(elements)) = access(program, ctx, source, node) else { return; }; @@ -2431,7 +4540,7 @@ pub(super) fn lower_field_initializer( if program.types.field_is_reference(class, name) { return; } - if let Some(elements) = Elements::for_field(program, owner, name, &object.desc) { + if let Some(elements) = Elements::for_field(program, ctx, owner, name, &object.desc) { lower_list_initializer(program, ctx, source, elements, init); } } @@ -2463,18 +4572,14 @@ fn lower_list_initializer( model, init, |arity, value_initialized_allocator| { - if program.types.is_struct_defined(&owner) { - list_constructors(program, &owner, model) - .any(|ctor| ctor.accepts(arity, value_initialized_allocator)) - } else { - canonical_declarations(ctx) - .and_then(|decls| decls.list_constructors.get(owner.as_ref())) - .is_some_and(|ctors| { - ctors - .iter() - .any(|ctor| ctor.accepts(arity, value_initialized_allocator)) - }) - } + list_constructor_accepts( + program, + ctx, + &owner, + model, + arity, + value_initialized_allocator, + ) }, ) else { return false; @@ -2482,15 +4587,50 @@ fn lower_list_initializer( let node = list.values; if !node_is_from_ignored_macro(ctx, init) && !node_is_from_ignored_macro(ctx, node) { let entry = model.initializer_entry; - let mut cursor = node.walk(); - let mut values = node - .named_children(&mut cursor) - .filter(|n| n.cached_kind() != "comment") - .filter_map(|value| unwrap_braced_value(braced_value(value, entry)?)) - .peekable(); - if values.peek().is_some() { + // A nested container's braced entry describes that inner container, + // so keep the braces for `store_values` to interpret at the inner + // level instead of flattening single-element lists. + let preserve_braces = elements.nested(program, ctx).is_some(); + let mut values = Vec::new(); + if let Some(entry) = entry { + inserted_values( + program, + ctx, + source, + node, + InsertionOptions { + entry: Some(entry), + list_overload: true, + preserve_braces, + allow_single_pair: false, + mapped: elements.element(), + key: elements.map_key(), + }, + &mut values, + ); + } else { + let mut cursor = node.walk(); + for clause in node + .named_children(&mut cursor) + .filter(|n| n.cached_kind() != "comment") + { + if node_is_from_ignored_macro(ctx, clause) { + continue; + } + let value = if preserve_braces { + clause + } else { + let Some(value) = unwrap_braced_value(clause) else { + continue; + }; + value + }; + values.push(StoredValue::Expression(value)); + } + } + if !values.is_empty() { lower_operation(program, ctx, source, node, |program, ctx| { - elements.store(program, ctx, source, node, values); + elements.store_values(program, ctx, source, node, values); }); } } diff --git a/crates/trace-parse/src/lower.rs b/crates/trace-parse/src/lower.rs index eb519b69..35ede1bf 100644 --- a/crates/trace-parse/src/lower.rs +++ b/crates/trace-parse/src/lower.rs @@ -240,6 +240,10 @@ struct LowerContext { /// Typedefs and `using` aliases declared in the blocks of the function /// being lowered, innermost last; each block drops its own on exit. local_aliases: Vec, + /// Locals that receive a nested container's elements: a range-for + /// variable over a container of containers, so its own subscripts and + /// ranges read the nested cell rather than the variable's element cell. + nested_container_owners: HashMap, /// Block declarations shadow outer defaults independently of FnId interning. default_scopes: Vec, call_default_bindings: HashMap>, @@ -278,6 +282,8 @@ struct LowerContext { /// A call node has one lexical scope and static return type. Reuse /// receiver probes across outer-chain lookup and the body's later walk. call_receiver_cache: RefCell>, + /// Successful nested owners of access expressions, shared by chain prefixes. + container_access_owners: RefCell>, /// `call_expression` node id → `CallReturn` destination, so the matching /// `CallSite` can carry `return_dst` for `dlsym` models. call_return_dst: RefCell>, @@ -4472,6 +4478,7 @@ fn lower_prepared_source( friend_classes: Vec::new(), type_scope: RefCell::new(Vec::new()), local_aliases: Vec::new(), + nested_container_owners: HashMap::default(), default_scopes: Vec::new(), call_default_bindings: HashMap::default(), initializer_default_scopes: RefCell::default(), @@ -4485,6 +4492,7 @@ fn lower_prepared_source( macro_lambda_text: HashMap::default(), callee_load_cache: RefCell::new(HashMap::default()), call_receiver_cache: RefCell::new(HashMap::default()), + container_access_owners: RefCell::new(HashMap::default()), call_return_dst: RefCell::new(HashMap::default()), call_address_dst: RefCell::new(HashMap::default()), expression_values: RefCell::new(HashMap::default()), @@ -4551,6 +4559,7 @@ fn lower_prepared_source( ctx.handled_constructor_exprs.borrow_mut().clear(); ctx.callee_load_cache.borrow_mut().clear(); ctx.call_receiver_cache.borrow_mut().clear(); + ctx.container_access_owners.borrow_mut().clear(); ctx.call_return_dst.borrow_mut().clear(); ctx.call_address_dst.borrow_mut().clear(); ctx.expression_values.borrow_mut().clear(); @@ -4969,11 +4978,14 @@ fn declared_alias( ) }; let type_spelling = (ctx.is_cpp - && !matches!( - desc, - TypeDesc::Struct { .. } | TypeDesc::Union { .. } | TypeDesc::Unknown - )) - .then(|| container_elements::type_spelling(program, ctx, source, declaration)) + && match &desc { + TypeDesc::Unknown => false, + // A specialization alias (`using Items = std::vector`) keeps + // its arguments; a plain class alias needs no separate spelling. + TypeDesc::Struct { name, .. } | TypeDesc::Union { name, .. } => name.contains('<'), + _ => true, + }) + .then(|| container_elements::type_spelling_implicit_defaults(program, ctx, source, declaration)) .flatten() .map(Arc::from); Some(trace_ir::InitializerAlias { @@ -14709,6 +14721,13 @@ fn lower_statement_local(program: &mut Program, ctx: &mut LowerContext, source: // element source now so `for (Callback callbacks : callbacks)` still // names the outer container rather than the variable being declared. let range_source = range.and_then(|range| range_source(program, ctx, source, range)); + // A range over a container of containers binds the loop variable to the + // inner elements carried by the outer element cell, so its own subscripts + // and nested ranges read callbacks stored through the outer container. + let nested_container = match &range_source { + Some(RangeSource::Container(elements)) => elements.nested(program, ctx), + _ => None, + }; // Prefer the resolved element descriptor for `auto`, which carries a // function-pointer alias the spelling walk leaves unknown; fall back to // the spelling lookup for unmodeled ranges and arrays. @@ -14725,7 +14744,6 @@ fn lower_statement_local(program: &mut Program, ctx: &mut LowerContext, source: Some(RangeSource::Container(elements)) => Some(elements.cv(program)), _ => None, }; - let binds_reference = decl.cached_kind() == "reference_declarator"; let ty = deduced_local_type(program, type_id, decl, element); let var = lower_one_declarator( program, @@ -14740,7 +14758,26 @@ fn lower_statement_local(program: &mut Program, ctx: &mut LowerContext, source: Lifecycle::DestroyOnly, ); forget_placeholder_alias(ctx, type_node, var); + let binds_reference = decl.cached_kind() == "reference_declarator" + || var.is_some_and(|var| ctx.reference_bindings.contains(&var)); if let Some(var) = var { + if let Some(nested) = &nested_container { + if binds_reference { + ctx.nested_container_owners + .insert(var, nested.owner().clone()); + } else { + let span = range.unwrap_or(node); + lower_operation(program, ctx, source, span, |program, ctx| { + container_elements::copy_into_range_var( + program, + ctx, + span, + nested.clone(), + var, + ); + }); + } + } if let (Some(range), Some(range_source)) = (range, range_source) { flow_range_element(program, ctx, source, range, range_source, var); } @@ -14778,32 +14815,6 @@ enum RangeSource { Container(container_elements::Elements), } -/// Whether a range expression is spelled through an ignored macro. A field -/// range (`holder.RANGE_MEMBER`, `outer.SELECT_NESTED.entries`) starts at the -/// object, so every field token on the receiver chain has its own provenance -/// checked, as member-call lowering does. -fn range_is_from_ignored_macro(ctx: &LowerContext, range: Node) -> bool { - let mut node = range; - loop { - if node_is_from_ignored_macro(ctx, node) { - return true; - } - if node.cached_kind() != "field_expression" { - return false; - } - if node - .cached_field("field") - .is_some_and(|field| node_is_from_ignored_macro(ctx, field)) - { - return true; - } - let Some(argument) = node.cached_field("argument") else { - return false; - }; - node = peel_expression(argument); - } -} - /// Resolve an array summary or an iterable modeled container's element /// summary for `range`. The caller must run this before declaring the loop /// variable so a shadowing name still names the outer range. @@ -14816,7 +14827,7 @@ fn range_source( // The `for` statement may start outside a macro while the range itself is // spelled inside one (`for (T x : RANGE)`); an ignored range macro // suppresses the read the same way an ignored subscript bracket does. - if range_is_from_ignored_macro(ctx, range) { + if container_elements::receiver_chain_ignored(ctx, source, range) { return None; } if receiver_desc(program, ctx, source, range) @@ -20987,6 +20998,7 @@ fn with_initializer_expression( let saved_scope = ctx.type_scope.replace(initializer.type_scope.clone()); let saved_loads = ctx.callee_load_cache.take(); let saved_receivers = ctx.call_receiver_cache.take(); + let saved_container_owners = ctx.container_access_owners.take(); // A reparsed initializer brings its own syntax tree, whose node ids may // repeat those of the tree being lowered. A decided result is only valid // while its call's node is alive. @@ -21005,6 +21017,7 @@ fn with_initializer_expression( let result = lower(program, ctx, &source, value); ctx.callee_load_cache.replace(saved_loads); ctx.call_receiver_cache.replace(saved_receivers); + ctx.container_access_owners.replace(saved_container_owners); ctx.from_this_results.replace(saved_from_this); ctx.call_return_dst.replace(saved_returns); ctx.call_address_dst.replace(saved_addresses); @@ -22840,6 +22853,13 @@ fn receiver_desc( { return Some(program.types.get(field.type_id).desc.as_ref().clone()); } + // A named standard pair's specialized second member names the + // mapped container, which the primary template does not. + if let Some(var) = lookup_var_node(program, ctx, source, base) { + if let Some((_, ty)) = container_elements::pair_field(program, var, member) { + return Some(program.types.get(ty).desc.as_ref().clone()); + } + } } let cls = if let Some((receiver, member)) = container_elements::iterator_member_operand(ctx, source, node) @@ -23032,6 +23052,22 @@ fn receiver_desc( if ty.cached_field("declarator").is_some() { return None; } + // A specialization's arguments live only in the type node; the + // raw-text class probe drops them. + if let Some(spelling) = container_elements::type_spelling_node(program, ctx, source, ty) + .filter(|spelling| spelling.contains('<')) + { + return if container_elements::has_top_level(&spelling, '*') + || container_elements::has_top_level(&spelling, '&') + { + Some(TypeDesc::Unknown) + } else { + Some(TypeDesc::Struct { + name: spelling, + fields: Vec::new(), + }) + }; + } let name = normalize_qualified(node_text(source, &ty)); declared_class_in_scope(program, ctx, &name).map(|name| TypeDesc::Struct { name, @@ -35590,6 +35626,7 @@ mod qualified_variable_lookup_tests { friend_classes: Vec::new(), type_scope: RefCell::new(Vec::new()), local_aliases: Vec::new(), + nested_container_owners: HashMap::default(), default_scopes: Vec::new(), call_default_bindings: HashMap::default(), initializer_default_scopes: RefCell::default(), @@ -35603,6 +35640,7 @@ mod qualified_variable_lookup_tests { macro_lambda_text: HashMap::default(), callee_load_cache: RefCell::new(HashMap::default()), call_receiver_cache: RefCell::new(HashMap::default()), + container_access_owners: RefCell::new(HashMap::default()), call_return_dst: RefCell::new(HashMap::default()), call_address_dst: RefCell::new(HashMap::default()), expression_values: RefCell::new(HashMap::default()), diff --git a/crates/trace-parse/src/merge.rs b/crates/trace-parse/src/merge.rs index 0c55d286..b448b6eb 100644 --- a/crates/trace-parse/src/merge.rs +++ b/crates/trace-parse/src/merge.rs @@ -1992,15 +1992,26 @@ fn remap_flow( element, } => { use trace_ir::ContainerOwner; - FlowConstraint::ContainerElement { - dst: rv(*dst), - owner: match owner { + fn remap_owner( + owner: &ContainerOwner, + rv: &dyn Fn(VarId) -> VarId, + type_map: &[TypeId], + ) -> ContainerOwner { + match owner { ContainerOwner::Variable(var) => ContainerOwner::Variable(rv(*var)), ContainerOwner::Field { class, name } => ContainerOwner::Field { class: remap_type(*class, type_map), name: name.clone(), }, - }, + ContainerOwner::Nested { parent, instance } => ContainerOwner::Nested { + parent: Arc::new(remap_owner(parent, rv, type_map)), + instance: instance.clone(), + }, + } + } + FlowConstraint::ContainerElement { + dst: rv(*dst), + owner: remap_owner(owner, &rv, type_map), element: remap_type(*element, type_map), } } diff --git a/docs/CXX.md b/docs/CXX.md index 692e17a8..50b8c787 100644 --- a/docs/CXX.md +++ b/docs/CXX.md @@ -1341,8 +1341,8 @@ Map models read the mapped slot from braced key/value entries, direct `std::make_pair` arguments, and named `std::pair` values initialized from two arguments or braced clauses. Named pair reads use the ordinary field summaries for their concrete specialization. Copy initialization and assignment between -named pair specializations propagate pointer and callable values between -matching fields. Explicit pair specializations use their indexed constructor +named pair specializations propagate pointer, callable, and modeled container +element values between matching fields. Explicit pair specializations use their indexed constructor declarations, while ordinary instantiations use the primary template's declarations. Braced `insert` calls can store each element of a sequence or set list, or the mapped slot from each braced map @@ -1385,15 +1385,76 @@ types `h` as `T const*` and `h->run()` selects `T::run() const`. An ignored macro that spells any field on the range's receiver chain (`for (T x : outer.SELECT_NESTED.entries)`) suppresses the read. -Follow-ups include container copies, iterator arithmetic and reference -parameters, write-back through reference loop variables, map iteration (which -yields a pair), access via pointers or references to the container itself, -nested containers, structured bindings, and element models for the set-like, -array, span and initializer-list spellings. Planned stores +A modeled container whose element is another modeled container stores inner +values in a nested cell keyed by the outer owner and the inner specialization. +Storing a named inner container copies its element cell and matching descendant +cells. A named pair contributes the mapped member's cells. By-value range +variables get their own seeded cells. Reference variables, including reference +aliases, bind the source cell. These copies and reads are flow-insensitive. +Named containers stay isolated by variable, and field-owned containers share +cells by declaring member and element type. + +Nested cells and copies compare canonical specializations. Aliases, inline +standard-library namespaces, and explicit spellings of default arguments +resolve to the same identity. Defaults come from the indexed declaration or +the canonical prelude. Alias storage keeps defaults implicit. Long type +arguments use a stable identity before they can be duplicated by an enclosing +specialization, including in an explicit allocator. Top-level cv-qualification +on a container or on a callback's by-value parameter leaves the specialization's +identity intact. Pointee qualification can distinguish specializations, such as +`std::vector` and `std::vector`. + +Braced inner values use the inner container's constructor rules. The model +must opt into initializer lists, including for a typed `std::initializer_list` +temporary. Default construction via an empty brace and ordinary constructors +use their own rules. Named and typed copies, including allocator-extended +copies using the specialization's bound allocator, preserve the source's +element summary. `std::move` and `std::forward` use the operand's cell. A +derived or convertible inner value can keep a list viable even when analysis +has no cell for that value. A call with a declared return type can identify a +viable inner value, and propagating the return value's element summary requires +separate modeling. + +Map initializer lists and inserts can mix braced entries, typed pair literals, +named pairs, and `std::make_pair` expressions. Both list recognition and +mapped-value extraction check key compatibility for non-braced pairs. +Arithmetic, qualification, and possible class-key conversions are allowed. +An integer key expression can reach a converting constructor through a +standard numeric conversion. +For a pair-shaped key, the first member of a candidate entry has to initialize +the entire key. Converting pairs are checked component by component. An indexed +class key supplied as a single expression needs a compatible type, a possible +conversion operator, or a viable constructor. +A compatible pair-returning call can count as an entry while contributing no +stored value. Empty entry braces contribute no store and require a viable +default construction. Standard map layouts identify their key in template +argument zero. +Custom models use their configured entry position. + +A map initializer requires a list of entries. An insert also accepts a single +`{key, mapped}` pair when the key fits and the clauses do not all form +entries. The mapped value keeps its braces for inner-container construction. +For position inserts into nested sequences, the entire brace can initialize +one inner container, or its clauses can supply a list of inner containers. + +Each bracket in a subscript chain needs its own configured access operation. +Modeled accessors such as `at`, `front`, and `back` also descend to the +receiver's nested cell. Brackets have distinct source sites, including in +unevaluated chains. Lowering reuses the resolved owners of access prefixes. +Ignored macro provenance on a receiver, bracket, or member access, including +an explicit `operator[]` token, stops its modeled flow. Chained accesses and +nested ranges can read the same stored values in `std::vector>`, +`std::map>`, and `std::vector>`. + +Follow-ups include container copies, element summaries returned from calls, +iterator arithmetic and reference parameters, write-back through reference loop +variables, map iteration (which yields a pair) and structured bindings, access +via pointers or references to the container itself, chained lookups through +`find(...)->second`, and element +models for the set-like, array, span and initializer-list spellings. Planned stores include fill construction, initializer-list assignment and `assign`, and -`try_emplace`. Pair projections currently cover named standard pairs and direct -`std::make_pair` calls. Other pair-producing expressions and lists of typed -pair expressions are follow-ups. +`try_emplace`. Extracting mapped values from other pair-producing expressions, +such as calls returning pairs, remains a follow-up. ### Factory construction diff --git a/docs/EVAL_REPORT.md b/docs/EVAL_REPORT.md index baf6e7e9..8fc0a14e 100644 --- a/docs/EVAL_REPORT.md +++ b/docs/EVAL_REPORT.md @@ -1,5 +1,37 @@ # Evaluation Report +## Nested container cells - 2026-11-26 + +Containers whose element type is itself a modeled container now get the outer +cell and the nested cell their inner values need. The canonical debug checks on +the pinned corpora show four new HiView cells and two new Camera cells: + +| Corpus | Measurement | Before | After | +|---|---|---:|---:| +| HiView | modeled element cells | 35 | 39 | +| Camera | modeled element cells | 8 | 10 | + +The HiView additions are the outer and nested cells for +`BaseContext.monitors` and `XperfMonitorManager.dispatchers`, both containers of +`std::vector<...*>`. The Camera additions are the outer and nested cells for +`HCameraService.delayCbtaskMap_`, a map of maps. + +The review fix also restores callback flow through unscoped enum map keys. +Fresh debug exports of the pinned HiView checkout before and after the fix +show 333 to 349 indirect edges. All 16 restored edges are local lambda +targets, four each at `decoded_event.cpp:162`, `decoded_event.cpp:201`, +`raw_data_builder.cpp:378`, and `raw_data_builder.cpp:425`. The two +`DecodedEvent` sites again forward `param` to all eight lambda formals. +Both corpora pass all 44 canonical checks at `--jobs 1` and `--jobs 8`, with +identical analysis rows at both job counts. + +The subsequent review fixes preserve the canonical HiView and Camera analysis +rows from `bf57e6a`. In a separate `--full-export` probe, each alias in a +15-level chain names the previous type in both `std::vector` arguments, once +directly and once through `std::allocator`. The longest exported type name +falls from 1,703,906 characters to 158. A 27-level run peaks at 5,986 characters +and still resolves the innermost callback through the full subscript chain. + ## Container range-for reads and canonical budget - 2026-11-24 A `range-for` over a named modeled sequence or set container now reads the same diff --git a/docs/IR.md b/docs/IR.md index 313402bc..7f4bae94 100644 --- a/docs/IR.md +++ b/docs/IR.md @@ -336,8 +336,11 @@ Nested call arguments (`consume(make())`, `Register(obj->GetHandler())`, `consum **`ContainerElement`** gives `dst` the address of a typed, index-insensitive container element cell. A named container uses its merged variable identity. A data member uses its declaring type and member identity within the link -target, sharing the cell across instances of that member. Lowering emits -ordinary `Store` and `Load` facts through the address. See [Container +target, sharing the cell across instances of that member. A modeled container +element that is itself a modeled container uses a nested owner keyed by the +parent owner and the inner specialization, so inner values stay addressable +through chained subscripts and nested ranges. Lowering emits ordinary `Store` +and `Load` facts through the address. See [Container elements](CXX.md#container-elements) for the supported C++ operations. **`NewHeap`** represents C++ `new T(...)` allocations, and the object a recognised smart-pointer factory builds ([Factory construction](CXX.md#factory-construction)). The PAG allocates a heap location typed to the allocated struct and adds an `AddrOf` edge from `dst` to the heap location. The solver then propagates into the struct's fields, enabling resolution of function pointers stored by constructors (e.g., `MParcelImplInterfaceAssign` writing into `HdfSBufImpl.readBuffer`). Lowering (`lower_new_object`, `construct_on_heap` in `lower.rs`) gives every `new T(args)` its heap object, a `$new` temporary typed `T`, in value and statement position alike, and at file scope too; the constructor sites (in a body) take it as `this` and the constructor's own argument list as their arguments, never a placement list (`new (std::nothrow) T(a, b)` passes `a, b`); a braced list (`new T{a, b}`) is that list when `T` has a user-provided constructor, as for a braced local, and otherwise initializes an aggregate member by member, with no constructor site; and the expression's value is that object. A construction from one argument records no constructor site (`copies_implicitly`, checked in `emit_member_targets`) wherever the object is built (`new T(other)`, a factory, a local `T x(other)`, a class-typed member initializer `m_(other)`) when either no constructor of the class takes one argument, or the argument is an object of the class itself (directly or by reference) and no constructor takes the class: that is a copy or a move, which runs the implicit constructor, where arity filtering would otherwise fall back to every constructor, or rank `T(int)`, and bind the copied object to an unrelated parameter. A pointer argument (`T *`) is not an object copy; a reference to a pointer keeps that pointer type too. A user-declared copy or move constructor (`T(const T &)`) keeps its site, including constructors whose later parameters have defaults (`T(const T &, int = 0)`). An aggregate whose definition and constructor set are indexed, copied from its own type, records no unresolved constructor site. For `new` and factories, cached project headers import project prerequisites as types only, so an empty constructor lookup there retains a site for the later TU symbol merge to resolve. A missing class definition or an unknown constructor parameter type retains the possible constructor edge on those paths. Member-initializer lists omit the implicit default or copy constructor itself while retaining nontrivial construction of its base and member subobjects. A reference member's binding (`ref_(other)`) records none regardless of its class's constructors. See [Ctors / dtors](CXX.md#c-support-first-step) for the member-initializer rule. diff --git a/scripts/eval_expected_canonical.json b/scripts/eval_expected_canonical.json index 45783376..8f6f74a4 100644 --- a/scripts/eval_expected_canonical.json +++ b/scripts/eval_expected_canonical.json @@ -1,5 +1,5 @@ { - "note": "Pinned corpora in canonical system-header mode with the embedded models. Recaptured after rebasing onto local master bb64b1e on Windows 11 x64 with MSYS2 MinGW GCC 15.2.0. Header-dependent totals use that toolchain as the reference. Counts include the 2026-11-20 vector specialization audit. The 2026-11-20 binder Host/interface-overload change recaptured the canonical IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641; ability_runtime edges_total 418036 -> 417915 and diagnostics 11944 -> 11945; HDF and HiView IPC counts are unchanged. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_total 417915 -> 418405, edges_indirect 2043 -> 2533 and public_edges_total 409148 -> 410574, with the same run reporting diagnostics 11944; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime functions_total 89063 -> 88690, functions_external 20414 -> 20041, edges_total 418405 -> 420602, edges_direct 255993 -> 257078, edges_external 158238 -> 159350, arg_flow_edges 455892 -> 457968, public_functions_total 85660 -> 85287 and public_edges_total 410574 -> 412771; diagnostics, IPC and indirect centers are unchanged. `budget_pops` is null so canonical runs use the analyzer's derived pop budget, which scales with the PAG constraint count and reaches a fixpoint instead of truncating at a flat cap (docs/POINTERS.md, Work budget). The range-for container read recaptured the modeled element counts (HDF 3 -> 4, HiView 33 -> 35, Camera 7 -> 8, Ability Runtime 38 -> 39) and ability_runtime edges_total 420602 -> 420605, edges_indirect 2533 -> 2536 and arg_flow_edges 457968 -> 457970, where ConnectServerManager's range-for callback dispatch now reaches its registered callbacks. The range-for pointee-const change recaptured ability_runtime edges_total 420605 -> 420591 and edges_direct 257078 -> 257064: const receivers no longer reach the non-const overload of ExtractInsightIntentGenericInfo::get(). See docs/EVAL_REPORT.md.", + "note": "Pinned corpora in canonical system-header mode with the embedded models. Recaptured after rebasing onto local master bb64b1e on Windows 11 x64 with MSYS2 MinGW GCC 15.2.0. Header-dependent totals use that toolchain as the reference. Counts include the 2026-11-20 vector specialization audit. The 2026-11-20 binder Host/interface-overload change recaptured the canonical IPC centers: Camera 808 -> 702 and ability_runtime 1762 -> 1641; ability_runtime edges_total 418036 -> 417915 and diagnostics 11944 -> 11945; HDF and HiView IPC counts are unchanged. The 2026-11-23 AAFwk TaskHandlerWrap::SubmitTask/SubmitTaskJust invoke models recaptured ability_runtime edges_total 417915 -> 418405, edges_indirect 2043 -> 2533 and public_edges_total 409148 -> 410574, with the same run reporting diagnostics 11944; the new probe pins AmsMgrScheduler::StartSpecifiedAbility reaching AppMgrServiceInner::StartSpecifiedAbility through its submitted lambda. The 2026-11-23 binder-wrapper member-resolution change recaptured ability_runtime functions_total 89063 -> 88690, functions_external 20414 -> 20041, edges_total 418405 -> 420602, edges_direct 255993 -> 257078, edges_external 158238 -> 159350, arg_flow_edges 455892 -> 457968, public_functions_total 85660 -> 85287 and public_edges_total 410574 -> 412771; diagnostics, IPC and indirect centers are unchanged. `budget_pops` is null so canonical runs use the analyzer's derived pop budget, which scales with the PAG constraint count and reaches a fixpoint instead of truncating at a flat cap (docs/POINTERS.md, Work budget). The range-for container read recaptured the modeled element counts (HDF 3 -> 4, HiView 33 -> 35, Camera 7 -> 8, Ability Runtime 38 -> 39) and ability_runtime edges_total 420602 -> 420605, edges_indirect 2533 -> 2536 and arg_flow_edges 457968 -> 457970, where ConnectServerManager's range-for callback dispatch now reaches its registered callbacks. The range-for pointee-const change recaptured ability_runtime edges_total 420605 -> 420591 and edges_direct 257078 -> 257064: const receivers no longer reach the non-const overload of ExtractInsightIntentGenericInfo::get(). The nested-container change then added the outer and nested cells for containers whose elements are themselves modeled containers: HiView modeled element cells 35 -> 39 and Camera 8 -> 10, with every other global and probe unchanged. See docs/EVAL_REPORT.md.", "analyze_args": [ "--canonical-system-headers", "--compiler", @@ -65,7 +65,7 @@ {"case": "Raw data builder array dispatch", "caller": "%::InitArrayValueParams", "caller_file": "%raw_data_builder.cpp", "line": 425, "resolution": "indirect", "expected": 4} ], "probes": [ - {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 35}, + {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 39}, {"name": "DecodedEvent array lookup reaches only its four local lambdas", "sql": "SELECT COUNT(*) = 4 AND SUM(t.name GLOB c.name || '::$lambda*') = 4 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions c ON c.id = e.caller_fn_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%decoded_event.cpp' AND s.line = 162 AND c.name LIKE '%::AppendCustomizedArrayParam' AND e.resolution = 'indirect'", "cmp": "exact", "value": 1}, {"name": "DecodedEvent scalar lookup reaches only its four local lambdas", "sql": "SELECT COUNT(*) = 4 AND SUM(t.name GLOB c.name || '::$lambda*') = 4 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions c ON c.id = e.caller_fn_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%decoded_event.cpp' AND s.line = 201 AND c.name LIKE '%::AppendCustomizedParam' AND e.resolution = 'indirect'", "cmp": "exact", "value": 1}, {"name": "DecodedEvent forwards param to every local lambda", "sql": "SELECT COUNT(DISTINCT a.formal_var_id) FROM arg_flow_edges a JOIN call_sites s ON s.id = a.call_site_id JOIN files p ON p.id = s.file_id JOIN functions c ON c.id = s.caller_fn_id JOIN variables u ON u.id = a.actual_var_id JOIN variables v ON v.id = a.formal_var_id JOIN functions t ON t.id = v.fn_id WHERE p.path LIKE '%decoded_event.cpp' AND s.line IN (162, 201) AND c.name LIKE '%::DecodedEvent::AppendCustomized%Param' AND a.arg_index = 0 AND u.fn_id = c.id AND u.name = 'param' AND v.name = 'param' AND t.name GLOB c.name || '::$lambda*'", "cmp": "exact", "value": 8} @@ -99,7 +99,7 @@ {"case": "System NAPI session factory subscript", "caller": "%::createSessionInstanceForSys", "caller_file": "%camera_session_for_sys_napi.cpp", "line": 2419, "resolution": "indirect", "expected": 19} ], "probes": [ - {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 8}, + {"name": "Modeled container element cells", "sql": "SELECT COUNT(*) FROM flow_nodes WHERE detail = 'array_summary' AND label LIKE 'elements:%'", "cmp": "exact", "value": 10}, {"name": "Device protection map values reach the disconnect callback field", "sql": "SELECT COUNT(*) = 2 AND SUM(t.name IN ('OHOS::CameraStandard::HCameraDevice::DeviceEjectCallBack', 'OHOS::CameraStandard::HCameraDevice::DeviceFaultCallBack')) = 2 FROM call_edges e JOIN call_sites s ON s.id = e.call_site_id JOIN functions t ON t.id = e.callee_fn_id JOIN files p ON p.id = s.file_id WHERE p.path LIKE '%device_protection_ability_connection.cpp' AND s.line = 41 AND e.resolution = 'indirect'", "cmp": "exact", "value": 1} ] }, diff --git a/tests/fixtures/cpp_container_lookup/main.cpp b/tests/fixtures/cpp_container_lookup/main.cpp index fc3186d8..f13e0c16 100644 --- a/tests/fixtures/cpp_container_lookup/main.cpp +++ b/tests/fixtures/cpp_container_lookup/main.cpp @@ -294,12 +294,14 @@ void iterator_write() { callbacks.at(0)(); } +enum DispatchKey : unsigned char { Captured, Forwarded }; + void unordered_dispatch(Callback captured, Callback forwarded) { - std::unordered_map> callbacks = { - {0, [captured](Callback value) { value(); return captured; }}, - {1, [](Callback value) { value(); return beta; }}, + std::unordered_map> callbacks = { + {DispatchKey::Captured, [captured](Callback value) { value(); return captured; }}, + {DispatchKey::Forwarded, [](Callback value) { value(); return beta; }}, }; - auto iter = callbacks.find(0); + auto iter = callbacks.find(DispatchKey::Captured); Callback result = iter->second(forwarded); result(); } diff --git a/tests/fixtures/cpp_nested_containers/container_conversions.cpp b/tests/fixtures/cpp_nested_containers/container_conversions.cpp new file mode 100644 index 00000000..be6f2939 --- /dev/null +++ b/tests/fixtures/cpp_nested_containers/container_conversions.cpp @@ -0,0 +1,150 @@ +#include "nested_containers.h" + +struct FloatingKey { + FloatingKey(double); +}; + +void map_numeric_key_initializer() { + std::map callbacks{{1, alpha}}; + callbacks.at(1)(); +} + +void map_numeric_key_insert() { + std::map callbacks; + callbacks.insert({1, alpha}); + callbacks.at(1)(); +} + +struct NonDefaultKey { + NonDefaultKey(int); + NonDefaultKey(int, Callback); +}; + +void empty_brace_with_nondefault_key() { + std::map callbacks; + callbacks.insert({{1, unrelated}, {}}); + callbacks.at(1)(); +} + +using Inner = std::vector; +struct DerivedCallbacks : Inner {}; +struct ConvertsToCallbacks { + operator Inner() const; +}; + +void inner_container_conversions(DerivedCallbacks derived, ConvertsToCallbacks converted) { + std::vector outer{{alpha}, derived, converted}; + outer[0][0](); +} + +#define EXPLICIT_SLOT operator[] +void explicit_subscript_macro() { + std::vector outer{{alpha}}; + outer.EXPLICIT_SLOT(0)[0](); +} + +void move_inner_callbacks() { + Inner first{alpha}; + Inner second{beta}; + std::vector outer; + outer.push_back(std::move(first)); + outer.push_back(std::forward(second)); + outer[0][0](); +} + +void copy_list_with_allocator() { + using Callbacks = std::list; + Callbacks inner{alpha}; + std::vector outer; + outer.push_back({inner, std::allocator{}}); + outer[0].front()(); +} + +void copy_map_with_allocator() { + using Callbacks = std::map; + Callbacks inner{{1, alpha}}; + std::vector outer; + outer.push_back({inner, std::allocator>{}}); + outer[0].at(1)(); +} + +void int_callback(int) {} +void pointer_callback(int*) {} +void const_pointer_callback(const int*) {} + +void copy_callback_parameter_cv() { + std::vector inner{int_callback}; + std::vector> outer; + outer.push_back(inner); + outer[0][0](0); +} + +struct PointerParameters { + std::vector> callbacks; + std::vector> const_callbacks; +}; + +void copy_callback_pointer_parameter_cv() { + PointerParameters values; + values.callbacks.push_back({pointer_callback}); + values.const_callbacks.push_back({const_pointer_callback}); + values.callbacks[0][0](nullptr); +} + +struct TagKey { int ident; }; +enum class EnumTagKey { First }; + +void map_pair_struct_key() { + std::pair key{TagKey{1}, unrelated}; + std::map, Callback> callbacks; + callbacks.insert({key, {}}); + callbacks.at(key)(); +} + +void map_make_pair_enum_key() { + std::map, Callback> callbacks; + callbacks.insert({std::make_pair(EnumTagKey::First, unrelated), {}}); + callbacks.at({EnumTagKey::First, nullptr})(); +} + +void map_nested_pair_key() { + using InnerKey = std::pair; + using Key = std::pair; + Key key{{1, 2}, unrelated}; + std::map callbacks; + callbacks.insert({key, {}}); + callbacks.at(key)(); +} + +void map_pair_container_key() { + using Key = std::pair; + Key key{{unrelated}, {unrelated}}; + std::map callbacks; + callbacks.insert({key, {}}); + callbacks.at(key)[0](); +} + +void map_pair_key_entries() { + using Key = std::pair; + std::pair first{{TagKey{1}, unrelated}, alpha}; + std::map callbacks; + callbacks.insert({first, std::make_pair(Key{TagKey{2}, unrelated}, beta)}); + callbacks.at({TagKey{1}, nullptr})(); +} + +void map_aggregate_key_allocator_copy() { + Inner inner{alpha}; + std::map callbacks; + callbacks.insert({{unrelated, {unrelated}}, {inner, {}}}); + callbacks.at({unrelated, {}})[0](); +} + +struct WrapperKey { + WrapperKey(Callback); +}; + +void map_class_key_from_callback() { + std::map callbacks; + callbacks.insert({unrelated, alpha}); + callbacks.at(unrelated)(); +} diff --git a/tests/fixtures/cpp_nested_containers/main.cpp b/tests/fixtures/cpp_nested_containers/main.cpp new file mode 100644 index 00000000..7856599b --- /dev/null +++ b/tests/fixtures/cpp_nested_containers/main.cpp @@ -0,0 +1,1053 @@ +#include "nested_containers.h" + +using Inner = std::vector; + +void alpha() {} +void beta() {} +void unrelated() {} +void Handler::run() {} +void OtherHandler::run() {} + +void vector_direct(unsigned i, unsigned j) { + std::vector> nested; + std::vector inner; + inner.push_back(alpha); + nested.push_back(inner); + nested[i][j](); +} + +void vector_braced_insertion(unsigned i, unsigned j) { + std::vector> nested; + nested.push_back({alpha}); + nested[i][j](); +} + +void vector_emplace(unsigned i, unsigned j) { + std::vector> nested; + std::vector inner; + inner.push_back(alpha); + nested.emplace_back(inner); + nested[i][j](); +} + +void vector_braced_multi_emplace(unsigned i, unsigned j) { + std::vector> nested; + nested.emplace_back(std::initializer_list{alpha, beta}); + nested[i][j](); +} + +void vector_braced_multi_push(unsigned i, unsigned j) { + std::vector> nested; + nested.push_back({alpha, beta}); + nested[i][j](); +} + +void vector_map_push_braced(unsigned i) { + std::vector> nested; + nested.push_back({{1, alpha}}); + nested[i][1](); +} + +void vector_map_push_multi(unsigned i) { + std::vector> nested; + nested.push_back({{1, alpha}, {2, beta}}); + nested[i][1](); +} + +void vector_braced_range() { + std::vector> nested = {{alpha}, {beta}}; + for (auto &slot : nested) { + for (Callback callback : slot) { + callback(); + } + } +} + +void vector_named_range() { + std::vector> nested; + std::vector inner; + inner.push_back(alpha); + nested.push_back(inner); + for (auto &slot : nested) { + for (Callback callback : slot) { + callback(); + } + } +} + +void vector_field_range() { + Holder holder; + std::vector inner; + inner.push_back(alpha); + holder.slots.push_back(inner); + for (auto &slot : holder.slots) { + for (Callback callback : slot) { + callback(); + } + } +} + +void vector_isolation() { + std::vector> left = {{alpha}}; + std::vector> right = {{unrelated}}; + for (auto &slot : left) { + for (Callback callback : slot) { + callback(); + } + } +} + +void pointer_range() { + Handler handler; + OtherHandler other; + std::vector> nested; + std::vector inner; + inner.push_back(&handler); + nested.push_back(inner); + std::vector other_inner; + other_inner.push_back(&other); + std::vector> others; + others.push_back(other_inner); + for (auto &slot : nested) { + for (Handler *item : slot) { + item->run(); + } + } +} + +void map_map_subscript(unsigned i, unsigned j) { + std::map> nested = {{0, {{1, alpha}, {2, beta}}}}; + nested[i][j](); +} + +void map_vector_subscript(unsigned i, unsigned j) { + std::map> nested = {{0, {alpha, beta}}}; + nested[i][j](); +} + +void vector_map_range() { + std::vector> nested = {{{1, alpha}}, {{2, beta}}}; + for (auto &entry : nested) { + entry[1](); + } +} + + + +void map_insert_single_pair(unsigned i, unsigned j) { + std::map> nested; + nested.insert({1, {alpha, beta}}); + nested[i][j](); +} + +void vector_insert_ambiguous(unsigned i) { + std::vector> nested; + nested.insert(nested.end(), {{1, alpha}, {2, beta}}); + nested[i][1](); +} + +void vector_descendant_copy(unsigned i, unsigned j, unsigned k) { + std::vector>> outer; + std::vector> middle = {{alpha}}; + outer.push_back(middle); + outer[i][j][k](); +} + +void vector_one_element_list(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer = {inner}; + outer[i][j](); +} + +void typed_reference_range() { + std::vector> outer = {{alpha}}; + for (std::vector &inner : outer) { + for (Callback callback : inner) { + callback(); + } + } +} + +void by_value_range_isolation() { + std::vector> outer = {{alpha}}; + for (auto inner : outer) { + inner.push_back(beta); + } + outer[0][0](); +} + +#define OUTER_INDEX [0] +void nested_ignored_bracket() { + std::vector> outer = {{alpha}}; + outer OUTER_INDEX [0](); +} + +void vector_triple_braced(unsigned i, unsigned j) { + std::vector> nested = {{{alpha}}}; + nested[i][j](); +} + +void vector_named_inner_braced_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer; + outer.push_back({inner}); + outer[i][j](); +} + +void map_named_pair_insert(unsigned i, unsigned j) { + std::pair> pair; + pair.second.push_back(alpha); + std::map> nested; + nested.insert(pair); + nested[i][j](); +} + +void map_without_subscript_model(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::map> nested; + nested.insert({0, inner}); + nested[i][j](); +} + +void map_inner_without_initializer() { + std::map> nested; + nested.insert({0, {alpha}}); + nested[0][0](); +} + +void unevaluated_nested(unsigned i) { + std::vector> nested = {{alpha}}; + (void)sizeof(nested[i][0]); +} + +#define SLOT slots +void ignored_range_field_subscript() { + Holder holder; + holder.slots.push_back({alpha}); + for (Callback callback : holder.SLOT[0]) { + callback(); + } +} + +void map_pair_key_insert(unsigned i, unsigned j) { + std::map, std::vector> nested; + nested.insert({{1, 2}, {alpha, beta}}); + nested[std::pair{1, 2}][j](); +} + +void map_pair_braced_insert(unsigned i, unsigned j) { + std::pair> pair{1u, {alpha, beta}}; + std::map> nested; + nested.insert(pair); + nested[i][j](); +} + +void map_pair_named_insert(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::pair> pair{1L, inner}; + std::map> nested; + nested.insert(pair); + nested[i][j](); +} + +void vector_allocator_braced_push(unsigned i, unsigned j) { + std::vector> nested; + nested.push_back({{alpha, beta}, {}}); + nested[i][j](); +} + +void vector_typed_inner_brace(unsigned i, unsigned j) { + std::vector> nested = { + std::vector{alpha, beta}, + }; + nested[i][j](); +} + +#define METHOD push_back +void ignored_method_macro() { + std::vector callbacks; + callbacks.METHOD(alpha); + callbacks[0](); +} + +void map_insert_allocator(unsigned i, unsigned j) { + std::map> nested; + nested.insert({0, {{alpha, beta}, {}}}); + nested[i][j](); +} + +void map_callback_key_insert() { + std::map> nested; + nested.insert({{alpha, {beta}}, {alpha, {beta}}}); + nested[alpha][0](); +} + +void map_pair_braced_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::pair> pair{1L, {inner}}; + std::map> nested; + nested.insert(pair); + nested[i][j](); +} + +void map_pair_typed_brace(unsigned i, unsigned j) { + std::pair> pair{ + 1LL, std::vector{alpha, beta}}; + std::map> nested; + nested.insert(pair); + nested[i][j](); +} + +#define INNER std::vector +void ignored_typed_insert() { + std::vector> outer; + outer.push_back(INNER{alpha}); + outer[0][0](); +} + +#define PAYLOAD inner +void ignored_named_payload() { + std::vector inner; + inner.push_back(alpha); + std::vector> outer; + outer.push_back({PAYLOAD}); + outer[0][0](); +} + +void alias_descendant_copy(unsigned i, unsigned j, unsigned k) { + std::vector middle = {{alpha}}; + std::vector>> outer; + outer.push_back(middle); + outer[i][j][k](); +} + +void vector_typed_brace_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer = {std::vector{inner}}; + outer[i][j](); +} + +void vector_nested_allocator(unsigned i, unsigned j) { + std::vector> outer{{{alpha, beta}, {beta, alpha}}, {}}; + outer[i][j](); +} + +void map_pair_key_entry(unsigned i, unsigned j) { + std::map, std::vector> nested; + nested.insert({{1, unrelated}, {alpha, beta}}); + nested[std::pair{1, unrelated}][j](); +} + +void vector_explicit_inner_allocator(unsigned i, unsigned j) { + std::vector>> outer; + std::vector> inner; + inner.push_back(alpha); + outer.push_back(inner); + outer[i][j](); +} + +void vector_nested_allocator_mixed(unsigned i, unsigned j) { + std::vector> outer = {{{alpha, beta}, {}}, {beta}}; + outer[i][j](); +} + +void map_callback_pair_key_entry() { + std::map, std::vector> nested; + nested.insert({{unrelated, unrelated}, {alpha, beta}}); + nested[std::pair{unrelated, unrelated}][0](); +} + +void map_class_key_insert(unsigned i, unsigned j) { + std::map> nested; + nested.insert({1, {alpha, beta}}); + nested[NumberKey(1)][j](); +} + +void custom_entry_insert(unsigned i) { + app::Custom> custom; + custom.insert({0, {alpha, beta}}); + custom[i][0](); +} + +void vector_nested_ordinary_constructor(unsigned i, unsigned j) { + std::vector> outer{{alpha}, {3, nullptr}}; + outer[i][j](); +} + +void ignored_nested_field_bracket() { + Holder holder; + holder.slots.push_back({alpha}); + holder.SLOT[0][0](); +} + +void map_vector_pair_key_entry() { + using V = std::vector; + std::map, V> nested; + nested.insert({{{unrelated}, {unrelated}}, {{alpha}, {beta}}}); + nested[std::pair{{unrelated}, {unrelated}}][0](); +} + +void map_typed_mapped_entry(unsigned i) { + std::map> nested; + nested.insert({{1, std::vector{alpha, beta}}}); + nested[1][i](); +} + +void vector_braced_copy_allocator(unsigned i, unsigned j) { + std::vector source; + source.push_back(alpha); + std::vector>> outer; + outer.push_back({source}); + outer[i][j](); +} + +void vector_mixed_allocator_copy(unsigned i, unsigned j) { + std::vector> middle; + middle.push_back(alpha); + std::vector> outer; + outer.push_back(middle); + outer[i][j](); +} + +void vector_at_chain(unsigned i) { + std::vector> outer = {{alpha}, {beta}}; + outer.at(i)[0](); +} + +void map_at_chain(unsigned i) { + std::map> nested = {{0, {alpha, beta}}}; + nested.at(0)[i](); +} + +void vector_double_braced_push(unsigned i, unsigned j) { + std::vector> nested; + nested.push_back({{alpha}}); + nested[i][j](); +} + +void vector_braced_named_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer = {{inner}}; + outer[i][j](); +} + +void map_braced_named_insert(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::map> nested; + nested.insert({1, {inner}}); + nested[i][j](); +} + +void map_initializer_named(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::map> nested = {{1, {inner}}}; + nested[i][j](); +} + +void map_typed_pair_compound_insert(unsigned i) { + std::map> nested; + nested.insert(std::pair>{1, {alpha, beta}}); + nested[1][i](); +} + +void reference_alias_range(unsigned i) { + using VecRef = std::vector &; + std::vector> outer = {{alpha}}; + for (VecRef slot : outer) { + slot[i](); + for (Callback callback : slot) { + callback(); + } + } +} + +#define AT_METHOD at +void ignored_accessor_macro(unsigned i) { + std::vector> outer = {{alpha}}; + outer.AT_METHOD(0)[i](); +} + +void ignored_accessor_range() { + std::vector> outer = {{alpha}}; + for (Callback callback : outer.AT_METHOD(0)) { + callback(); + } +} + +void ignored_range_bracket() { + std::vector> outer = {{alpha}}; + for (Callback callback : outer OUTER_INDEX) { + callback(); + } +} + +void unevaluated_at_chain(unsigned i) { + std::vector> outer = {{alpha}}; + (void)sizeof(outer.at(i)[0]); +} + +void map_pair_compound_entry_list_insert(unsigned i) { + std::map> nested; + nested.insert({std::pair>{1, {alpha}}}); + nested[1][i](); +} + +using CallbackKey = Callback; +void map_callback_alias_key_multi_insert() { + std::map> nested; + nested.insert({{alpha, {beta}}, {alpha, {beta}}}); + nested[alpha][0](); +} + +void ignored_nested_accessor_macro(unsigned i) { + std::vector> outer = {{alpha}}; + outer[i].AT_METHOD(0)(); +} + +void ignored_accessor_assignment() { + std::vector> outer(1); + outer[0].AT_METHOD(0) = alpha; + outer[0][0](); +} + +void map_const_key_insert(unsigned i) { + std::map> nested; + nested.insert({1, {alpha}}); + nested[1][i](); +} + +void map_allocator_entry_list(unsigned i, unsigned j) { + std::map> nested = { + {{1, {alpha}}, {2, {beta}}}, {}}; + nested[i][j](); +} + +void map_aggregate_key_multi_insert() { + std::map> nested; + nested.insert({{{unrelated, {}}, {alpha}}, {{unrelated, {}}, {beta}}}); + nested[CallbackKey2{unrelated, {}}][0](); +} + +void map_typed_pair_initializer(unsigned i) { + std::map> nested = { + std::pair>{1, {alpha}}}; + nested[1][i](); +} + +void vector_map_typed_pair_initializer(unsigned i) { + std::vector>> outer = { + {std::pair>{1, {alpha}}}}; + outer[0][1][i](); +} + +void map_allocator_aggregate_key(unsigned i) { + std::map> nested = { + {{{unrelated, {}}, {alpha}}, {{unrelated, {}}, {beta}}}, {}}; + nested[CallbackKey2{unrelated, {}}][i](); +} + +void map_mixed_pair_insert(unsigned i) { + std::map nested; + std::pair named{2, {beta}}; + nested.insert({{1, {alpha}}, named}); + nested[1][i](); + nested[2][i](); +} + +void map_three_entry_named_insert() { + std::map> nested; + std::pair> trailing{ + CallbackKey2{unrelated, {}}, {}}; + nested.insert({{{unrelated, {}}, {alpha}}, {{unrelated, {}}, {beta}}, trailing}); + nested[CallbackKey2{unrelated, {}}][0](); +} + + +void unevaluated_chained_accessor(unsigned i) { + std::vector>> outer = {{{alpha}}}; + (void)sizeof(outer[0].at(i)[0]); +} + +using CVec = const std::vector; +using CPair = const std::pair>; + +void map_insert_inner_allocator_one(unsigned i, unsigned j) { + std::map> nested; + nested.insert({1, {{alpha}, {}}}); + nested[i][j](); +} + +void map_insert_triple_single(unsigned i, unsigned j, unsigned k) { + std::map>> nested; + nested.insert({1, {{alpha}, {beta}}}); + nested[i][j][k](); +} + +void map_pair_key_map_single(unsigned i, unsigned j) { + std::map, std::map> nested; + nested.insert({{1, 2}, {{3, alpha}, {4, beta}}}); + nested[std::pair{1, 2}][i](); +} + +void vector_position_named_inner(unsigned i, unsigned j) { + std::vector> outer; + std::vector first; + std::vector second; + first.push_back(alpha); + second.push_back(beta); + outer.insert(outer.end(), {first, second}); + outer[i][j](); +} + +void vector_position_inner_lists(unsigned i, unsigned j) { + std::vector> outer; + outer.insert(outer.end(), {{alpha, beta}, {beta}}); + outer[i][j](); +} + +void vector_const_alias_typed_inner(unsigned i, unsigned j) { + std::vector> outer; + outer.push_back(CVec{alpha}); + outer[i][j](); +} + +void map_const_pair_alias_insert(unsigned i) { + std::map> nested; + nested.insert(CPair{1, {alpha}}); + nested[1][i](); +} + +void map_initializer_mixed_named(unsigned i) { + std::pair named{2, {beta}}; + std::map nested = {{1, {alpha}}, named}; + nested[1][i](); + nested[2][i](); +} + +void map_initializer_mixed_make_pair(unsigned i) { + std::map nested = { + {1, {alpha}}, std::make_pair(2, CallbackVecAlt{beta})}; + nested[1][i](); + nested[2][i](); +} + +void map_insert_named_first(unsigned i) { + std::map nested; + std::pair first; + first.second.push_back(alpha); + CallbackVecAlt second; + second.push_back(beta); + nested.insert({first, {2, second}}); + nested[1][i](); + nested[2][i](); +} + +void map_insert_make_pair_first(unsigned i) { + std::map nested; + nested.insert({std::make_pair(1, CallbackVecAlt{alpha}), {2, {beta}}}); + nested[1][i](); + nested[2][i](); +} + +void map_aggregate_key_single_pair() { + std::map> nested; + nested.insert({{unrelated, {alpha}}, {beta, beta}}); + nested[CallbackKey2{unrelated, {}}][0](); +} + +std::vector make_callbacks(); + +using CCallbackKey = const Callback; +void map_const_callback_alias_key() { + std::map> nested; + nested.insert({{alpha, {beta}}, {alpha, {beta}}}); + nested[alpha][0](); +} + +void map_pair_empty_key_insert(unsigned i) { + std::map, std::vector> nested; + nested.insert({{}, {alpha}}); + nested[std::pair{}][i](); +} + +void map_pair_empty_key_initializer(unsigned i) { + std::map, std::vector> nested = { + {{}, {alpha}}, {{1, 2}, {beta}}}; + nested[std::pair{}][i](); + nested[std::pair{1, 2}][i](); +} + +void map_direct_typed_pair_non_nested(unsigned i) { + std::map nested; + nested.insert(std::pair{1, alpha}); + nested[1](); +} + +void map_single_unmodeled_mapped() { + std::map> nested; + nested.insert({{unrelated, {alpha}}, make_callbacks()}); + nested[CallbackKey2{unrelated, {}}][0](); +} + +void map_pair_key_callback_non_nested(unsigned i) { + std::map, Callback> nested; + nested.insert({{1, 2}, alpha}); + nested[std::pair{1, 2}](); +} + +void map_pair_callback_key_non_nested() { + std::map, Callback> nested; + nested.insert({{1, beta}, alpha}); + nested[std::pair{1, beta}](); +} + +void map_named_pair_key_non_nested() { + std::pair key{1, 2}; + std::map, Callback> nested; + nested.insert({key, alpha}); + nested[std::pair{1, 2}](); +} + +void map_make_pair_key_non_nested() { + std::map, Callback> nested; + nested.insert({std::make_pair(1, 2), alpha}); + nested[std::pair{1, 2}](); +} + +void map_braced_mapped_non_nested() { + std::map, Callback> nested; + nested.insert({{1, 2}, {alpha}}); + nested[std::pair{1, 2}](); +} + +std::pair make_callback_entry(); + +void map_insert_braced_then_unmodeled() { + std::map nested; + nested.insert({{1, alpha}, make_callback_entry()}); + nested[1](); +} + +void map_insert_unmodeled_then_braced() { + std::map nested; + nested.insert({make_callback_entry(), {2, alpha}}); + nested[2](); +} + +void pair_container_field_copy(unsigned i) { + std::pair src{1, {alpha}}; + std::pair dst(src); + std::map nested; + nested.insert(dst); + nested[1L][i](); +} + +void pair_container_field_assignment(unsigned i) { + std::pair src{1, {alpha}}; + std::pair dst; + dst = src; + std::map nested; + nested.insert(dst); + nested[1L][i](); +} + +void map_empty_inner_brace_without_initializer(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::map> nested = {{1, {}}, {2, inner}}; + nested[2][j](); +} + +void map_initializer_default_entry() { + std::map nested = {{1, alpha}, {}, {2, beta}}; + nested[1](); + nested[2](); +} + +std::pair get_callback_pair(); + +void map_initializer_unmodeled_pair() { + std::map nested = {{1, alpha}, get_callback_pair()}; + nested[1](); +} + +void map_copy_list_pair_key() { + std::pair key{1, 2}; + std::map, Callback> nested = {{{key}, alpha}}; + nested[std::pair{1, 2}](); +} + +void vector_allocator_extended_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer; + outer.push_back({inner, std::allocator{}}); + outer[i][j](); +} + +void vector_empty_map_without_initializer(unsigned i) { + std::map populated; + populated.insert({1, alpha}); + std::vector> outer{{}, populated}; + outer[i][1](); +} + +#define IDX [0] +void ignored_receiver_chain_macro() { + std::vector holders; + Holder holder; + holders.push_back(&holder); + holder.slots.push_back({alpha}); + holders IDX ->slots[0][0](); +} + +void ignored_accessor_receiver_chain_macro() { + std::vector holders; + Holder holder; + holders.push_back(&holder); + holder.slots.push_back({alpha}); + holders.AT_METHOD(0)->slots[0][0](); +} + +void ignored_parenthesized_receiver_chain_macro() { + std::vector holders; + Holder holder; + holders.push_back(&holder); + holder.slots.push_back({alpha}); + (holders IDX)->slots[0][0](); +} + +void map_entry_conversion() { + std::map nested = {{1, alpha}, ConvertibleEntry{}}; + nested[1](); +} + +std::vector make_inner(); + +void vector_returned_inner(unsigned i, unsigned j) { + std::vector> outer{make_inner(), {beta}}; + outer[i][j](); +} + +std::pair, std::vector> make_nested_entry(); + +void map_insert_braced_then_pair_return(unsigned i) { + std::map, std::vector> nested; + nested.insert({{{1, 2}, {alpha}}, make_nested_entry()}); + nested[std::pair{1, 2}][i](); +} + +void vector_initializer_allocator_copy(unsigned i, unsigned j) { + std::map inner; + inner.insert({1, alpha}); + std::vector> outer{{inner, {}}, {{2, beta}}}; + outer[i][j](); +} + +void vector_parenthesized_typed_inner(unsigned i, unsigned j) { + std::vector> outer{ + (std::vector{beta}), {alpha}}; + outer[i][j](); +} + +void map_converting_pair_key() { + std::pair key{1, 2}; + std::map, Callback> nested; + nested.insert({{key}, alpha}); + nested[std::pair{1, 2}](); +} + +void map_convertible_mapped_value() { + ConvertibleCallback value; + std::map nested = {{1, alpha}, std::make_pair(2L, value)}; + nested[1L](); +} + +void map_single_pair_empty_mapped() { + std::map, Callback> nested; + nested.insert({{1, alpha}, {}}); + nested[std::pair{1, alpha}](); +} + +void map_initializer_trailing_empty(unsigned i) { + std::map nested{{1, alpha}, {}}; + nested[1](); +} + +void map_initializer_trailing_empty_nested(unsigned i, unsigned j) { + std::map> nested{{1, {alpha}}, {}}; + nested[1][j](); +} + +void vector_braced_typed_temporary_copy(unsigned i, unsigned j) { + std::vector> outer; + outer.push_back({std::vector{alpha}}); + outer[i][j](); +} + +void map_insert_empty_then_make_pair() { + std::map nested; + nested.insert({{}, std::make_pair(1, alpha)}); + nested[1](); +} + +void vector_callback_param_spelling(unsigned i) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer; + outer.push_back(inner); + outer[i][0](); +} + +void map_initializer_aggregate_trailing_empty() { + std::map nested = {{{1, 2}, alpha}, {}}; + nested[Key{1, 2}](); +} + +void map_initializer_aggregate_trailing_empty_nested() { + std::map> nested = {{{1, 2}, {alpha}}, {}}; + nested[Key{1, 2}][0](); +} + +void map_insert_inner_call_aggregate_key(unsigned i) { + std::map> nested; + nested.insert({{{1, 2}, {alpha}}, {{3, 4}, make_inner()}}); + nested[Key{1, 2}][i](); +} + +void vector_braced_typed_named_copy(unsigned i, unsigned j) { + std::vector inner; + inner.push_back(alpha); + std::vector> outer; + outer.push_back({std::vector{inner}}); + outer[i][j](); +} + +void vector_braced_typed_allocator_copy(unsigned i, unsigned j) { + std::vector> outer; + outer.push_back({std::vector{alpha}, {}}); + outer[i][j](); +} + +void vector_braced_typed_temporary_initializer(unsigned i, unsigned j) { + std::vector> outer = { + {std::vector{alpha}}}; + outer[i][j](); +} + +void map_pair_compound_key() { + std::map, Callback> nested = { + {{std::pair{1, 2}}, alpha}}; + nested[std::pair{1, 2}](); +} + +void map_three_level_single_pair(unsigned i) { + std::map, std::vector>> nested; + nested.insert({{1, 2}, {{3, nullptr}, {{alpha}}}}); + nested[std::pair{1, 2}][0][i](); +} + +void map_insert_aggregate_key_empty_mapped() { + std::map nested; + nested.insert({{1, unrelated}, {}}); + nested[AggregateKey{1, nullptr}](); +} + +void map_insert_pair_key_integer_variable() { + int k = 1; + std::map, Callback> nested; + nested.insert({{k, unrelated}, {}}); + nested[std::pair{1, nullptr}](); +} + +void map_parenthesized_pair_compound(unsigned i) { + std::map> nested = { + (std::pair>{1, {alpha}})}; + nested[1][i](); +} + +void map_insert_parenthesized_pair_compound(unsigned i) { + std::map> nested; + nested.insert((std::pair>{1, {alpha}})); + nested[1][i](); +} + +void vector_initializer_list_temporary(unsigned i, unsigned j) { + std::vector> outer = { + std::initializer_list{alpha, beta}}; + outer[i][j](); +} + +void map_initializer_list_temporary(unsigned i) { + std::map> nested = { + {1, std::initializer_list{alpha, beta}}}; + nested[1][i](); +} + +void map_insert_initializer_list_temporary(unsigned i) { + std::map> nested; + nested.insert({1, std::initializer_list{alpha, beta}}); + nested[1][i](); +} + +void ignored_range_pointer_macro() { + RawHolder holder; + holder.items[0] = alpha; + std::vector holders; + holders.push_back(&holder); + for (Callback callback : (*holders IDX).items) { + callback(); + } +} + +void map_pair_key_as_entry_non_nested() { + std::pair key{1, unrelated}; + std::map, Callback> nested; + nested.insert({key, {}}); + nested[std::pair{1, unrelated}](); +} + +void map_make_pair_key_as_entry_non_nested() { + std::map, Callback> nested; + nested.insert({std::make_pair(1, unrelated), {}}); + nested[std::pair{1, unrelated}](); +} + +void map_insert_widening_keys() { + std::pair first{1, alpha}; + std::map callbacks; + callbacks.insert({first, std::make_pair(2, beta)}); + callbacks[1L](); +} + +void map_insert_converting_class_keys(unsigned i) { + using Values = std::vector>; + std::pair first{1, {alpha}}; + Values second{beta}; + std::map callbacks; + callbacks.insert({first, std::make_pair(2, second)}); + callbacks[NumberKey(1)][i](); +} + +void map_insert_qualified_callback_keys() { + Callback first = unrelated; + Callback second = alpha; + std::map callbacks; + callbacks.insert({std::make_pair(first, alpha), std::make_pair(second, beta)}); + callbacks[first](); +} + +void map_insert_qualified_pointer_keys(int *first, int *second) { + std::map callbacks; + callbacks.insert({std::make_pair(first, alpha), std::make_pair(second, beta)}); + callbacks[first](); +} diff --git a/tests/fixtures/cpp_nested_containers/nested_containers.h b/tests/fixtures/cpp_nested_containers/nested_containers.h new file mode 100644 index 00000000..91bba228 --- /dev/null +++ b/tests/fixtures/cpp_nested_containers/nested_containers.h @@ -0,0 +1,177 @@ +#pragma once + +namespace std { +template class initializer_list { + const T* first; + decltype(sizeof(0)) size; +}; + +template struct pair { + K first; + V second; +}; + +// The converting constructor and assignment make construction and assignment +// from pair to pair valid C++. +template struct pair { + long first; + V second; + pair(); + pair(long, V); + template pair(const pair &); + template pair &operator=(const pair &); +}; + +template pair make_pair(A, B); + +struct allocator_stub {}; + +template class allocator; +template class less {}; + +template, class Alloc = allocator>> +class map { +public: + struct iterator { + pair* operator->(); + pair& operator*(); + }; + map(); + map(initializer_list>); + map(initializer_list>, allocator_stub); + map(const map &, Alloc); + iterator find(K); + void insert(pair); + void insert(initializer_list>); + V& at(K); + V& operator[](K); +}; + +template class allocator { +public: + allocator(); + template allocator(U); +}; + +template> class list { +public: + list(initializer_list); + list(const list &, Alloc); + T& front(); +}; + +template T&& move(T&); +template T&& forward(T&); + +template> class vector { +public: + struct iterator { + T& operator*() const; + iterator& operator++(); + bool operator!=(const iterator&) const; + }; + vector(); + vector(unsigned); + vector(unsigned, const T&, allocator_stub = allocator_stub()); + vector(initializer_list, allocator_stub = allocator_stub()); + vector(const vector &, Allocator); + void push_back(T); + template void emplace_back(U); + iterator begin(); + iterator end(); + iterator insert(iterator, T); + iterator insert(iterator, initializer_list); + T& operator[](unsigned); + T& at(unsigned); +}; +} // namespace std + +using Callback = void (*)(); +using CallbackVecAlt = std::vector>; +// A distinct specialization no other fixture function populates, so a pair +// field copy across differing pair specializations is observable in isolation. +using CallbackVecPairCopy = std::vector>; + +void alpha(); +void beta(); +void unrelated(); + +struct Holder { + std::vector> slots; +}; + +struct Handler { + void run(); +}; + +struct OtherHandler { + void run(); +}; + +struct NumberKey { + NumberKey(int); +}; + +namespace std { +template struct pair { + NumberKey first; + V second; + pair(NumberKey, V); + template pair(const pair &); +}; + +template struct pair { + K const first; + V second; + pair(K, V); + template pair(const pair &); +}; + +template struct pair { + K const *first; + V second; + pair(K const *, V); + template pair(const pair &); +}; +} // namespace std + +namespace app { +struct Policy { + int value; +}; + +template class Custom { +public: + void insert(std::pair); + Value& operator[](int); +}; +} // namespace app + +static std::vector> shared_slots = {{alpha}}; + +struct CallbackKey2 { + Callback cb; + std::vector items; +}; + +struct ConvertibleEntry { + operator std::pair() const; +}; + +struct ConvertibleCallback { + operator Callback() const; +}; + +struct Key { + int a; + int b; +}; + +struct AggregateKey { + int a; + Callback cb; +}; + +struct RawHolder { + Callback items[1]; +}; diff --git a/tests/fixtures/cpp_nested_containers/read.cpp b/tests/fixtures/cpp_nested_containers/read.cpp new file mode 100644 index 00000000..16ee3867 --- /dev/null +++ b/tests/fixtures/cpp_nested_containers/read.cpp @@ -0,0 +1,14 @@ +#include "nested_containers.h" + +void read_slots() { + Holder holder; + for (auto &slot : holder.slots) { + for (Callback callback : slot) { + callback(); + } + } +} + +void use_shared_slots_read() { + shared_slots[0][0](); +} diff --git a/tests/fixtures/cpp_nested_containers/store.cpp b/tests/fixtures/cpp_nested_containers/store.cpp new file mode 100644 index 00000000..77a05d4c --- /dev/null +++ b/tests/fixtures/cpp_nested_containers/store.cpp @@ -0,0 +1,12 @@ +#include "nested_containers.h" + +void store_slots() { + Holder holder; + std::vector inner; + inner.push_back(alpha); + holder.slots.push_back(inner); +} + +void use_shared_slots_store() { + shared_slots[0][0](); +}