~starkingdoms/starkingdoms

ref: 3cad7d73f8ce1baf291a334628fb96a93c5fafe6 starkingdoms/kabel/src/name_resolution.rs -rw-r--r-- 14.6 KiB
3cad7d73 — ghostly_zsh list initialization and subscripting 1 year, 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use std::collections::HashMap;

use crate::{ast::{ASTType, AST}, ast_error, ast_from_ast, error::{ErrorKind, KabelError}, extension::Extension, out_of_scope_var};

pub struct Resolver {
    text: Vec<String>,
    symbol_table: Vec<HashMap<String, (Symbol, usize)>>, // (Symbol, reference to locals)
    pub locals: Vec<Vec<usize>>, // scope
    pub scope: usize,
    pub errors: Vec<KabelError>,
}

impl Resolver {
    pub fn new(text: String) -> Self {
        Self {
            text: text.lines().collect::<Vec<&str>>().iter().map(|s| s.to_string()).collect(),
            symbol_table: vec![HashMap::new()],
            locals: vec![Vec::new()],
            scope: 0,
            errors: Vec::new(),
        }
    }
    pub fn visit(&mut self, ast: AST) -> AST {
        use ASTType::*;
        match ast.ast_type {
            Program(asts) => {
                let mut program = Vec::new();
                for ast in asts {
                    let ast = self.visit(ast.clone());
                    program.push(ast)
                }
                AST {
                    ast_type: ASTType::Program(program),
                    extensions: Vec::new(),
                    start_line: 0,
                    end_line: 0,
                    start_column: 0,
                    end_column: 0,
                }
            }
            Function(name, args, block) => {
                if self.resolve_var(&name.name).0 {
                    self.errors.push(out_of_scope_var!(self,
                            ErrorKind::FunctionAlreadyDeclaredVariable, ast,
                            "Function \"{}\" already declared", name ;
                            "hint: has variable \"{}\" already been declared?", name.name));
                } else {
                    let resolution = self.resolve_function(&name.name, 0);
                    if resolution.is_ok() {
                        self.errors.push(out_of_scope_var!(self,
                                ErrorKind::FunctionAlreadyDeclaredFunction, ast,
                                "Function \"{}\" already declared", name ;
                                "hint: has function \"{}\" already been declared?", name.name));
                    }
                    if let Err((kind, _, _)) = resolution {
                        if kind == ErrorKind::IncorrectArity {
                            self.errors.push(out_of_scope_var!(self,
                                    ErrorKind::FunctionAlreadyDeclaredFunction, ast,
                                    "Function \"{}\" already declared", name ;
                                    "hint: has function \"{}\" already been declared?", name.name));
                        } else {}
                    }
                }
                self.locals.last_mut().expect("locals last in function push").push(self.scope);
                self.symbol_table.last_mut().unwrap().insert(name.name.clone(),
                 (Symbol::Function(args.len()), self.locals.last().expect("locals last in function symbol len").len()-1));

                self.locals.push(Vec::new());
                self.symbol_table.push(HashMap::new());
                self.locals.last_mut().expect("locals last in function self-reference push").push(self.scope+1);
                self.symbol_table.last_mut().unwrap().insert(name.name.clone(), (Symbol::Var,self.locals.last().expect("locals last in function self-reference len").len()-1));
                for arg in args.clone() {
                    self.locals.last_mut().expect("locals last in function arg push").push(self.scope+1);
                    self.symbol_table.last_mut().unwrap().insert(arg.name, (Symbol::Var,self.locals.last().expect("locals last in function arg len").len()-1));
                }
                let block = self.visit(*block);
                self.symbol_table.pop();
                self.locals.pop();
                AST {
                    ast_type: Function(name, args, Box::new(block)),
                    extensions: vec![Extension::Resolution(self.scope, self.locals.last().expect("locals last in function ast len").len()-1)],
                    start_line: ast.start_line,
                    end_line: ast.end_line,
                    start_column: ast.start_column,
                    end_column: ast.end_column,
                }
            }
            Return(expr) => {
                if let Some(expr) = *expr {
                    let expr = self.visit(expr);
                    return ast_from_ast!(Return(Box::new(Some(expr))), ast, ast);
                }
                ast_from_ast!(Return(Box::new(None)), ast, ast)
            }
            Loop(block) => {
                let block = self.visit(*block);
                ast_from_ast!(Loop(Box::new(block)), ast, ast)
            }
            While(condition, block) => {
                let condition = self.visit(*condition);
                let block = self.visit(*block);
                ast_from_ast!(While(Box::new(condition), Box::new(block)), ast, ast)
            }
            Break => { ast_from_ast!(Break, ast, ast) }
            Continue => { ast_from_ast!(Continue, ast, ast) }
            For(expr1, expr2, expr3, block) => {
                self.symbol_table.push(HashMap::new());
                self.scope += 1;
                let mut n_expr1 = None;
                let mut n_expr2 = None;
                let mut n_expr3 = None;
                if let Some(expr) = *expr1 {
                    n_expr1 = Some(self.visit(expr));
                }
                if let Some(expr) = *expr2 {
                    n_expr2 = Some(self.visit(expr));
                }
                if let Some(expr) = *expr3 {
                    n_expr3 = Some(self.visit(expr));
                }
                let block = self.visit(*block);
                while let Some(scope) = self.locals.last().expect("locals failed in For").last() {
                    if self.scope == *scope {
                        self.locals.last_mut().expect("locals failed in For pop").pop();
                    } else {
                        break;
                    }
                }
                self.scope -= 1;
                self.symbol_table.pop();
                ast_from_ast!(For(Box::new(n_expr1), Box::new(n_expr2), Box::new(n_expr3), Box::new(block)), ast, ast)
            }
            If(condition, block, else_expr) => {
                let condition = self.visit(*condition);
                let block = self.visit(*block);
                let mut n_else_expr = None;
                if let Some(else_expr) = *else_expr {
                    n_else_expr = Some(self.visit(else_expr));
                }
                ast_from_ast!(If(Box::new(condition), Box::new(block), Box::new(n_else_expr)), ast, ast)
            }
            Block(stmts) => {
                self.symbol_table.push(HashMap::new());
                self.scope += 1;
                let mut n_stmts = Vec::new();
                for stmt in stmts {
                    n_stmts.push(self.visit(stmt));
                }
                /*for (index, scope) in self.locals.clone().iter().enumerate() {
                    if self.scope == *scope {
                        self.locals.remove(index);
                    }
                }*/
                while let Some(scope) = self.locals.last().expect("locals last in block").last() {
                    if self.scope == *scope {
                        self.locals.last_mut().expect("locals last in block pop").pop();
                    } else {
                        break;
                    }
                }
                self.scope -= 1;
                self.symbol_table.pop();
                ast_from_ast!(Block(n_stmts), ast, ast)
            }
            Decl(name, expr) => {
                let expr = self.visit(*expr);
                self.locals.last_mut().expect("locals last in decl push").push(self.scope);
                if self.resolve_var(&name.name).0 {
                    self.errors.push(out_of_scope_var!(self,
                            ErrorKind::VariableAlreadyDeclaredVariable, ast,
                            "Variable \"{}\" already declared", name ;
                            "hint: has variable \"{}\" already been declared?", name.name));
                } else {
                    let resolution = self.resolve_function(&name.name, 0);
                    if resolution.is_ok() {
                        self.errors.push(out_of_scope_var!(self,
                                ErrorKind::VariableAlreadyDeclaredFunction, ast,
                                "Variable \"{}\" already declared", name ;
                                "hint: has function \"{}\" already been declared?", name.name));
                    }
                    if let Err((kind, _, _)) = resolution {
                        if kind == ErrorKind::IncorrectArity {
                            self.errors.push(out_of_scope_var!(self,
                                    ErrorKind::VariableAlreadyDeclaredFunction, ast,
                                    "Variable \"{}\" already declared", name ;
                                    "hint: has function \"{}\" already been declared?", name.name));
                        } else {}
                    }
                }
                self.symbol_table.last_mut().unwrap().insert(name.name.clone(), (Symbol::Var, self.locals.last().expect("locals last in decl symbol").len()-1));
                AST {
                    ast_type: Decl(name, Box::new(expr)),
                    extensions: vec![Extension::Resolution(self.scope, self.locals.last().expect("locals last in decl ast").len()-1)],
                    start_line: ast.start_line,
                    end_line: ast.end_line,
                    start_column: ast.start_column,
                    end_column: ast.end_column,
                }
            }
            Expr(expr) => {
                let expr = self.visit(*expr);
                ast_from_ast!(Expr(Box::new(expr)), ast, ast)
            }
            // REMOVE LATER
            Print(expr) => {
                let expr = self.visit(*expr);
                ast_from_ast!(Print(Box::new(expr)), ast, ast)
            }
            Assign(name, expr) => {
                let expr = self.visit(*expr);
                let resolution = self.resolve_var(&name.name);
                if !resolution.0 {
                    self.errors.push(out_of_scope_var!(self,
                            ErrorKind::OutOfScope, ast,
                            "Variable \"{}\" not in scope", name));
                }
                AST {
                    ast_type: Assign(name, Box::new(expr)),
                    extensions: vec![Extension::Resolution(self.scope, resolution.1)],
                    start_line: ast.start_line,
                    end_line: ast.end_line,
                    start_column: ast.start_column,
                    end_column: ast.end_column,
                }
            }
            Ternary(condition, true_expr, false_expr) => {
                let condition = self.visit(*condition);
                let true_expr = self.visit(*true_expr);
                let false_expr = self.visit(*false_expr);
                ast_from_ast!(Ternary(Box::new(condition), Box::new(true_expr), Box::new(false_expr)), ast, ast)
            }
            Subscript(array, index) => {
                let array = self.visit(*array);
                let index = self.visit(*index);
                ast_from_ast!(Subscript(Box::new(array), Box::new(index)), ast, ast)
            }
            Binary(left, oper, right) => {
                let left = self.visit(*left);
                let right = self.visit(*right);
                ast_from_ast!(Binary(Box::new(left), oper, Box::new(right)), ast, ast)
            }
            Unary(oper, right) => {
                let right = self.visit(*right);
                ast_from_ast!(Unary(oper, Box::new(right)), ast, ast)
            }
            Lit(ref lit) => {
                let lit = lit.clone();
                match lit {
                    crate::ast::Lit::Ident(ref name) => {
                        let resolution = self.resolve_var(name);
                        if !resolution.0 {
                            self.errors.push(ast_error!(self, ErrorKind::OutOfScope, ast, "Variable \"{}\" not in scope", name))
                        } else {
                            return AST {
                                ast_type: Lit(lit),
                                extensions: vec![Extension::Resolution(self.scope, resolution.1)],
                                start_line: ast.start_line,
                                end_line: ast.end_line,
                                start_column: ast.start_column,
                                end_column: ast.end_column,
                            };
                        }
                    }
                    _ => {}
                }
                ast_from_ast!(Lit(lit), ast, ast)
            }
            Call(ident, args) => {
                let ident = self.visit(*ident.clone());
                let mut n_args = Vec::new();
                for arg in args {
                    n_args.push(self.visit(arg));
                }
                return AST {
                    ast_type: Call(Box::new(ident), n_args),
                    extensions: Vec::new(),
                    start_line: ast.start_line,
                    end_line: ast.end_line,
                    start_column: ast.start_column,
                    end_column: ast.end_column,
                };
            }
            /*Member(left, right) => {
                self.visit_member(*left, *right);
            }*/
            _ => { panic!("not implemented") } // not implemented
        }
    }
    // TODO: make visit_member not throw out of scope errors
    /*pub fn visit_member(&mut self, left: AST, right: AST) {
        self.visit(left);
        self.visit(right);
    }*/
    fn resolve_var(&self, name: &String) -> (bool, usize) {
        for scope in self.symbol_table.iter().rev() {
            if let Some((Symbol::Var, place)) | Some((Symbol::Function(_), place)) = scope.get(name) {
                return (true, *place);
            }
        }
        (false, 0)
    }
    fn resolve_function(&mut self, name: &String, arity: usize) -> Result<usize, (ErrorKind, Option<usize>, Option<usize>)>{
        for scope in self.symbol_table.iter().rev() {
            if let Some((Symbol::Function(f_arity), place)) = scope.get(name) {
                if *f_arity == arity {
                    return Ok(*place);
                } else {
                    return Err((ErrorKind::IncorrectArity, Some(*f_arity), Some(arity)));
                }
            }
        }
        Err((ErrorKind::OutOfScope, None, None))
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Symbol {
    Var,
    Function(usize),
}