-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
lower.rs
382 lines (320 loc) · 12 KB
/
lower.rs
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#![allow(unused)]
use crate::parser::ast::ExprKind;
use crate::parser::tokens::TokenType;
use crate::parser::visitors::VisitorMut;
use crate::parser::{ast, interner::InternedString};
use std::collections::HashSet;
use im_rc::HashMap;
use super::ir::Expr;
// ((lambda (x y z) (+ x y z)) 10 20 30)
// =>
// (x = 10)
// (y = 20)
// (z = 30)
// (+ x (+ y z))
struct RenameShadowedVars<'a> {
depth: usize,
in_scope: HashSet<InternedString>,
shadowed: HashMap<InternedString, usize>,
args: Option<Vec<InternedString>>,
ret_val: Option<InternedString>,
legal_vars: &'a HashSet<InternedString>,
}
impl<'a> RenameShadowedVars<'a> {
pub fn new(legal_vars: &'a HashSet<InternedString>) -> Self {
Self {
depth: 0,
in_scope: HashSet::new(),
shadowed: HashMap::new(),
args: None,
ret_val: None,
legal_vars,
}
}
}
// If a new variable is introduced, we should just insert it into the map with an empty shadow
// Removing should only remove if the
// #[derive(Default)]
// struct ScopeMap {
// inner: HashMap<String, Vec<String>>,
// }
// impl ScopeMap {
// fn insert()
// }
/// Checks that the input is in fact a lowered function
pub fn lower_function(
expr: &ExprKind,
bound_vars: &mut HashSet<InternedString>,
) -> Option<(String, Vec<String>, String, Vec<Expr>)> {
// let mut visitor = RenameShadowedVars::default();
if let ExprKind::Define(d) = expr {
let function_name = d.name.atom_identifier_or_else(|| unreachable!()).ok()?;
// Register the function itself as a legal function to be used
// NOTE: Unbind the function name if compilation fails
bound_vars.insert(function_name.to_string());
let mut visitor = RenameShadowedVars::new(&bound_vars);
if let ExprKind::LambdaFunction(_) = &d.body {
// let func_name = d.name.atom_identifier_or_else(|| unreachable!()).ok()?;
// let output = visitor.visit_define(&d)?;
match visitor.visit_define(&d) {
Some(Expr::Assign(func_name, stmt)) => {
// return Some((func_name, visitor.args?, visitor.ret_val?, vec![*stmt]));
return Some((func_name, visitor.args?, visitor.ret_val?, vec![*stmt]));
}
_ => {
// Make this function name illegal if compilation failed
bound_vars.remove(function_name);
}
}
// Make this function name illegal if compilation failed
// bound_vars.remove(function_name);
// if let Expr::Assign(func_name, stmt) = output {
// // return Some((func_name, visitor.args?, visitor.ret_val?, vec![*stmt]));
// return Some((func_name, visitor.args?, visitor.ret_val?, vec![*stmt]));
// }
}
}
None
}
impl<'a> VisitorMut for RenameShadowedVars<'a> {
type Output = Option<Expr>;
// Not great, but gets the job done
fn visit_if(&mut self, f: &ast::If) -> Self::Output {
let test = Box::new(self.visit(&f.test_expr)?);
let then_expr = self.visit(&f.then_expr)?;
let else_expr = self.visit(&f.else_expr)?;
match (&then_expr, &else_expr) {
(Expr::Block(t), Expr::Block(e)) => Some(Expr::IfElse(test, t.clone(), e.clone())),
(Expr::Block(t), _) => Some(Expr::IfElse(test, t.clone(), vec![else_expr])),
(_, Expr::Block(e)) => Some(Expr::IfElse(test, vec![then_expr], e.clone())),
(_, _) => Some(Expr::IfElse(test, vec![then_expr], vec![else_expr])),
}
}
// Define -> Assignment
fn visit_define(&mut self, define: &ast::Define) -> Self::Output {
let body = self.visit(&define.body)?;
let name = define
.name
.atom_identifier_or_else(|| unreachable!())
.ok()?
.to_owned();
// self.in_scope.insert(name.clone());
Some(Expr::Assign(name, Box::new(body)))
}
// If done correctly, this _should_ be unreachable
fn visit_lambda_function(&mut self, lambda_function: &ast::LambdaFunction) -> Self::Output {
// TODO identify return variables
// Do I need to specify the return or is the last value just there?
let args = lambda_function
.args
.iter()
.map(|x| {
x.atom_identifier_or_else(|| unreachable!())
.ok()
.map(|x| x.to_string())
})
.collect::<Option<Vec<_>>>()?;
// Make sure these are now in scope
for arg in &args {
self.in_scope.insert(arg.clone());
}
self.args = Some(args);
// Badly attach the return value label
self.ret_val = Some("###__return-value__###".to_string());
let output = Some(Expr::Assign(
"###__return-value__###".to_string(),
Box::new(self.visit(&lambda_function.body)?),
));
output
}
fn visit_begin(&mut self, begin: &ast::Begin) -> Self::Output {
let body = begin
.exprs
.iter()
.map(|e| self.visit(e))
.collect::<Option<Vec<_>>>()?;
Some(Expr::Block(body))
}
fn visit_return(&mut self, _r: &ast::Return) -> Self::Output {
None
}
// fn visit_apply(&mut self, _apply: &ast::Apply) -> Self::Output {
// None
// }
// fn visit_panic(&mut self, _p: &ast::Panic) -> Self::Output {
// None
// }
// fn visit_transduce(&mut self, _transduce: &ast::Transduce) -> Self::Output {
// None
// }
// fn visit_execute(&mut self, _execute: &ast::Execute) -> Self::Output {
// None
// }
fn visit_quote(&mut self, _quote: &ast::Quote) -> Self::Output {
None
}
fn visit_macro(&mut self, _m: &ast::Macro) -> Self::Output {
None
}
// TODO fix this
fn visit_atom(&mut self, a: &ast::Atom) -> Self::Output {
use TokenType::*;
match &a.syn.ty {
Identifier(s) => {
// Short circuit if we reference a function that we can't yet reference
self.validate_identifier(s)?;
if let Some(depth) = self.shadowed.get(s) {
// Create this busted shadowed nonsense
Some(Expr::Identifier(
"###__depth__".to_string() + depth.to_string().as_str() + s.as_str(),
))
} else {
Some(Expr::Identifier(s.clone()))
}
}
IntegerLiteral(i) => Some(Expr::Literal(i.to_string())),
_ => None,
}
}
// Check explicit function application with let
fn visit_list(&mut self, l: &ast::List) -> Self::Output {
// The first should be the function, and the rest should be the args
let mut args = l.iter();
// The corresponds to either a symbol, or a lambda function in this case
// Anything else we don't care about
let func = args.next()?;
match func {
ExprKind::LambdaFunction(lam) => {
self.depth += 1;
// These need to be mangled?
let variable_names = lam
.args
.iter()
.map(|x| x.atom_identifier_or_else(|| unreachable!()).ok().cloned())
.collect::<Option<Vec<_>>>()?;
let pre_variables = self.shadowed.clone();
// These are the lowered assignments
let mut assignments = variable_names
.clone()
.into_iter()
.zip(args)
.map(|x| -> Option<Expr> {
Some(Expr::Assign(
{
if self.in_scope.contains(&x.0) {
"###__depth__".to_string()
+ self.depth.to_string().as_str()
+ x.0.as_str()
} else {
x.0
}
},
Box::new(self.visit(x.1)?),
))
})
.collect::<Option<Vec<_>>>()?;
for variable in &variable_names {
if self.in_scope.contains(variable) {
println!("Shadowing: {}", variable);
self.shadowed.insert(variable.clone(), self.depth);
}
}
let body = self.visit(&lam.body)?;
// They're no longer in scope, take them out
for variable in &variable_names {
self.in_scope.remove(variable);
self.shadowed.remove(variable);
}
// Just reset the state for now
self.shadowed = pre_variables;
self.depth -= 1;
assignments.push(body);
Some(Expr::Block(assignments))
}
_ => {
let ident = func
.atom_identifier_or_else(|| "Not a valid function here")
.ok()?;
if let Some(binop) = symbol_to_binop(ident) {
self.expr_list_to_bin_op(binop, args)
} else {
self.validate_function_call_ident(ident)?;
Some(Expr::Call(
ident.to_owned(),
args.map(|x| self.visit(x)).collect::<Option<Vec<_>>>()?,
))
}
}
}
}
fn visit_syntax_rules(&mut self, _l: &ast::SyntaxRules) -> Self::Output {
None
}
// This should be assignment
// but only if the variable being assigned is scoped locally to the function
fn visit_set(&mut self, _s: &ast::Set) -> Self::Output {
todo!()
}
fn visit_require(&mut self, _s: &ast::Require) -> Self::Output {
None
}
fn visit_let(&mut self, l: &ast::Let) -> Self::Output {
todo!()
}
}
impl<'a> RenameShadowedVars<'a> {
fn expr_list_to_bin_op<'b>(
&mut self,
binop: fn(Box<Expr>, Box<Expr>) -> Expr,
exprs: impl DoubleEndedIterator<Item = &'b ExprKind>,
) -> Option<Expr> {
let mut args_iter = exprs.into_iter();
let left_initial = Box::new(self.visit(args_iter.next()?)?);
let right_initial = Box::new(self.visit(args_iter.next()?)?);
args_iter.try_fold(binop(left_initial, right_initial), |accum, next| {
Some(binop(Box::new(accum), Box::new(self.visit(next)?)))
})
}
fn validate_function_call_ident(&self, ident: &InternedString) -> Option<()> {
if self.legal_vars.contains(ident) {
println!("Validated: {}", ident);
println!("Legal vars: {:#?}", self.legal_vars);
Some(())
} else {
println!(
"Found a variable that cannot be referenced, aborting compilation: {}",
ident
);
None
}
}
fn validate_identifier(&self, ident: &InternedString) -> Option<()> {
if !self.shadowed.contains_key(ident)
&& !self.in_scope.contains(ident)
&& !self.legal_vars.contains(ident)
{
println!(
"Found a variable that cannot be referenced, aborting compilation: {}",
ident
);
None
} else {
Some(())
}
}
}
fn symbol_to_binop(symbol: &str) -> Option<fn(Box<Expr>, Box<Expr>) -> Expr> {
match symbol {
"+" => Some(Expr::Add),
"-" => Some(Expr::Sub),
"/" => Some(Expr::Div),
"*" => Some(Expr::Mul),
"=" | "equal?" | "eq?" => Some(Expr::Eq),
"<" => Some(Expr::Lt),
">" => Some(Expr::Gt),
"!=" => Some(Expr::Ne),
">=" => Some(Expr::Ge),
"<=" => Some(Expr::Le),
_ => None,
}
}