| 1 |
= ScopeInference |
| 2 |
|
| 3 |
Scope inference is an analysis/rewrite pass for the <<AST#>> |
| 4 |
<<IntermediateLanguage#>>, invoked from <<Elaborate#>>. |
| 5 |
|
| 6 |
== Description |
| 7 |
|
| 8 |
This pass adds free type variables to the `val` or `fun` |
| 9 |
declaration where they are implicitly scoped. |
| 10 |
|
| 11 |
== Implementation |
| 12 |
|
| 13 |
https://github.com/MLton/mlton/blob/master/mlton/elaborate/scope.sig[`scope.sig`] |
| 14 |
https://github.com/MLton/mlton/blob/master/mlton/elaborate/scope.fun[`scope.fun`] |
| 15 |
|
| 16 |
== Details and Notes |
| 17 |
|
| 18 |
Scope inference determines for each type variable, the declaration |
| 19 |
where it is bound. Scope inference is a direct implementation of the |
| 20 |
specification given in section 4.6 of the |
| 21 |
<<DefinitionOfStandardML#,Definition>>. Recall that a free occurrence |
| 22 |
of a type variable `'a` in a declaration `d` is _unguarded_ |
| 23 |
in `d` if `'a` is not part of a smaller declaration. A type |
| 24 |
variable `'a` is implicitly scoped at `d` if `'a` is |
| 25 |
unguarded in `d` and `'a` does not occur unguarded in any |
| 26 |
declaration containing `d`. |
| 27 |
|
| 28 |
The first pass of scope inference walks down the tree and renames all |
| 29 |
explicitly bound type variables in order to avoid name collisions. It |
| 30 |
then walks up the tree and adds to each declaration the set of |
| 31 |
unguarded type variables occurring in that declaration. At this |
| 32 |
point, if declaration `d` contains an unguarded type variable |
| 33 |
`'a` and the immediately containing declaration does not contain |
| 34 |
`'a`, then `'a` is implicitly scoped at `d`. The final |
| 35 |
pass walks down the tree leaving a `'a` at the a declaration where |
| 36 |
it is scoped and removing it from all enclosed declarations. |