@@ -1332,20 +1332,18 @@ impl BytecodeGenerator {
13321332 panic ! ( )
13331333 }
13341334
1335- // todo we need a map or something to map these to registers
1336- fn gen_variable (
1335+ fn lookup_variable_recursively (
13371336 & mut self ,
13381337 annotation_context : AnnotationContext ,
1339- pos : Position ,
1338+ pos : & Position ,
13401339 t : & Token ,
1341- ) -> u8 {
1342- // todo we assume it exists so return the map
1340+ ) -> Option < u8 > {
13431341 let result = self . codegen_context . chunks [ self . codegen_context . current_chunk_pointer ]
13441342 . variable_map
13451343 . get ( & t. as_identifier ( ) ) ;
13461344
13471345 if let Some ( v) = result {
1348- return * v ;
1346+ return Some ( * v ) ;
13491347 } else {
13501348 let reg = alloc_slot ! ( self ) ;
13511349 let mut counter = self . codegen_context . current_chunk_pointer ;
@@ -1363,16 +1361,29 @@ impl BytecodeGenerator {
13631361 } ,
13641362 pos. line as usize ,
13651363 ) ;
1366- return reg;
1364+ return Some ( reg) ;
13671365 }
13681366 if counter == 0 {
1369- break ;
1367+ return None ;
13701368 }
13711369 counter -= 1 ;
13721370 }
13731371 }
1372+ }
13741373
1375- panic ! ( "variable not found in any scope {:?}" , t)
1374+ // todo we need a map or something to map these to registers
1375+ fn gen_variable (
1376+ & mut self ,
1377+ annotation_context : AnnotationContext ,
1378+ pos : Position ,
1379+ t : & Token ,
1380+ ) -> u8 {
1381+ // todo we assume it exists so return the map
1382+ let res = self . lookup_variable_recursively ( annotation_context, & pos, t) ;
1383+ if res. is_some ( ) {
1384+ return res. unwrap ( ) ;
1385+ }
1386+ panic ! ( ) ;
13761387 }
13771388
13781389 fn get_variable (
@@ -1404,9 +1415,14 @@ impl BytecodeGenerator {
14041415
14051416 match value {
14061417 Some ( v) => {
1407- let location = self . visit ( annotation_context, & v) ;
1418+ let location = self . visit ( annotation_context. clone ( ) , & v) ;
14081419
1409- let var_location = alloc_perm_slot ! ( self ) ;
1420+ let existing_var = self . lookup_variable_recursively ( annotation_context, & pos, var) ;
1421+ let var_location = if existing_var. is_some ( ) {
1422+ existing_var. unwrap ( )
1423+ } else {
1424+ alloc_perm_slot ! ( self )
1425+ } ;
14101426
14111427 self . codegen_context . chunks [ self . codegen_context . current_chunk_pointer ]
14121428 . variable_map
0 commit comments