1 -- This extension inserts type-checking code at approriate place in the code,
2 -- thanks to annotations based on "::" keyword:
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.
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.
14 -- * Local variables can also be annotated. If they are, type-checking
15 -- code is inserted before any value assignment or re-assignment is
18 -- Type checking can be disabled with:
20 -- -{stat: types.enabled = false }
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.
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.
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])
48 -- This extension uses the code walking library [walk] to globally
49 -- transform the chunk AST. See [chunk_transformer()] for details
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
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
65 --------------------------------------------------------------------------------
67 -- Function chunk_transformer()
69 --------------------------------------------------------------------------------
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.
75 -- It relies on the following annotations:
77 -- * [`Local{ }] statements may have a [types] field, which contains a
78 -- id name ==> type name map.
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.
87 -- It relies on the code walking library, and two states:
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.
93 -- * [scopes] is a stack of id name ==> type name scopes, one per
94 -- currently acive variables scope.
96 -- What's performed by the walker:
98 -- * Assignments to a typed variable involve a type checking of the
101 -- * Local declarations are checked for additional type declarations.
103 -- * Blocks create and destroy variable scopes in [scopes]
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)
109 -- * Return statements get the additional type checking statement if
112 --------------------------------------------------------------------------------
114 -- TODO: unify scopes handling with free variables detector
116 require "metalua.walk"
118 -{ extension 'match' }
120 module("types", package.seeall)
124 local function chunk_transformer (block)
125 if not enabled then return end
126 local return_types, scopes = { }, { }
127 local cfg = { block = { }; stat = { }; expr = { } }
129 function cfg.stat.down (x)
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)
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')
146 | `Set{ lhs, rhs } ->
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
158 | `Return{ r_val } ->
159 local r_type = return_types[#return_types]
161 x <- `Return{ checktype_builder (r_type, r_val, 'expr') }
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)
174 local r_type = x.ret_type and process_type (x.ret_type) or false
175 table.insert (return_types, r_type)
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'))
195 cfg.block.down = || table.insert (scopes, { })
196 cfg.block.up = || table.remove (scopes)
198 walk.block(cfg, block)
201 --------------------------------------------------------------------------
202 -- Perform required transformations to change a raw type expression into
203 -- a callable function:
205 -- * identifiers are changed into indexes in [types], unless they're
206 -- allready indexed, or into parentheses;
208 -- * literal tables are embedded into a call to types.__table
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:
219 function cfg.expr.down(x)
221 | `Index{...} | `Paren{...} -> return 'break'
225 function cfg.expr.up (x)
227 | `Id{i} -> x <- `Index{ `Id "types", `String{ i } }
228 | `Table{...} | `String{...} | `Op{...} ->
229 local xcopy, name = table.shallow_copy(x)
231 | 'Table' -> name = '__table'
232 | 'String' -> name = '__string'
233 | 'Op' -> name = '__'..x[1]
235 x <- `Call{ `Index{ `Id "types", `String{ name } }, xcopy }
236 | `Function{ params, { results } } if results.tag=='Return' ->
238 x <- `Call{ +{types.__function}, params, results }
239 | `Function{...} -> error "malformed function type"
243 walk.expr(cfg, type_term)
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:
256 | 'expr' if non_const_tags [term.tag] ->
257 local v = mlp.gensym()
258 return `Stat{ { `Local{ {v}, {term} }; `Call{ type, v } }, v }
260 return `Stat{ { `Call{ type, term } }, term }
262 return `Call{ type, term }
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 }
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")
280 local param, type = unpack(y)
282 if type then e.param_types[param[1]] = type end
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 }
293 --------------------------------------------------------------------------
294 -- Updated function definition parser, which accepts typed vars as
296 --------------------------------------------------------------------------
298 -- Parameters parsing:
299 local id_or_dots = gg.multisequence{ { "...", builder = "Dots" }, default = mlp.id }
302 mlp.func_val = gg.sequence{
304 gg.sequence{ id_or_dots, opt_type }, terminators = ")", separators = "," },
305 ")", opt_type, mlp.block, "end",
306 builder = func_val_builder }
308 mlp.lexer:add { "::", "newtype" }
309 mlp.chunk.transformers:add (chunk_transformer)
311 -- Local declarations parsing:
312 local local_decl_parser = mlp.stat:get "local" [2].default
314 local_decl_parser[1].primary = gg.sequence{ mlp.id, opt_type }
316 function local_decl_parser.builder(x)
317 local lhs, rhs = unpack(x)
318 local s, stypes = `Local{ { }, rhs or { } }, { }
320 local id, type = unpack(lhs[i])
322 if type then stypes[id[1]]=type end
324 if next(stypes) then s.types = stypes end
328 function newtype_builder(x)
329 local lhs, rhs = unpack(x)
331 | `Id{ x } -> t = process_type (rhs)
332 | `Call{ `Id{ x }, ... } ->
333 t = `Function{ { }, rhs }
335 if lhs[i].tag ~= "Id" then error "Invalid newtype parameter" end
338 | _ -> error "Invalid newtype definition"
340 return `Let{ { `Index{ `Id "types", `String{ x } } }, { t } }
343 mlp.stat:add{ "newtype", mlp.expr, "=", mlp.expr, builder = newtype_builder }
346 --------------------------------------------------------------------------
347 -- Register as an operator
348 --------------------------------------------------------------------------
349 --mlp.expr.infix:add{ "::", prec=100, builder = |a, _, b| insert_test(a,b) }
351 +{ require (-{ `String{ package.metalua_extension_prefix .. 'types-runtime' } }) }