Skip to content

Commit 2b90e82

Browse files
authored
Use rust idioms for accessing a Vec in codegen/src/compile.rs (RustPython#6326)
* Use rust idioms for accessing a `Vec` * clippy * Remove `unsafe`
1 parent f49c185 commit 2b90e82

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

crates/codegen/src/compile.rs

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -557,11 +557,9 @@ impl Compiler {
557557

558558
/// Get the SymbolTable for the current scope.
559559
fn current_symbol_table(&self) -> &SymbolTable {
560-
if self.symbol_table_stack.is_empty() {
561-
panic!("symbol_table_stack is empty! This is a compiler bug.");
562-
}
563-
let index = self.symbol_table_stack.len() - 1;
564-
&self.symbol_table_stack[index]
560+
self.symbol_table_stack
561+
.last()
562+
.expect("symbol_table_stack is empty! This is a compiler bug.")
565563
}
566564

567565
/// Get the index of a free variable.
@@ -626,9 +624,8 @@ impl Compiler {
626624
let table = current_table.sub_tables.remove(0);
627625

628626
// Push the next table onto the stack
629-
let last_idx = self.symbol_table_stack.len();
630627
self.symbol_table_stack.push(table);
631-
&self.symbol_table_stack[last_idx]
628+
self.current_symbol_table()
632629
}
633630

634631
/// Pop the current symbol table off the stack
@@ -657,12 +654,13 @@ impl Compiler {
657654
let source_path = self.source_file.name().to_owned();
658655

659656
// Lookup symbol table entry using key (_PySymtable_Lookup)
660-
let ste = if key < self.symbol_table_stack.len() {
661-
&self.symbol_table_stack[key]
662-
} else {
663-
return Err(self.error(CodegenErrorType::SyntaxError(
664-
"unknown symbol table entry".to_owned(),
665-
)));
657+
let ste = match self.symbol_table_stack.get(key) {
658+
Some(v) => v,
659+
None => {
660+
return Err(self.error(CodegenErrorType::SyntaxError(
661+
"unknown symbol table entry".to_owned(),
662+
)));
663+
}
666664
};
667665

668666
// Use varnames from symbol table (already collected in definition order)
@@ -1199,12 +1197,10 @@ impl Compiler {
11991197

12001198
// If not found and we're in TypeParams scope, try parent scope
12011199
let symbol = if symbol.is_none() && is_typeparams {
1202-
if self.symbol_table_stack.len() > 1 {
1203-
let parent_idx = self.symbol_table_stack.len() - 2;
1204-
self.symbol_table_stack[parent_idx].lookup(name.as_ref())
1205-
} else {
1206-
None
1207-
}
1200+
self.symbol_table_stack
1201+
.get(self.symbol_table_stack.len() - 2) // Try to get parent index
1202+
.expect("Symbol has no parent! This is a compiler bug.")
1203+
.lookup(name.as_ref())
12081204
} else {
12091205
symbol
12101206
};

0 commit comments

Comments
 (0)