This commit is contained in:
numzero 2025-04-19 12:15:15 +03:00
parent 819d6ec3fc
commit b0e201fccb

View File

@ -1,4 +1,4 @@
use std::{cell::RefCell, collections::HashMap}; use std::cell::RefCell;
use crate::ast; use crate::ast;
@ -53,49 +53,57 @@ struct Call {
args: Vec<Expression>, args: Vec<Expression>,
} }
#[derive(Debug, Clone, Default)] mod scope {
struct Scope { use std::collections::HashMap;
locals: Vec<ast::Ident>,
upvalues: Vec<(ast::Ident, Ident)>,
scope: HashMap<ast::Ident, Ident>,
}
impl Scope { use super::Ident;
fn new_toplevel() -> Self { use crate::ast;
Self {
locals: vec!["_ENV".to_string()], #[derive(Debug, Clone, Default)]
upvalues: vec![], pub struct Scope {
scope: [("_ENV".to_string(), Ident::Local(0))] locals: Vec<ast::Ident>,
.into_iter() upvalues: Vec<(ast::Ident, Ident)>,
.collect(), scope: HashMap<ast::Ident, Ident>,
}
impl Scope {
pub fn new_toplevel() -> Self {
Self {
locals: vec!["_ENV".to_string()],
upvalues: vec![],
scope: [("_ENV".to_string(), Ident::Local(0))]
.into_iter()
.collect(),
}
}
pub fn lookup(&self, name: &ast::Ident) -> Option<Ident> {
self.scope.get(name).copied()
}
fn add(&mut self, name: &ast::Ident, ident: Ident) -> Ident {
self.scope.insert(name.clone(), ident);
ident
}
pub fn add_arg(&mut self, name: &ast::Ident, index: usize) {
self.scope.insert(name.clone(), Ident::Argument(index));
}
pub fn add_local(&mut self, name: &ast::Ident) -> Ident {
let index = self.locals.len();
self.locals.push(name.clone());
self.add(name, Ident::Local(index))
}
pub fn add_upvalue(&mut self, name: &ast::Ident, up_ident: Ident) -> Ident {
let index = self.upvalues.len();
self.upvalues.push((name.clone(), up_ident));
self.add(name, Ident::Upvalue(index))
} }
} }
fn lookup(&self, name: &ast::Ident) -> Option<Ident> {
self.scope.get(name).copied()
}
fn add(&mut self, name: &ast::Ident, ident: Ident) -> Ident {
self.scope.insert(name.clone(), ident);
ident
}
fn add_arg(&mut self, name: &ast::Ident, index: usize) {
self.scope.insert(name.clone(), Ident::Argument(index));
}
fn add_local(&mut self, name: &ast::Ident) -> Ident {
let index = self.locals.len();
self.locals.push(name.clone());
self.add(name, Ident::Local(index))
}
fn add_upvalue(&mut self, name: &ast::Ident, up_ident: Ident) -> Ident {
let index = self.upvalues.len();
self.upvalues.push((name.clone(), up_ident));
self.add(name, Ident::Upvalue(index))
}
} }
use scope::Scope;
#[derive(Debug)] #[derive(Debug)]
struct BuildContext<'a> { struct BuildContext<'a> {