MCPcopy Index your code
hub / github.com/RustPython/RustPython / fold_set_constants

Method fold_set_constants

crates/codegen/src/ir.rs:1238–1327  ·  view source on GitHub ↗

Fold constant set literals: LOAD_CONST* + BUILD_SET N → BUILD_SET 0 + LOAD_CONST (frozenset-as-tuple) + SET_UPDATE 1

(&mut self)

Source from the content-addressed store, hash-verified

1236 /// Fold constant set literals: LOAD_CONST* + BUILD_SET N →
1237 /// BUILD_SET 0 + LOAD_CONST (frozenset-as-tuple) + SET_UPDATE 1
1238 fn fold_set_constants(&mut self) {
1239 for block in &mut self.blocks {
1240 let mut i = 0;
1241 while i < block.instructions.len() {
1242 let instr = &block.instructions[i];
1243 let Some(Instruction::BuildSet { .. }) = instr.instr.real() else {
1244 i += 1;
1245 continue;
1246 };
1247
1248 let set_size = u32::from(instr.arg) as usize;
1249 if set_size < 3 || i < set_size {
1250 i += 1;
1251 continue;
1252 }
1253
1254 let start_idx = i - set_size;
1255 let mut elements = Vec::with_capacity(set_size);
1256 let mut all_const = true;
1257
1258 for j in start_idx..i {
1259 let load_instr = &block.instructions[j];
1260 match load_instr.instr.real() {
1261 Some(Instruction::LoadConst { .. }) => {
1262 let const_idx = u32::from(load_instr.arg) as usize;
1263 if let Some(constant) =
1264 self.metadata.consts.get_index(const_idx).cloned()
1265 {
1266 elements.push(constant);
1267 } else {
1268 all_const = false;
1269 break;
1270 }
1271 }
1272 Some(Instruction::LoadSmallInt { .. }) => {
1273 let value = u32::from(load_instr.arg) as i32;
1274 elements.push(ConstantData::Integer {
1275 value: BigInt::from(value),
1276 });
1277 }
1278 _ => {
1279 all_const = false;
1280 break;
1281 }
1282 }
1283 }
1284
1285 if !all_const {
1286 i += 1;
1287 continue;
1288 }
1289
1290 // Use FrozenSet constant (stored as Tuple for now)
1291 let const_data = ConstantData::Tuple { elements };
1292 let (const_idx, _) = self.metadata.consts.insert_full(const_data);
1293
1294 let folded_loc = block.instructions[i].location;
1295 let end_loc = block.instructions[i].end_location;

Callers 1

finalize_codeMethod · 0.80

Calls 5

newFunction · 0.85
get_indexMethod · 0.80
lenMethod · 0.45
realMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected