oonta 0.3.1

OCaml (subset) to LLVM IR compiler front-end
Documentation
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;

use crate::ast::{
    ApplicationExpr, Ast, BinOpExpr, CondExpr, ConstructExpr, Expr, FunExpr, LetInExpr,
    PatternMatchExpr, TupleExpr, VarExpr,
};
use crate::lexer::Lexer;
use crate::pass::type_inference::TypeMap;
use crate::typ::{Primitive, Type, Variable, is_polymorphic};
use crate::utils::terminal_colors::{BLUE, END, YELLOW};

struct MonoPass<'a> {
    mono_binds: MonoBinds,
    poly_binds: HashMap<&'a str, Rc<RefCell<Expr>>>,
    binds_to_mono_names: HashMap<&'a str, Vec<String>>,
    binds_indices: HashMap<&'a str, usize>,
    renamed_captures: HashMap<&'a str, String>,
    debug: bool,
    type_map: &'a mut TypeMap,
    lexer: &'a Lexer,
}

#[derive(Default)]
pub struct MonoBinds {
    pub binds: Vec<MonoBind>,
    pub forced_mono_binds: Vec<usize>,
}

pub struct MonoBind {
    pub name: String,
    pub expr: Rc<RefCell<Expr>>,
    pub insertion_index: usize,
}

pub fn monomorphize(ast: &Ast, type_map: &mut TypeMap, lexer: &Lexer, debug: bool) -> MonoBinds {
    let mut pass = MonoPass {
        mono_binds: MonoBinds::default(),
        poly_binds: HashMap::new(),
        binds_to_mono_names: HashMap::new(),
        binds_indices: HashMap::new(),
        renamed_captures: HashMap::new(),
        debug,
        type_map,
        lexer,
    };
    pass.visit_binds(ast);
    pass.mono_binds
}

impl<'a> MonoPass<'a> {
    fn visit_binds(&mut self, ast: &Ast) {
        for (i, bind) in ast.binds.iter().enumerate() {
            let typ = self.get_from_type_map(&bind.expr);
            let name = bind
                .name
                .clone()
                .map(|span| self.lexer.str_from_span(&span));
            if let Some(name) = name {
                self.binds_indices.insert(name, i);
                if let Some(mono_names) = self.binds_to_mono_names.get_mut(name) {
                    mono_names.clear();
                }
            }
            if is_polymorphic(typ) {
                if let Some(name) = name {
                    self.poly_binds.insert(name, bind.expr.clone());
                }
            } else {
                if let Some(name) = name {
                    self.poly_binds.remove(name);
                }
                self.transform_poly_applications(&bind.expr);
                self.renamed_captures.clear();
            }
        }
    }

    fn transform_poly_applications(&mut self, expr: &Rc<RefCell<Expr>>) {
        match &mut *expr.borrow_mut() {
            Expr::Application(application_expr) => {
                self.transform_poly_application(application_expr);
                application_expr
                    .binds
                    .iter()
                    .for_each(|e| self.transform_poly_applications(e));
            }
            Expr::Fun(fun_expr) => {
                self.transform_poly_applications(&fun_expr.body);
                for capture in fun_expr.captures.iter_mut() {
                    if let Some(rename) = self.renamed_captures.remove(&capture[..]) {
                        *capture = rename;
                    }
                }
            }
            Expr::Tuple(tuple_expr) => {
                tuple_expr
                    .elements
                    .iter()
                    .for_each(|e| self.transform_poly_applications(e));
            }
            Expr::Construction(construction_expr) => {
                if let Some(arg) = &construction_expr.arg {
                    self.transform_poly_applications(arg);
                }
            }
            Expr::LetIn(let_in_expr) => {
                self.transform_poly_applications(&let_in_expr.bind.1);
                self.transform_poly_applications(&let_in_expr.expr);
            }
            Expr::BinOp(bin_op_expr) => {
                self.transform_poly_applications(&bin_op_expr.lhs);
                self.transform_poly_applications(&bin_op_expr.rhs);
            }
            Expr::Conditional(cond_expr) => {
                self.transform_poly_applications(&cond_expr.cond);
                self.transform_poly_applications(&cond_expr.yes);
                self.transform_poly_applications(&cond_expr.no);
            }
            Expr::PatternMatch(pattern_match_expr) => {
                self.transform_poly_applications(&pattern_match_expr.matched);
                pattern_match_expr
                    .branches
                    .iter()
                    .for_each(|(_, e)| self.transform_poly_applications(e));
            }
            Expr::Var(var) => {
                if self.is_polymorphic(var) {
                    let bind_idx = self.insertion_index(var);
                    if !self.mono_binds.forced_mono_binds.contains(&bind_idx) {
                        self.mono_binds.forced_mono_binds.push(bind_idx);
                        self.debug_force_mono(var);
                    }
                }
            }
            Expr::Literal(_) => (),
        }
    }

    fn transform_poly_application(&mut self, application_expr: &mut ApplicationExpr) {
        let mono_typ = self.get_from_type_map(&application_expr.fun);
        let mut application_fun = application_expr.fun.borrow_mut();
        let var = match &mut *application_fun {
            Expr::Var(var) => var,
            _ => return,
        };
        let poly_expr = match self.poly_binds.get(self.lexer.str_from_span(&var.id)) {
            Some(expr) => expr,
            None => return,
        };
        let poly_typ = self.get_from_type_map(poly_expr);

        let mut poly_args = BTreeMap::new();
        gather_poly_args(&poly_typ, &mono_typ, &mut poly_args);
        let poly_args_str = poly_args_to_string(&poly_args);
        var.poly_args.replace(poly_args_str.clone());

        if !self.is_monomorphized(var) {
            self.debug(var, &poly_typ, &mono_typ, &poly_args);
            let mono_name = var.mono_name(self.lexer);
            let mono_expr = self.monomorphize_expr(&poly_expr.clone(), &poly_args);
            self.replace_recursive_bind_name(mono_expr.clone(), mono_name.clone());
            let mono_bind = MonoBind::new(mono_name, mono_expr.clone(), self.insertion_index(var));
            self.mono_binds.binds.push(mono_bind);
            self.insert_mono_name(var);
            self.transform_poly_applications(&mono_expr);
            self.renamed_captures.clear();
        }

        self.renamed_captures
            .insert(var.base_name(self.lexer), var.mono_name(self.lexer));
    }

    fn monomorphize_expr(
        &mut self,
        poly_expr: &Rc<RefCell<Expr>>,
        poly_args: &BTreeMap<usize, Rc<RefCell<Type>>>,
    ) -> Rc<RefCell<Expr>> {
        let expr = match &*poly_expr.borrow() {
            Expr::Fun(FunExpr {
                params,
                body,
                captures,
                recursive_bind,
                span,
            }) => {
                let params = params.clone();
                let body = self.monomorphize_expr(body, poly_args);
                let captures = captures.clone();
                let recursive_bind = recursive_bind.clone();
                let span = span.clone();
                Expr::Fun(FunExpr {
                    params,
                    body,
                    captures,
                    recursive_bind,
                    span,
                })
            }
            Expr::Application(ApplicationExpr { fun, binds, span }) => {
                let fun = self.monomorphize_expr(fun, poly_args);
                let binds = binds
                    .iter()
                    .map(|b| self.monomorphize_expr(b, poly_args))
                    .collect();
                let span = span.clone();
                Expr::Application(ApplicationExpr { fun, binds, span })
            }
            Expr::Conditional(CondExpr {
                cond,
                yes,
                no,
                span,
            }) => {
                let cond = self.monomorphize_expr(cond, poly_args);
                let yes = self.monomorphize_expr(yes, poly_args);
                let no = self.monomorphize_expr(no, poly_args);
                let span = span.clone();
                Expr::Conditional(CondExpr {
                    cond,
                    yes,
                    no,
                    span,
                })
            }
            Expr::PatternMatch(PatternMatchExpr {
                matched,
                branches,
                span,
            }) => {
                let matched = self.monomorphize_expr(matched, poly_args);
                let branches = branches
                    .iter()
                    .map(|b| (b.0.clone(), self.monomorphize_expr(&b.1, poly_args)))
                    .collect();
                let span = span.clone();
                Expr::PatternMatch(PatternMatchExpr {
                    matched,
                    branches,
                    span,
                })
            }
            Expr::Tuple(TupleExpr { elements, span }) => {
                let elements = elements
                    .iter()
                    .map(|e| self.monomorphize_expr(e, poly_args))
                    .collect();
                let span = span.clone();
                Expr::Tuple(TupleExpr { elements, span })
            }
            Expr::BinOp(BinOpExpr { op, lhs, rhs, span }) => {
                let op = *op;
                let lhs = self.monomorphize_expr(lhs, poly_args);
                let rhs = self.monomorphize_expr(rhs, poly_args);
                let span = span.clone();
                Expr::BinOp(BinOpExpr { op, lhs, rhs, span })
            }
            Expr::Construction(ConstructExpr { cons, arg, span }) => {
                let cons = cons.clone();
                let arg = arg
                    .clone()
                    .map(|expr| self.monomorphize_expr(&expr, poly_args));
                let span = span.clone();
                Expr::Construction(ConstructExpr { cons, arg, span })
            }
            Expr::LetIn(LetInExpr { bind, expr, span }) => {
                let bind = (bind.0.clone(), self.monomorphize_expr(&bind.1, poly_args));
                let expr = self.monomorphize_expr(expr, poly_args);
                let span = span.clone();
                Expr::LetIn(LetInExpr { bind, expr, span })
            }
            Expr::Literal(literal_expr) => Expr::Literal(literal_expr.clone()),
            Expr::Var(var_expr) => Expr::Var(var_expr.clone()),
        };
        let expr = Rc::new(RefCell::new(expr));
        let poly_typ = self.get_from_type_map(poly_expr);
        let typ = monomorphize_typ(&poly_typ, poly_args);
        self.insert_into_type_map(&expr, typ);
        expr
    }

    fn replace_recursive_bind_name(&self, expr: Rc<RefCell<Expr>>, mono_name: String) {
        if let Expr::Fun(fun_expr) = &mut *expr.borrow_mut()
            && let Some(name) = &mut fun_expr.recursive_bind
        {
            *name = mono_name;
        }
    }

    fn get_from_type_map(&self, expr: &Rc<RefCell<Expr>>) -> Rc<RefCell<Type>> {
        let expr_ptr = &*expr.borrow() as *const Expr;
        self.type_map.get(expr_ptr).unwrap()
    }

    fn insert_into_type_map(&mut self, expr: &Rc<RefCell<Expr>>, typ: Rc<RefCell<Type>>) {
        let expr_ptr = &*expr.borrow() as *const Expr;
        self.type_map.insert(expr_ptr, typ);
    }

    fn is_monomorphized(&self, var: &VarExpr) -> bool {
        let base_name = var.base_name(self.lexer);
        let mono_name = var.mono_name(self.lexer);
        self.binds_to_mono_names
            .get(base_name)
            .map(|mono_names| mono_names.contains(&mono_name))
            .unwrap_or(false)
    }

    fn insertion_index(&self, var: &VarExpr) -> usize {
        let base_name = var.base_name(self.lexer);
        *self.binds_indices.get(base_name).unwrap()
    }

    fn insert_mono_name(&mut self, var: &VarExpr) {
        let base_name = var.base_name(self.lexer);
        let mono_name = var.mono_name(self.lexer);
        if let Some(mono_names) = self.binds_to_mono_names.get_mut(base_name) {
            mono_names.push(mono_name);
        } else {
            self.binds_to_mono_names
                .insert(base_name, vec![mono_name.clone()]);
        }
    }

    fn is_polymorphic(&self, var: &VarExpr) -> bool {
        let base_name = var.base_name(self.lexer);
        self.poly_binds.contains_key(base_name)
    }

    fn debug(
        &self,
        var: &VarExpr,
        poly_typ: &Rc<RefCell<Type>>,
        mono_typ: &Rc<RefCell<Type>>,
        poly_args: &BTreeMap<usize, Rc<RefCell<Type>>>,
    ) {
        if self.debug {
            println!(
                "Monomorphing {YELLOW}'{}' {}{END} into {BLUE}{}{END}:",
                var.base_name(self.lexer),
                poly_typ.borrow(),
                mono_typ.borrow()
            );
            poly_args.values().enumerate().for_each(|(i, v)| {
                println!(
                    "{YELLOW}'{}{END} -> {BLUE}{}{END}",
                    char::from_u32(i as u32 + 'a' as u32).unwrap(),
                    v.borrow()
                )
            });
        }
    }

    fn debug_force_mono(&self, var: &VarExpr) {
        if self.debug {
            let base_name = var.base_name(self.lexer);
            println!("{BLUE}'{}'{END} bind forced as monomorphic", base_name);
        }
    }
}

fn gather_poly_args(
    poly_typ: &Rc<RefCell<Type>>,
    mono_typ: &Rc<RefCell<Type>>,
    typ_args: &mut BTreeMap<usize, Rc<RefCell<Type>>>,
) {
    match (&*poly_typ.borrow(), &*mono_typ.borrow()) {
        (_, Type::Variable(Variable::Link(mono_typ))) => {
            gather_poly_args(poly_typ, mono_typ, typ_args)
        }
        (Type::Variable(Variable::Link(poly_typ)), _) => {
            gather_poly_args(poly_typ, mono_typ, typ_args)
        }
        (Type::Variable(Variable::Unbound(v)), Type::Custom(_, _))
        | (Type::Variable(Variable::Unbound(v)), Type::Tuple(_))
        | (Type::Variable(Variable::Unbound(v)), Type::Primitive(_)) => {
            typ_args.insert(*v, mono_typ.clone());
        }
        (Type::Fun(poly_typs), Type::Fun(mono_typs))
        | (Type::Tuple(poly_typs), Type::Tuple(mono_typs))
        | (Type::Custom(_, poly_typs), Type::Custom(_, mono_typs)) => {
            poly_typs
                .iter()
                .zip(mono_typs)
                .for_each(|(poly_typ, mono_typ)| gather_poly_args(poly_typ, mono_typ, typ_args));
        }
        (Type::Variable(Variable::Unbound(v)), Type::Variable(Variable::Unbound(_))) => {
            // If there is still an unbound variable left, that means it does not matter what type
            // it is bound to. We'll use integer as default.
            // TODO: Use available monomorphized expression
            let int_typ = Rc::new(RefCell::new(Type::Primitive(Primitive::Integer)));
            typ_args.insert(*v, int_typ);
        }
        _ => (),
    }
}

fn poly_args_to_string(typ_args: &BTreeMap<usize, Rc<RefCell<Type>>>) -> String {
    typ_args
        .values()
        .map(|t| t.borrow().poly_arg_str())
        .collect::<Vec<String>>()
        .join(".")
}

fn monomorphize_typ(
    poly_typ: &Rc<RefCell<Type>>,
    typ_args: &BTreeMap<usize, Rc<RefCell<Type>>>,
) -> Rc<RefCell<Type>> {
    match &*poly_typ.borrow() {
        Type::Fun(typs) => {
            let typs = typs
                .iter()
                .map(|typ| monomorphize_typ(typ, typ_args))
                .collect();
            Rc::new(RefCell::new(Type::Fun(typs)))
        }
        Type::Tuple(typs) => {
            let typs = typs
                .iter()
                .map(|typ| monomorphize_typ(typ, typ_args))
                .collect();
            Rc::new(RefCell::new(Type::Tuple(typs)))
        }
        Type::Custom(name, args) => {
            let args = args
                .iter()
                .map(|arg| monomorphize_typ(arg, typ_args))
                .collect();
            Rc::new(RefCell::new(Type::Custom(name.clone(), args)))
        }
        Type::Variable(Variable::Unbound(var)) => typ_args.get(var).unwrap().clone(),
        Type::Variable(Variable::Link(to)) => monomorphize_typ(to, typ_args),
        Type::Primitive(_) => poly_typ.clone(),
    }
}

impl MonoBind {
    fn new(name: String, expr: Rc<RefCell<Expr>>, insertion_index: usize) -> Self {
        Self {
            name,
            expr,
            insertion_index,
        }
    }
}