Appearance
| 1 | namespace Syntax.Process is | |
| 2 | // Collects the variables written within a walked | |
| 3 | // subtree — by assignment (`=`, including destructuring) or by | |
| 4 | // being passed `ref`. Two consumers, each dropping a narrow on | |
| 5 | // a variable the walked subtree writes: the loop kill-set, where | |
| 6 | // a narrow cannot be assumed across the back-edge, and the entry | |
| 7 | // to a finally body, where a narrow proven before the try | |
| 8 | // survives what the try did not write. | |
| 9 | // | |
| 10 | // A `Visitor` whose default per-node visits are no-ops, so only | |
| 11 | // ASSIGNMENT and REFERENCE need overriding; default `pre` | |
| 12 | // returns false, so the framework descends through everything. | |
| 13 | class LOOP_ASSIGNMENT_COLLECTOR: Visitor is | |
| 14 | names: Collections.SET[string] public | |
| 15 | ||
| 16 | // Targets of assignments that have already been compiled, by the | |
| 17 | // symbol they store to. Only filled when asked for: before a | |
| 18 | // walk, or between walks, an assignment holds no value or a stale | |
| 19 | // one. | |
| 20 | symbols: Collections.SET[Semantic.Symbols.Symbol] public | |
| 21 | _use_resolved_targets: bool | |
| 22 | ||
| 23 | init() is | |
| 24 | init(false) | |
| 25 | si | |
| 26 | ||
| 27 | init(use_resolved_targets: bool) is | |
| 28 | super.init() | |
| 29 | names = Collections.SET[string]() | |
| 30 | symbols = Collections.SET[Semantic.Symbols.Symbol]() | |
| 31 | _use_resolved_targets = use_resolved_targets | |
| 32 | si | |
| 33 | ||
| 34 | // Whether the walk wrote the variable, by symbol where the store | |
| 35 | // was resolved and by name where it was not. | |
| 36 | wrote(variable: Semantic.Symbols.Symbol) -> bool => | |
| 37 | symbols.contains(variable) \/ (variable.name? /\ names.contains(variable.name)) | |
| 38 | ||
| 39 | visit(assignment: Trees.Statements.ASSIGNMENT) is | |
| 40 | if _use_resolved_targets then | |
| 41 | if let store: IR.Values.Store.SYMBOL = assignment.value then | |
| 42 | symbols.add(store.symbol) | |
| 43 | return | |
| 44 | fi | |
| 45 | fi | |
| 46 | ||
| 47 | let targets = Collections.LIST[Trees.Expressions.Expression]() | |
| 48 | assignment.left.get_names_into(targets) | |
| 49 | ||
| 50 | for target in targets do | |
| 51 | _collect(target) | |
| 52 | od | |
| 53 | si | |
| 54 | ||
| 55 | visit(reference: Trees.Expressions.REFERENCE) is | |
| 56 | // `x ref` — a `ref` argument may be written by the callee. | |
| 57 | _collect(reference.left) | |
| 58 | si | |
| 59 | ||
| 60 | _collect(expr: Trees.Expressions.Expression) is | |
| 61 | if !isa Trees.Expressions.IDENTIFIER(expr) then | |
| 62 | return | |
| 63 | fi | |
| 64 | ||
| 65 | let identifier = expr | |
| 66 | ||
| 67 | names.add(identifier.identifier.name) | |
| 68 | si | |
| 69 | si | |
| 70 | si |