]> git.lizzy.rs Git - metalua.git/blob - src/lib/metalua/extension/types.mlua
fixes in extension libs
[metalua.git] / src / lib / metalua / extension / types.mlua
1 -- This extension inserts type-checking code at approriate place in the code,
2 -- thanks to annotations based on "::" keyword:
3 --
4 -- * function declarations can be annotated with a returned type. When they
5 --   are, type-checking code is inserted in each of their return statements,
6 --   to make sure they return the expected type.
7 --
8 -- * function parameters can also be annotated. If they are, type-checking
9 --   code is inserted in the function body, which checks the arguments' types
10 --   and cause an explicit error upon incorrect calls. Moreover, if a new value
11 --   is assigned to the parameter in the function's body, the new value's type
12 --   is checked before the assignment is performed.
13 --
14 -- * Local variables can also be annotated. If they are, type-checking
15 --   code is inserted before any value assignment or re-assignment is
16 --   performed on them.
17 --
18 -- Type checking can be disabled with:
19 --
20 -- -{stat: types.enabled = false }
21 --
22 -- Code transformation is performed at the chunk level, i.e. file by
23 -- file.  Therefore, it the value of compile-time variable
24 -- [types.enabled] changes in the file, the only value that counts is
25 -- its value once the file is entirely parsed.
26 --
27 -- Syntax
28 -- ======
29 --
30 -- Syntax annotations consist of "::" followed by a type
31 -- specifier. They can appear after a function parameter name, after
32 -- the closing parameter parenthese of a function, or after a local
33 -- variable name in the declaration. See example in samples.
34 --
35 -- Type specifiers are expressions, in which identifiers are taken
36 -- from table types. For instance, [number] is transformed into
37 -- [types.number]. These [types.xxx] fields must contain functions,
38 -- which generate an error when they receive an argument which doesn't
39 -- belong to the type they represent. It is perfectly acceptible for a
40 -- type-checking function to return another type-checking function,
41 -- thus defining parametric/generic types. Parameters can be
42 -- identifiers (they're then considered as indexes in table [types])
43 -- or literals.
44 --
45 -- Design hints
46 -- ============
47 --
48 -- This extension uses the code walking library [walk] to globally
49 -- transform the chunk AST. See [chunk_transformer()] for details
50 -- about the walker.
51 --
52 -- During parsing, type informations are stored in string-indexed
53 -- fields, in the AST nodes of tags `Local and `Function. They are
54 -- used by the walker to generate code only if [types.enabled] is
55 -- true.
56 --
57 -- TODO
58 -- ====
59 --
60 -- It's easy to add global vars type-checking, by declaring :: as an
61 -- assignment operator.  It's easy to add arbitrary expr
62 -- type-checking, by declaring :: as an infix operator. How to make
63 -- both cohabit?
64
65 --------------------------------------------------------------------------------
66 --
67 -- Function chunk_transformer()
68 --
69 --------------------------------------------------------------------------------
70 --
71 -- Takes a block annotated with extra fields, describing typing
72 -- constraints, and returns a normal AST where these constraints have
73 -- been turned into type-checking instructions.
74 --
75 -- It relies on the following annotations:
76 --
77 --  * [`Local{ }] statements may have a [types] field, which contains a
78 --    id name ==> type name map.
79 --
80 --  * [Function{ }] expressions may have an [param_types] field, also a
81 --    id name ==> type name map. They may also have a [ret_type] field
82 --    containing the type of the returned value.
83 --
84 -- Design hints:
85 -- =============
86 --
87 -- It relies on the code walking library, and two states:
88 --
89 --  * [return_types] is a stack of the expected return values types for
90 --    the functions currently in scope, the most deeply nested one
91 --    having the biggest index.
92 --
93 --  * [scopes] is a stack of id name ==> type name scopes, one per
94 --    currently acive variables scope.
95 --
96 -- What's performed by the walker:
97 --
98 --  * Assignments to a typed variable involve a type checking of the
99 --    new value;
100 --
101 --  * Local declarations are checked for additional type declarations.
102 --
103 --  * Blocks create and destroy variable scopes in [scopes]
104 --
105 --  * Functions create an additional scope (around its body block's scope)
106 --    which retains its argument type associations, and stacks another
107 --    return type (or [false] if no type constraint is given)
108 --
109 --  * Return statements get the additional type checking statement if
110 --    applicable.
111 --
112 --------------------------------------------------------------------------------
113
114 -- TODO: unify scopes handling with free variables detector
115
116 require "metalua.walk"
117
118 -{ extension 'match' }
119
120 module("types", package.seeall)
121
122 enabled = true
123
124 local function chunk_transformer (block)
125    if not enabled then return end
126    local return_types, scopes = { }, { }
127    local cfg = { block = { }; stat = { }; expr = { } }
128
129    function cfg.stat.down (x)
130       match x with
131       | `Local{ lhs, rhs, types = x_types } ->
132          -- Add new types declared by lhs in current scope.
133          local myscope = scopes [#scopes]
134          for var, type in pairs (x_types) do
135             myscope [var] = process_type (type)
136          end
137          -- Type-check each rhs value with the type of the
138          -- corresponding lhs declaration, if any.  Check backward, in
139          -- case a local var name is used more than once.
140          for i = 1, max (#lhs, #rhs) do
141             local type, new_val = myscope[lhs[i][1]], rhs[i]
142             if type and new_val then
143                rhs[i] = checktype_builder (type, new_val, 'expr')
144             end
145          end
146       | `Set{ lhs, rhs } ->
147          for i=1, #lhs do
148             match lhs[i] with
149             | `Id{ v } ->
150                -- Retrieve the type associated with the variable, if any:
151                local  j, type = #scopes, nil
152                repeat j, type = j-1, scopes[j][v] until type or j==0
153                -- If a type constraint is found, apply it:
154                if type then rhs[i] = checktype_builder(type, rhs[i] or `Nil, 'expr') end
155             | _ -> -- assignment to a non-variable, pass
156             end
157          end
158       | `Return{ r_val } ->
159          local r_type = return_types[#return_types]
160          if r_type then
161             x <- `Return{ checktype_builder (r_type, r_val, 'expr') }
162          end
163       | _ -> -- pass
164       end
165    end
166
167    function cfg.expr.down (x)
168       if x.tag ~= 'Function' then return end
169       local new_scope = { }
170       table.insert (scopes, new_scope)
171       for var, type in pairs (x.param_types or { }) do
172          new_scope[var] = process_type (type)
173       end
174       local r_type = x.ret_type and process_type (x.ret_type) or false
175       table.insert (return_types, r_type)
176    end
177
178    -------------------------------------------------------------------
179    -- Unregister the returned type and the variable scope in which
180    -- arguments are registered;
181    -- then, adds the parameters type checking instructions at the
182    -- beginning of the function, if applicable.
183    -------------------------------------------------------------------
184    function cfg.expr.up (x)
185       if x.tag ~= 'Function' then return end
186       -- Unregister stuff going out of scope:
187       table.remove (return_types)
188       table.remove (scopes)
189       -- Add initial type checking:
190       for v, t in pairs(x.param_types or { }) do
191          table.insert(x[2], 1, checktype_builder(t, `Id{v}, 'stat'))
192       end
193    end
194
195    cfg.block.down = || table.insert (scopes, { })
196    cfg.block.up   = || table.remove (scopes)
197
198    walk.block(cfg, block)
199 end
200
201 --------------------------------------------------------------------------
202 -- Perform required transformations to change a raw type expression into
203 -- a callable function:
204 --
205 --  * identifiers are changed into indexes in [types], unless they're
206 --    allready indexed, or into parentheses;
207 --
208 --  * literal tables are embedded into a call to types.__table
209 --
210 -- This transformation is not performed when type checking is disabled:
211 -- types are stored under their raw form in the AST; the transformation is
212 -- only performed when they're put in the stacks (scopes and return_types)
213 -- of the main walker.
214 --------------------------------------------------------------------------
215 function process_type (type_term)
216    -- Transform the type:
217    cfg = { expr = { } }
218
219    function cfg.expr.down(x)
220       match x with
221       | `Index{...} | `Paren{...} -> return 'break'
222       | _ -> -- pass
223       end
224    end
225    function cfg.expr.up (x)
226       match x with
227       | `Id{i} -> x <- `Index{ `Id "types", `String{ i } }
228       | `Table{...} | `String{...} | `Op{...} ->
229          local xcopy, name = table.shallow_copy(x)
230          match x.tag with
231          | 'Table'  -> name = '__table'
232          | 'String' -> name = '__string'
233          | 'Op'     -> name = '__'..x[1]
234          end
235          x <- `Call{ `Index{ `Id "types", `String{ name } }, xcopy }
236       | `Function{ params, { results } } if results.tag=='Return' ->
237          results.tag = nil
238          x <- `Call{ +{types.__function}, params, results }
239       | `Function{...} -> error "malformed function type"
240       | _ -> -- pass
241       end
242    end
243    walk.expr(cfg, type_term)
244    return type_term
245 end
246
247 --------------------------------------------------------------------------
248 -- Insert a type-checking function call on [term] before returning
249 -- [term]'s value. Only legal in an expression context.
250 --------------------------------------------------------------------------
251 local non_const_tags = table.transpose
252    { 'Dots', 'Op', 'Index', 'Call', 'Invoke', 'Table' }
253 function checktype_builder(type, term, kind)
254    -- Shove type-checking code into the term to check:
255    match kind with
256    | 'expr' if non_const_tags [term.tag] ->
257       local  v = mlp.gensym()
258       return `Stat{ { `Local{ {v}, {term} }; `Call{ type, v } }, v }
259    | 'expr' ->
260       return `Stat{ { `Call{ type, term } }, term }
261    | 'stat' ->
262       return `Call{ type, term }
263    end
264 end
265
266 --------------------------------------------------------------------------
267 -- Parse the typechecking tests in a function definition, and adds the
268 -- corresponding tests at the beginning of the function's body.
269 --------------------------------------------------------------------------
270 local function func_val_builder (x)
271    local typed_params, ret_type, body = unpack(x)
272    local e = `Function{ { }, body; param_types = { }; ret_type = ret_type }
273
274    -- Build [untyped_params] list, and [e.param_types] dictionary.
275    for i, y in ipairs (typed_params) do
276       if y.tag=="Dots" then
277          assert(i==#typed_params, "`...' must be the last parameter")
278          break
279       end
280       local param, type = unpack(y)
281       e[1][i] = param
282       if type then e.param_types[param[1]] = type end
283    end
284    return e
285 end
286
287 --------------------------------------------------------------------------
288 -- Parse ":: type" annotation if next token is "::", or return false.
289 -- Called by function parameters parser
290 --------------------------------------------------------------------------
291 local opt_type = gg.onkeyword{ "::", mlp.expr }
292
293 --------------------------------------------------------------------------
294 -- Updated function definition parser, which accepts typed vars as
295 -- parameters.
296 --------------------------------------------------------------------------
297
298 -- Parameters parsing:
299 local id_or_dots = gg.multisequence{ { "...", builder = "Dots" }, default = mlp.id }
300
301 -- Function parsing:
302 mlp.func_val = gg.sequence{
303    "(", gg.list{
304       gg.sequence{ id_or_dots, opt_type }, terminators = ")", separators  = "," },
305    ")",  opt_type, mlp.block, "end",
306    builder = func_val_builder }
307
308 mlp.lexer:add { "::", "newtype" }
309 mlp.chunk.transformers:add (chunk_transformer)
310
311 -- Local declarations parsing:
312 local local_decl_parser = mlp.stat:get "local" [2].default
313
314 local_decl_parser[1].primary = gg.sequence{ mlp.id, opt_type }
315
316 function local_decl_parser.builder(x)
317    local lhs, rhs = unpack(x)
318    local s, stypes = `Local{ { }, rhs or { } }, { }
319    for i = 1, #lhs do
320       local id, type = unpack(lhs[i])
321       s[1][i] = id
322       if type then stypes[id[1]]=type end
323    end
324    if next(stypes) then s.types = stypes end
325    return s
326 end
327
328 function newtype_builder(x)
329    local lhs, rhs = unpack(x)
330    match lhs with
331    | `Id{ x } -> t = process_type (rhs)
332    | `Call{ `Id{ x }, ... } ->
333       t = `Function{ { }, rhs }
334       for i = 2, #lhs do
335          if lhs[i].tag ~= "Id" then error "Invalid newtype parameter" end
336          t[1][i-1] = lhs[i]
337       end
338    | _ -> error "Invalid newtype definition"
339    end
340    return `Let{ { `Index{ `Id "types", `String{ x } } }, { t } }
341 end
342
343 mlp.stat:add{ "newtype", mlp.expr, "=", mlp.expr, builder = newtype_builder }
344
345
346 --------------------------------------------------------------------------
347 -- Register as an operator
348 --------------------------------------------------------------------------
349 --mlp.expr.infix:add{ "::", prec=100, builder = |a, _, b| insert_test(a,b) }
350
351 +{ require (-{ `String{ package.metalua_extension_prefix .. 'types-runtime' } }) }