|
| 1 | +# Aliases |
| 2 | + |
| 3 | +This document explains module/class aliases and type aliases. |
| 4 | + |
| 5 | +## Module/class alias |
| 6 | + |
| 7 | +Module/class aliases give another name to a module/class. |
| 8 | +This is useful for some syntaxes that has lexical constraints. |
| 9 | + |
| 10 | +```rbs |
| 11 | +class C |
| 12 | +end |
| 13 | +
|
| 14 | +class D = C # ::D is an alias for ::C |
| 15 | +
|
| 16 | +class E < D # ::E inherits from ::D, which is actually ::C |
| 17 | +end |
| 18 | +``` |
| 19 | + |
| 20 | +Note that module/class aliases cannot be recursive. |
| 21 | + |
| 22 | +So, we can define a *normalization* of aliased module/class names. |
| 23 | +Normalization follows the chain of alias definitions and resolves them to the original module/class defined with `module`/`class` syntax. |
| 24 | + |
| 25 | +```rbs |
| 26 | +class C |
| 27 | +end |
| 28 | +
|
| 29 | +class D = C |
| 30 | +class E = D |
| 31 | +``` |
| 32 | + |
| 33 | +`::E` is defined as an alias, and it can be normalized to `::C`. |
| 34 | + |
| 35 | +## Type alias |
| 36 | + |
| 37 | +The biggest difference from module/class alias is that type alias can be recursive. |
| 38 | + |
| 39 | +```rbs |
| 40 | +# cons_cell type is defined recursively |
| 41 | +type cons_cell = nil |
| 42 | + | [Integer, cons_cell] |
| 43 | +``` |
| 44 | + |
| 45 | +This means type aliases *cannot be* normalized generally. |
| 46 | +So, we provide another operation for type alias, `DefinitionBuilder#expand_alias` and its family. |
| 47 | +It substitutes with the immediate right hand side of a type alias. |
| 48 | + |
| 49 | +``` |
| 50 | +cons_cell ===> nil | [Integer, cons_cell] (expand 1 step) |
| 51 | + ===> nil | [Integer, nil | [Integer, cons_cell]] (expand 2 steps) |
| 52 | + ===> ... (expand will go infinitely) |
| 53 | +``` |
| 54 | + |
| 55 | +Note that the namespace of a type alias *can be* normalized, because they are module names. |
| 56 | + |
| 57 | +```rbs |
| 58 | +module M |
| 59 | + type t = String |
| 60 | +end |
| 61 | +
|
| 62 | +module N = M |
| 63 | +``` |
| 64 | + |
| 65 | +With the type definition above, a type `::N::t` can be normalized to `::M::t`. |
| 66 | +And then it can be expanded to `::String`. |
| 67 | + |
| 68 | +> [!NOTE] |
| 69 | +> This is something like an *unfold* operation in type theory. |
| 70 | +
|
| 71 | +## Type name resolution |
| 72 | + |
| 73 | +Type name resolution in RBS usually rewrites *relative* type names to *absolute* type names. |
| 74 | +`Environment#resolve_type_names` converts all type names in the RBS type definitions, and returns a new `Environment` object. |
| 75 | + |
| 76 | +It also *normalizes* modules names in type names. |
| 77 | + |
| 78 | +- If the type name can be resolved and normalized successfully, the AST has *absolute* type names. |
| 79 | +- If the type name resolution/normalization fails, the AST has *relative* type names. |
0 commit comments