|
| 1 | +use cairo_lang_debug::DebugWithDb; |
| 2 | +use cairo_lang_semantic::corelib::unit_ty; |
| 3 | +use cairo_lang_semantic::expr::fmt::ExprFormatter; |
| 4 | +use cairo_lang_semantic::test_utils::{TestFunction, setup_test_function}; |
| 5 | +use cairo_lang_semantic::usage::MemberPath; |
| 6 | +use cairo_lang_semantic::{self as semantic, Expr, Statement, StatementId}; |
| 7 | +use cairo_lang_syntax::node::TypedStablePtr; |
| 8 | +use cairo_lang_test_utils::parse_test_file::TestRunnerResult; |
| 9 | +use cairo_lang_utils::ordered_hash_map::OrderedHashMap; |
| 10 | +use cairo_lang_utils::unordered_hash_set::UnorderedHashSet; |
| 11 | +use cairo_lang_utils::{Upcast, extract_matches}; |
| 12 | +use itertools::Itertools; |
| 13 | + |
| 14 | +use super::block_builder::{BlockBuilder, merge_block_builders}; |
| 15 | +use super::context::{LoweringContext, VarRequest}; |
| 16 | +use super::test_utils::{create_encapsulating_ctx, create_lowering_context}; |
| 17 | +use crate::VariableId; |
| 18 | +use crate::fmt::LoweredFormatter; |
| 19 | +use crate::test_utils::LoweringDatabaseForTesting; |
| 20 | + |
| 21 | +const N_LOWERING_VARS: usize = 100; |
| 22 | + |
| 23 | +cairo_lang_test_utils::test_file_test!( |
| 24 | + test_merge_block_builders, |
| 25 | + "src/lower/test_data", |
| 26 | + { |
| 27 | + merge_block_builders: "merge_block_builders", |
| 28 | + }, |
| 29 | + test_merge_block_builders |
| 30 | +); |
| 31 | + |
| 32 | +/// Tests the [merge_block_builders] function. |
| 33 | +/// |
| 34 | +/// Each test case has the following input sections: |
| 35 | +/// - `variables`: A comma-separated list of "var_name: type". |
| 36 | +/// - `block_definitions`: Defines the semantic to lowering map of each input block. |
| 37 | +/// |
| 38 | +/// For example: |
| 39 | +/// ```ignore |
| 40 | +/// ((x, 0),); |
| 41 | +/// ((x.a, 1), (y, 2)); |
| 42 | +/// ``` |
| 43 | +/// represents two blocks, where: |
| 44 | +/// * The first maps `x` to lowered variable 0. |
| 45 | +/// * The second maps `x.a` to lowered variable 1, and `y` to lowered variable 2. |
| 46 | +/// |
| 47 | +/// Note that `x` and `x.*` should not be specified together in one block. |
| 48 | +/// |
| 49 | +/// - `module_code`: Additional code for defining structs and helper functions. |
| 50 | +fn test_merge_block_builders( |
| 51 | + inputs: &OrderedHashMap<String, String>, |
| 52 | + _args: &OrderedHashMap<String, String>, |
| 53 | +) -> TestRunnerResult { |
| 54 | + let db = LoweringDatabaseForTesting::default(); |
| 55 | + // Create a function with the given variables as parameters and the given block definitions |
| 56 | + // as a dummy function body. |
| 57 | + // Note that the function body is not lowered at any point, and it is only used to parse the |
| 58 | + // semantic to lowering map. |
| 59 | + let test_function = setup_test_function( |
| 60 | + &db, |
| 61 | + &format!("fn foo ({}) {{ {} }}", &inputs["variables"], &inputs["block_definitions"]), |
| 62 | + "foo", |
| 63 | + inputs.get("module_code").unwrap_or(&"".into()), |
| 64 | + ) |
| 65 | + .unwrap(); |
| 66 | + |
| 67 | + let mut encapsulating_ctx = |
| 68 | + create_encapsulating_ctx(&db, test_function.function_id, &test_function.signature); |
| 69 | + |
| 70 | + let mut ctx = create_lowering_context( |
| 71 | + &db, |
| 72 | + test_function.function_id, |
| 73 | + &test_function.signature, |
| 74 | + &mut encapsulating_ctx, |
| 75 | + ); |
| 76 | + |
| 77 | + // Create dummy lowering variables. |
| 78 | + let dummy_location = ctx.get_location(test_function.signature.stable_ptr.untyped()); |
| 79 | + let lowering_vars: Vec<VariableId> = (0..N_LOWERING_VARS) |
| 80 | + .map(|_| ctx.new_var(VarRequest { ty: unit_ty(ctx.db), location: dummy_location })) |
| 81 | + .collect(); |
| 82 | + |
| 83 | + let expr_formatter = ExprFormatter { db: db.upcast(), function_id: test_function.function_id }; |
| 84 | + |
| 85 | + let input_blocks = create_block_builders(&mut ctx, &test_function, &lowering_vars); |
| 86 | + let input_blocks_str = |
| 87 | + input_blocks.iter().map(|b| format!("{:?}", b.debug(&expr_formatter))).join("\n"); |
| 88 | + |
| 89 | + // Invoke [merge_block_builders] on the input blocks. |
| 90 | + let merged_block = merge_block_builders(&mut ctx, input_blocks, dummy_location); |
| 91 | + |
| 92 | + let lowered_formatter = LoweredFormatter::new(db.upcast(), &ctx.variables.variables); |
| 93 | + let lowered_blocks = ctx.blocks.build().unwrap(); |
| 94 | + let lowered_str = lowered_blocks |
| 95 | + .iter() |
| 96 | + .map(|(block_id, block)| { |
| 97 | + format!( |
| 98 | + "{:?}:\n{:?}\n", |
| 99 | + block_id.debug(&lowered_formatter), |
| 100 | + block.debug(&lowered_formatter) |
| 101 | + ) |
| 102 | + }) |
| 103 | + .join(""); |
| 104 | + |
| 105 | + TestRunnerResult { |
| 106 | + outputs: OrderedHashMap::from([ |
| 107 | + ("input_blocks".into(), input_blocks_str), |
| 108 | + ("merged_block_builder".into(), format!("{:?}", merged_block.debug(&expr_formatter))), |
| 109 | + ("lowered".into(), lowered_str), |
| 110 | + ]), |
| 111 | + error: None, |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +/// Creates a block builder for each semantic "statement" in the function body. |
| 116 | +/// |
| 117 | +/// See [create_block_builder] for more details. |
| 118 | +fn create_block_builders( |
| 119 | + ctx: &mut LoweringContext<'_, '_>, |
| 120 | + test_function: &TestFunction, |
| 121 | + lowering_vars: &[VariableId], |
| 122 | +) -> Vec<BlockBuilder> { |
| 123 | + let expr = ctx.function_body.arenas.exprs[test_function.body].clone(); |
| 124 | + let block_expr = extract_matches!(expr, Expr::Block); |
| 125 | + |
| 126 | + block_expr |
| 127 | + .statements |
| 128 | + .iter() |
| 129 | + .map(|statement_id| create_block_builder(ctx, *statement_id, lowering_vars)) |
| 130 | + .collect() |
| 131 | +} |
| 132 | + |
| 133 | +/// Given a semantic "statement" of the form: |
| 134 | +/// `((member_path, lower_var_idx), ...)` |
| 135 | +/// creates a block builder with a semantic mapping that maps each member path to the corresponding |
| 136 | +/// given lowered variable. |
| 137 | +/// |
| 138 | +/// Assumption: if a certain semantic variable is mapped, all its children should not be mapped. |
| 139 | +/// |
| 140 | +/// Note that the statement is not a real statement - it is not lowered, and it is only used to |
| 141 | +/// define the semantic mapping. |
| 142 | +fn create_block_builder( |
| 143 | + ctx: &mut LoweringContext<'_, '_>, |
| 144 | + statement_id: StatementId, |
| 145 | + lowering_vars: &[VariableId], |
| 146 | +) -> BlockBuilder { |
| 147 | + let block_id = ctx.blocks.alloc_empty(); |
| 148 | + let mut block_builder = BlockBuilder::root(block_id); |
| 149 | + let mut visited_vars: UnorderedHashSet<semantic::VarId> = Default::default(); |
| 150 | + |
| 151 | + let statement_expr = |
| 152 | + extract_matches!(&ctx.function_body.arenas.statements[statement_id], Statement::Expr); |
| 153 | + let external_tuple = |
| 154 | + extract_matches!(&ctx.function_body.arenas.exprs[statement_expr.expr], Expr::Tuple); |
| 155 | + |
| 156 | + let expr_ids = external_tuple.items.clone(); |
| 157 | + for expr_id in expr_ids { |
| 158 | + let inner_tuple = extract_matches!(&ctx.function_body.arenas.exprs[expr_id], Expr::Tuple); |
| 159 | + let lower_var_idx: usize = (&extract_matches!( |
| 160 | + &ctx.function_body.arenas.exprs[inner_tuple.items[1]], |
| 161 | + Expr::Literal |
| 162 | + ) |
| 163 | + .value) |
| 164 | + .try_into() |
| 165 | + .unwrap(); |
| 166 | + |
| 167 | + match &ctx.function_body.arenas.exprs[inner_tuple.items[0]] { |
| 168 | + Expr::MemberAccess(member_access) => { |
| 169 | + let member_path: MemberPath = (member_access.member_path.as_ref().unwrap()).into(); |
| 170 | + let mut var = &member_path; |
| 171 | + while let MemberPath::Member { parent: v, .. } = var { |
| 172 | + var = v; |
| 173 | + } |
| 174 | + let var_id = extract_matches!(var, MemberPath::Var); |
| 175 | + |
| 176 | + if visited_vars.insert(*var_id) { |
| 177 | + block_builder.put_semantic(*var_id, lowering_vars[lower_var_idx]); |
| 178 | + } |
| 179 | + |
| 180 | + let location = ctx.get_location(member_access.stable_ptr.untyped()); |
| 181 | + block_builder.update_ref_raw( |
| 182 | + ctx, |
| 183 | + member_path, |
| 184 | + lowering_vars[lower_var_idx], |
| 185 | + location, |
| 186 | + ); |
| 187 | + // Remove the statements that were created as part of the `update_ref_raw` call. |
| 188 | + block_builder.statements.statements.clear(); |
| 189 | + } |
| 190 | + Expr::Var(var) => { |
| 191 | + if visited_vars.insert(var.var) { |
| 192 | + block_builder.put_semantic(var.var, lowering_vars[lower_var_idx]); |
| 193 | + } |
| 194 | + } |
| 195 | + expr => { |
| 196 | + panic!("Unexpected expression: {expr:?}"); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + block_builder |
| 202 | +} |
0 commit comments