diff --git a/Cargo.toml b/Cargo.toml index 0a2c155..6531fc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ license = "MIT" edition = "2018" [dependencies] +indexmap = "1.0" rustpython-bytecode = { path = "../bytecode", version = "0.1.0" } rustpython-parser = { path = "../parser", version = "0.1.0" } num-complex = { version = "0.2", features = ["serde"] } diff --git a/src/lib.rs b/src/lib.rs index 5e844b2..de949be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,4 +8,4 @@ extern crate log; pub mod compile; pub mod error; -mod symboltable; +pub mod symboltable; diff --git a/src/symboltable.rs b/src/symboltable.rs index 5490bd0..9d4d677 100644 --- a/src/symboltable.rs +++ b/src/symboltable.rs @@ -8,12 +8,12 @@ Inspirational file: https://github.com/python/cpython/blob/master/Python/symtabl */ use crate::error::{CompileError, CompileErrorType}; +use indexmap::map::IndexMap; use rustpython_parser::ast; use rustpython_parser::location::Location; -use std::collections::HashMap; pub fn make_symbol_table(program: &ast::Program) -> Result { - let mut builder = SymbolTableBuilder::new(); + let mut builder: SymbolTableBuilder = Default::default(); builder.enter_scope(); builder.scan_program(program)?; assert_eq!(builder.scopes.len(), 1); @@ -26,7 +26,7 @@ pub fn make_symbol_table(program: &ast::Program) -> Result Result { - let mut builder = SymbolTableBuilder::new(); + let mut builder: SymbolTableBuilder = Default::default(); builder.enter_scope(); builder.scan_statements(statements)?; assert_eq!(builder.scopes.len(), 1); @@ -36,7 +36,7 @@ pub fn statements_to_symbol_table( Ok(symbol_table) } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum SymbolRole { Global, Nonlocal, @@ -45,9 +45,10 @@ pub enum SymbolRole { } /// Captures all symbols in the current scope, and has a list of subscopes in this scope. +#[derive(Clone)] pub struct SymbolScope { /// A set of symbols present on this scope level. - pub symbols: HashMap, + pub symbols: IndexMap, /// A list of subscopes in the order as found in the /// AST nodes. @@ -72,18 +73,20 @@ impl From for CompileError { type SymbolTableResult = Result<(), SymbolTableError>; impl SymbolScope { - pub fn new() -> Self { - SymbolScope { - symbols: HashMap::new(), - sub_scopes: vec![], - } - } - pub fn lookup(&self, name: &str) -> Option<&SymbolRole> { self.symbols.get(name) } } +impl Default for SymbolScope { + fn default() -> Self { + SymbolScope { + symbols: Default::default(), + sub_scopes: Default::default(), + } + } +} + impl std::fmt::Debug for SymbolScope { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( @@ -152,13 +155,15 @@ pub struct SymbolTableBuilder { pub scopes: Vec, } -impl SymbolTableBuilder { - pub fn new() -> Self { +impl Default for SymbolTableBuilder { + fn default() -> Self { SymbolTableBuilder { scopes: vec![] } } +} +impl SymbolTableBuilder { pub fn enter_scope(&mut self) { - let scope = SymbolScope::new(); + let scope = Default::default(); self.scopes.push(scope); }