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
use itertools::Itertools;

use crate::base::{
    ast::{
        self, AstType, DisplayEnv, Do, Expr, MutVisitor, Pattern, SpannedAlias, SpannedExpr,
        TypedIdent,
    },
    fnv::FnvMap,
    pos::{self, ByteOffset, BytePos, Span},
    scoped_map::ScopedMap,
    source::Source,
    symbol::{Symbol, SymbolData, SymbolModule},
    types::{ArcType, Type},
};

struct Environment {
    stack: ScopedMap<Symbol, (Symbol, Span<BytePos>)>,
}

pub fn rename<'s, 'ast>(
    source: &'s (dyn Source + 's),
    symbols: &mut SymbolModule,
    ast_arena: ast::ArenaRef<'s, 'ast, Symbol>,
    expr: &mut SpannedExpr<'ast, Symbol>,
) {
    enum TailCall {
        TailCall,
        Return,
    }

    struct RenameVisitor<'a: 'b, 'b, 's, 'ast> {
        source: &'s (dyn Source + 's),
        symbols: &'b mut SymbolModule<'a>,
        seen_symbols: FnvMap<Symbol, u32>,
        scope: Vec<Symbol>,
        env: Environment,
        ast_arena: ast::ArenaRef<'s, 'ast, Symbol>,
        hole: ArcType,
    }

    impl<'a, 'b, 's, 'ast> RenameVisitor<'a, 'b, 's, 'ast> {
        fn new_pattern(&mut self, pattern: &mut ast::SpannedPattern<Symbol>) {
            match pattern.value {
                Pattern::Record {
                    ref mut fields,
                    ref mut implicit_import,
                    ..
                } => {
                    for (name, value) in ast::pattern_values_mut(fields) {
                        match value {
                            Some(pat) => self.new_pattern(pat),
                            None => {
                                let id = name.value.clone();
                                name.value = self.stack_var(id, pattern.span);
                            }
                        }
                    }
                    if let Some(ref mut implicit_import) = *implicit_import {
                        let new_name =
                            self.stack_var(implicit_import.value.clone(), implicit_import.span);
                        implicit_import.value = new_name;
                    }
                }
                Pattern::Ident(ref mut id) => {
                    let new_name = self.stack_var(id.name.clone(), pattern.span);
                    id.name = new_name;
                }
                Pattern::As(ref mut id, ref mut pat) => {
                    let new_name = self.stack_var(id.value.clone(), pattern.span);
                    id.value = new_name;
                    self.new_pattern(pat)
                }
                Pattern::Tuple { ref mut elems, .. } => {
                    for elem in &mut **elems {
                        self.new_pattern(elem);
                    }
                }
                Pattern::Constructor(_, ref mut args) => {
                    for arg in &mut **args {
                        self.new_pattern(arg);
                    }
                }
                Pattern::Literal(_) | Pattern::Error => (),
            }
        }

        // Renames the symbol to be unique in this module
        fn stack_var(&mut self, id: Symbol, span: Span<BytePos>) -> Symbol {
            let mut location = self
                .source
                .location(span.start())
                .map(|location| (location.line.0 + 1, location.column.0 + 1))
                .unwrap_or_else(|| (span.start().0, 0));
            let new_id = self.symbols.symbol(SymbolData {
                global: false,
                name: id.as_str(),
                location: Some(location),
            });

            let index = self.seen_symbols.entry(new_id.clone()).or_default();
            let new_id = if *index == 0 {
                *index += 1;
                new_id
            } else {
                // TODO More reliable way of generating unique symbols
                *index += 1;
                location.1 += *index;
                self.symbols.symbol(SymbolData {
                    global: false,
                    name: id.as_str(),
                    location: Some(location),
                })
            };

            debug!("Rename binding `{:?}` = `{:?}`", id, new_id);

            self.env.stack.insert(id, (new_id.clone(), span));

            new_id
        }

        fn stack_type(&mut self, span: Span<BytePos>, alias: &mut SpannedAlias<Symbol>) {
            let new = self.symbols.scoped_symbol(alias.value.name.declared_name());
            self.env
                .stack
                .insert(alias.value.name.clone(), (new.clone(), span));
            alias.value.name = new;
        }

        /// Renames `id` to the unique identifier which have the type `expected`
        /// Returns `Some(new_id)` if renaming was necessary or `None` if no renaming was necessary
        /// as `id` was currently unique (#Int+, #Float*, etc)
        fn rename(&self, id: &Symbol) -> Option<Symbol> {
            self.env.stack.get(id).map(|t| t.0.clone())
        }

        fn rename_expr(&mut self, expr: &mut SpannedExpr<'ast, Symbol>) -> TailCall {
            match expr.value {
                Expr::Ident(ref mut id)
                    // FIXME Still allow renaming of variants somehow without causing resolution
                    // problems with types
                    if !id.name.declared_name().starts_with(char::is_uppercase) =>
                {
                    if let Some(new_id) = self.rename(&id.name) {
                        id.name = new_id;
                    }
                }
                Expr::Record {
                    ref mut exprs,
                    ref mut base,
                    ..
                } => {
                    for expr_field in &mut **exprs {
                        match expr_field.value {
                            Some(ref mut expr) => self.visit_expr(expr),
                            None => {
                                if let Some(new_id) = self.rename(&expr_field.name.value) {
                                    debug!("Rename record field {} = {}", expr_field.name, new_id);
                                    expr_field.name.value = new_id;
                                }
                            }
                        }
                    }

                    if let Some(ref mut base) = *base {
                        self.visit_expr(base);
                    }
                }
                Expr::Infix {
                    ref mut lhs,
                    ref mut op,
                    ref mut rhs,
                    ref mut implicit_args,
                } => {
                    if let Some(new_id) = self.rename(&op.value.name) {
                        debug!(
                            "Rename {} = {}",
                            self.symbols.string(&op.value.name),
                            self.symbols.string(&new_id)
                        );
                        op.value.name = new_id;
                    }
                    self.visit_expr(lhs);
                    self.visit_expr(rhs);
                    for arg in &mut **implicit_args {
                        self.visit_expr(arg);
                    }
                }
                Expr::Match(ref mut expr, ref mut alts) => {
                    self.visit_expr(expr);
                    for alt in &mut **alts {
                        self.env.stack.enter_scope();
                        self.new_pattern(&mut alt.pattern);
                        self.visit_expr(&mut alt.expr);
                        self.env.stack.exit_scope();
                    }
                }
                Expr::LetBindings(ref mut bindings, _) => {
                    self.env.stack.enter_scope();

                    let is_recursive = bindings.is_recursive();

                    for bind in bindings.iter_mut() {
                        if !is_recursive {
                            if let Pattern::Ident(id) = &bind.name.value {
                                self.scope.push(id.name.clone());
                            }

                            self.visit_expr(&mut bind.expr);

                            if let Pattern::Ident(_) = &bind.name.value {
                                self.scope.pop();
                            }
                        }
                        if let Some(ref mut typ) = bind.typ {
                            self.visit_ast_type(typ)
                        }
                        self.new_pattern(&mut bind.name);
                    }

                    if is_recursive {
                        for bind in bindings {
                            self.env.stack.enter_scope();
                            for arg in &mut *bind.args {
                                arg.name.value.name =
                                    self.stack_var(arg.name.value.name.clone(), arg.name.span);
                            }

                            if let Pattern::Ident(id) = &bind.name.value {
                                self.scope.push(id.name.clone());
                            }

                            self.visit_expr(&mut bind.expr);

                            if let Pattern::Ident(_) = &bind.name.value {
                                self.scope.pop();
                            }

                            self.env.stack.exit_scope();
                        }
                    }

                    return TailCall::TailCall;
                }
                Expr::Lambda(ref mut lambda) => {
                    let location = self.source.location(expr.span.start()).unwrap_or_else(|| ice!("Lambda without source location"));
                    let name = format!(
                        "{}.{}",
                        self.symbols.module(),
                        self.scope.iter().map(|s| s.as_str()).format("."),
                    );
                    lambda.id.name = self.symbols.symbol(SymbolData {
                        global: false,
                        location: Some((location.line.0 + 1, location.column.0 + 1)),
                        name,
                    });

                    self.env.stack.enter_scope();

                    for arg in &mut *lambda.args {
                        arg.name.value.name =
                            self.stack_var(arg.name.value.name.clone(), expr.span);
                    }

                    self.visit_expr(&mut lambda.body);

                    self.env.stack.exit_scope();
                }
                Expr::TypeBindings(ref mut bindings, _) => {
                    self.env.stack.enter_scope();
                    for bind in &mut **bindings {
                        self.stack_type(expr.span, &mut bind.alias);
                    }
                    for bind in &mut **bindings {
                        self.visit_alias(&mut bind.alias);
                    }

                    return TailCall::TailCall;
                }
                Expr::Do(Do {
                    ref mut id,
                    ref mut bound,
                    ref mut flat_map_id,
                    ..
                }) => {
                    let flat_map = self.symbols.simple_symbol("flat_map");
                    *flat_map_id = Some(self.ast_arena.alloc(pos::spanned(
                        Span::new(expr.span.end(), expr.span.start() + ByteOffset::from(2)),
                        Expr::Ident(TypedIdent {
                            name: flat_map,
                            typ: self.hole.clone(),
                        }),
                    )));

                    let flat_map_id = flat_map_id
                        .as_mut()
                        .unwrap_or_else(|| ice!("flat_map_id not set before renaming"));

                    self.visit_expr(flat_map_id);
                    self.visit_expr(bound);

                    self.env.stack.enter_scope();

                    if let Some(ref mut id) = *id {
                        self.visit_pattern(id);
                    }

                    return TailCall::TailCall;
                }

                _ => ast::walk_mut_expr(self, expr),
            }
            TailCall::Return
        }
    }

    impl<'a, 'b, 'c, 's, 'ast> MutVisitor<'c, 'ast> for RenameVisitor<'a, 'b, 's, 'ast> {
        type Ident = Symbol;

        fn visit_pattern(&mut self, pattern: &mut ast::SpannedPattern<'ast, Symbol>) {
            self.new_pattern(pattern);
        }

        fn visit_expr(&mut self, mut expr: &mut SpannedExpr<'ast, Self::Ident>) {
            let mut i = 0;
            loop {
                match self.rename_expr(expr) {
                    TailCall::Return => break,
                    TailCall::TailCall => {
                        expr = match { expr }.value {
                            Expr::LetBindings(_, ref mut new_expr)
                            | Expr::TypeBindings(_, ref mut new_expr)
                            | Expr::Do(Do {
                                body: ref mut new_expr,
                                ..
                            }) => new_expr,
                            _ => ice!("Only Let and Type expressions can tailcall"),
                        };
                        i += 1;
                    }
                }
            }

            for _ in 0..i {
                self.env.stack.exit_scope();
            }
        }

        fn visit_ast_type(&mut self, s: &'c mut AstType<'ast, Self::Ident>) {
            match &mut **s {
                Type::ExtendTypeRow { types, .. } => {
                    for field in &mut **types {
                        if let Some(alias) = field.typ.try_get_alias_mut() {
                            if let Some(new_name) = self.rename(&field.name.value) {
                                alias.name = new_name;
                            }
                        }
                    }
                }
                Type::Projection(ids) => {
                    // The first id refers to a local variable so we need to rename it
                    if let Some(new_id) = self.rename(&mut ids[0]) {
                        ids[0] = new_id;
                    }
                }
                Type::Ident(id) => {
                    if let Some(new_id) = self.rename(&id.name) {
                        id.name = new_id;
                    }
                }
                _ => (),
            }
            ast::walk_mut_ast_type(self, s)
        }
    }

    let mut visitor = RenameVisitor {
        source,
        symbols: symbols,
        seen_symbols: Default::default(),
        scope: Vec::new(),
        env: Environment {
            stack: ScopedMap::new(),
        },
        ast_arena,
        hole: Type::hole(),
    };
    visitor.visit_expr(expr);
}