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

Method fold_list_constants

crates/codegen/src/ir.rs:1038–1130  ·  view source on GitHub ↗

Fold constant list literals: LOAD_CONST* + BUILD_LIST N → BUILD_LIST 0 + LOAD_CONST (tuple) + LIST_EXTEND 1

(&mut self)

Source from the content-addressed store, hash-verified

1036 /// Fold constant list literals: LOAD_CONST* + BUILD_LIST N →
1037 /// BUILD_LIST 0 + LOAD_CONST (tuple) + LIST_EXTEND 1
1038 fn fold_list_constants(&mut self) {
1039 for block in &mut self.blocks {
1040 let mut i = 0;
1041 while i < block.instructions.len() {
1042 let instr = &block.instructions[i];
1043 let Some(Instruction::BuildList { .. }) = instr.instr.real() else {
1044 i += 1;
1045 continue;
1046 };
1047
1048 let list_size = u32::from(instr.arg) as usize;
1049 if list_size == 0 || i < list_size {
1050 i += 1;
1051 continue;
1052 }
1053
1054 let start_idx = i - list_size;
1055 let mut elements = Vec::with_capacity(list_size);
1056 let mut all_const = true;
1057
1058 for j in start_idx..i {
1059 let load_instr = &block.instructions[j];
1060 match load_instr.instr.real() {
1061 Some(Instruction::LoadConst { .. }) => {
1062 let const_idx = u32::from(load_instr.arg) as usize;
1063 if let Some(constant) =
1064 self.metadata.consts.get_index(const_idx).cloned()
1065 {
1066 elements.push(constant);
1067 } else {
1068 all_const = false;
1069 break;
1070 }
1071 }
1072 Some(Instruction::LoadSmallInt { .. }) => {
1073 let value = u32::from(load_instr.arg) as i32;
1074 elements.push(ConstantData::Integer {
1075 value: BigInt::from(value),
1076 });
1077 }
1078 _ => {
1079 all_const = false;
1080 break;
1081 }
1082 }
1083 }
1084
1085 if !all_const || list_size < MIN_CONST_SEQUENCE_SIZE {
1086 i += 1;
1087 continue;
1088 }
1089
1090 let tuple_const = ConstantData::Tuple { elements };
1091 let (const_idx, _) = self.metadata.consts.insert_full(tuple_const);
1092
1093 let folded_loc = block.instructions[i].location;
1094 let end_loc = block.instructions[i].end_location;
1095 let eh = block.instructions[i].except_handler;

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