1 --------------------------------------------------------------------------------
3 -- "Make everything as simple as possible, but not simpler".
5 -- This library offers a generic way to write AST transforming
6 -- functions. Macros can take bits of AST as parameters and generate a
7 -- more complex AST with them; but modifying an AST a posteriori is
8 -- much more difficult; typical tasks requiring code walking are
9 -- transformation such as lazy evaluation or Continuation Passing
10 -- Style, but more mundane operations are required in more macros than
11 -- one would thing, such as "transform all returns which aren't inside
12 -- a nested function into an error throwing".
14 -- AST walking is an intrinsically advanced operation, and the
15 -- interface of this library, although it tries to remain as simple as
16 -- possible, is not trivial. You'll probably need to write a couple of
17 -- walkers with it before feeling comfortable.
20 -- We deal here with 3 important kinds of AST: statements, expressions
21 -- and blocks. Code walkers for these three kinds for AST are called
22 -- [walk.stat (cfg, ast)], [walk.expr (cfg, ast)] and [walk.block
23 -- (cfg, ast)] respectively. the [cfg] parameter describes what shall
24 -- happen as the AST is traversed by the walker, and [ast] is the tree
27 -- An aparte to fellow functional programmers: although Lua has
28 -- got all the features that constitute a functional language, its
29 -- heart, and in particular it table data, is imperative. It's often
30 -- asking for trouble to work against the host language's nature, so
31 -- code walkers are imperative, cope with it. Or use table.deep_copy()
32 -- if you don't want issues with shared state.
34 -- Since walkers are imperative (i.e. they transform the tree in
35 -- place, rather than returning a fresh variant of it), you'll often
36 -- want to override a node, i.e. keep its "pointer identity", but
37 -- replace its content with a new one; this is done by
38 -- table.override(), and is conveniently abbreviated as
39 -- "target <- new_content".
41 -- So, [cfg] can contain a series of sub-tables fields 'expr', 'stat',
42 -- 'block'. each of them can contain a function up() and/or a function
45 -- * down() is called when the walker starts visiting a node of the
46 -- matching kind, i.e. before any of its sub-nodes have been
47 -- visited. down() is allowed to return either the string "break",
48 -- which means "don't go further down this tree, don't try to walk
49 -- its children", or nil, i.e. "please process with the children
52 -- There are two reasons why you might want down() to return
53 -- "break": either because you really weren't interested into the
54 -- children nodes,or because you wanted to walk through them in a
55 -- special way, and down() already performed this special walking.
57 -- * up() is called just before the node is left, i.e. after all of
58 -- its children nodes have been completely parsed, down and up. This
59 -- is a good place to put treatments which rely on sub-nodes being
60 -- already treated. Notice that if down() returned 'break', up() is
61 -- run immediately after.
63 -- In previous versions of this library, there were plenty of fancy
64 -- configurable ways to decide whether an up() or down() functions
65 -- would be triggered or not. Experience suggested that the best way
66 -- is to keep it simpler, as done by the current design: the functions
67 -- in sub-table expr are run on each expression node, and ditto for
68 -- stat and block; the user is expected to use the pattern matching
69 -- extension to decide whether to act or not on a given node.
74 -- The version above is a strict subset of the truth: there are a
75 -- couple of other, more advanced features in the library.
77 -- Paths in visitor functions
78 -- --------------------------
79 -- First, up() and down() don't take only one node as a parameter, but
80 -- a series thereof: all the nested expr/stat/block nodes on the way
81 -- up to the ast's root. For instance, when a walker works on
82 -- +{ foo(bar*2+1) } an is on the node +{2}, up() and down() are called
83 -- with arguments (+{bar*2}, +{bar*2+1}, +{foo(bar*2+1)}).
85 -- `Call and `Invoke as statements
86 -- -------------------------------
87 -- `Call and `Invoke are normally expressions, but they can also
88 -- appear as statements. In this case, the cfg.expr.xxx() visitors
89 -- aren't called on them. Sometimes you want to consider tham as
90 -- expressions, sometimes not, and it's much easier to add a special
91 -- case in cfg.stat.xxx() visitors than to determine whether we're in
92 -- a statament's context in cfg.expr.xxx(),
96 -- There are some second class walkers: walk.expr_list() and walk.guess().
98 -- * The first one walks through a list of expressions. Although used
99 -- internally by the other walkers, it remains a second class
100 -- citizen: the list it works on won't appear in the path of nested
101 -- ASTs that's passed to up() and down(). This design choice has
102 -- been made because there's no clear definition of what is or isn't
103 -- an expr list in an AST, and anyway such lists are probably not
104 -- part of metacoders' mental image of an AST, so it's been thought
105 -- best to let people pretend they don't exist.
107 -- * walk.guess() tries to guess the type of the AST it receives,
108 -- according to its tag, and runs the appropriate walker. Node which
109 -- can be both stats and exprs (`Call and `Invoke) are considered as
112 -- These three walkers, although used internally by the other walkers,
113 -- remain second class citizens: the lists they work on won't appear
114 -- in the path of nested ASTs that's passed to up() and down().
118 -- There are two public dictionaries, walk.tags.stat and
119 -- walk.tags.expr, which keep the set of all tags that can start a
120 -- statement or an expression AST. They're used by walk.guess, and
121 -- users sometimes need them as well, so they've been kept available.
125 -- Finally, there's one last field in [cfg]: binder(). This function
126 -- is called on identifiers in a binder position, i.e. `Id{ } nodes
127 -- which create a scoped local variable, in `Function, `Fornum, `Local
128 -- etc. The main use case for that function is to keep track of
129 -- variables, captures, etc. and perform alpha conversions. In many
130 -- cases that work is best done through the library 'walk.id', which
131 -- understands the notions of scope, free variable, bound variable
134 -- Binder visitors are called just before the variable's scope starts,
135 -- e.g. they're called after the right-hand-side has been visited in a
136 -- `Local node, but before in a `Localrec node.
138 --------------------------------------------------------------------------------
140 -{ extension "match" }
142 walk = { traverse = { }; tags = { }; debug = false }
144 --------------------------------------------------------------------------------
145 -- Standard tags: can be used to guess the type of an AST, or to check
146 -- that the type of an AST is respected.
147 --------------------------------------------------------------------------------
148 walk.tags.stat = table.transpose{
149 'Do', 'Set', 'While', 'Repeat', 'Local', 'Localrec', 'Return',
150 'Fornum', 'Forin', 'If', 'Break', 'Goto', 'Label',
152 walk.tags.expr = table.transpose{
153 'Paren', 'Call', 'Invoke', 'Index', 'Op', 'Function', 'Stat',
154 'Table', 'Nil', 'Dots', 'True', 'False', 'Number', 'String', 'Id' }
156 --------------------------------------------------------------------------------
157 -- These [walk.traverse.xxx()] functions are in charge of actually going through
158 -- ASTs. At each node, they make sure to call the appropriate walker.
159 --------------------------------------------------------------------------------
160 function walk.traverse.stat (cfg, x, ...)
161 if walk.debug then printf("traverse stat %s", table.tostring(x)) end
163 local B = |y| walk.block (cfg, y, x, unpack(log))
164 local S = |y| walk.stat (cfg, y, x, unpack(log))
165 local E = |y| walk.expr (cfg, y, x, unpack(log))
166 local EL = |y| walk.expr_list (cfg, y, x, unpack(log))
167 local I = |y| walk.binder_list (cfg, y, x, unpack(log))
169 | {...} if x.tag == nil -> for y in ivalues(x) do walk.stat(cfg, y, ...) end
170 -- no tag --> node not inserted in the history log
172 | `Set{ lhs, rhs } -> EL(lhs); EL(rhs)
173 | `While{ cond, body } -> E(cond); B(body)
174 | `Repeat{ body, cond } -> B(body); E(cond)
175 | `Local{ lhs } -> I(lhs)
176 | `Local{ lhs, rhs } -> EL(rhs); I(lhs)
177 | `Localrec{ lhs, rhs } -> I(lhs); EL(rhs)
178 | `Fornum{ i, a, b, body } -> E(a); E(b); I{i}; B(body)
179 | `Fornum{ i, a, b, c, body } -> E(a); E(b); E(c); I{i}; B(body)
180 | `Forin{ i, rhs, body } -> EL(rhs); I(i); B(body)
181 | `If{...} -> for i=1, #x-1, 2 do E(x[i]); B(x[i+1]) end
182 if #x%2 == 1 then B(x[#x]) end
183 | `Call{...}|`Invoke{...}|`Return{...} -> EL(x)
184 | `Break | `Goto{ _ } | `Label{ _ } -> -- nothing
185 | {...} if walk.tags.stat[x.tag]->
186 printf("Warning: walk: malformed %s stat node: %s", x.tag, table.tostring(x,80))
187 | {...} -> print("Warning: walk: unknown stat node: "..table.tostring(x,80))
188 | _ -> print("Warning: walk: unexpected stat node of type "..type(x)
189 ..": "..table.tostring(x,80))
193 function walk.traverse.expr (cfg, x, ...)
194 if walk.debug then printf("traverse expr %s", table.tostring(x)) end
196 local B = |y| walk.block (cfg, y, x, unpack(log))
197 local S = |y| walk.stat (cfg, y, x, unpack(log))
198 local E = |y| walk.expr (cfg, y, x, unpack(log))
199 local EL = |y| walk.expr_list (cfg, y, x, unpack(log))
200 local I = |y| walk.binder_list (cfg, y, x, unpack(log))
202 | `Paren{ e } -> E(e)
203 | `Call{...} | `Invoke{...} -> EL(x)
204 | `Index{ a, b } -> E(a); E(b)
205 | `Op{ opid, ... } -> E(x[2]); if #x==3 then E(x[3]) end
206 | `Function{ params, body } -> I(params); B(body)
207 | `Stat{ b, e } -> B(b); E(e)
209 for i = 1, #x do match x[i] with
210 | `Pair{ k, v } -> E(k); E(v)
213 |`Nil|`Dots|`True|`False|`Number{_}|`String{_}|`Id{_} -> -- nothing
214 | {...} if walk.tags.expr[x.tag]->
215 printf("Warning: walk: malformed %s expr node: %s", x.tag, table.tostring(x,80))
216 | {...} -> print("Warning: walk: unknown expr node: "..table.tostring(x,80))
217 | _ -> print("Warning: walk: unexpected expr node of type "..type(x)
218 ..": "..table.tostring(x,80))
222 function walk.traverse.block (cfg, x, ...)
223 assert(type(x)=='table', "traverse.block() expects a table")
224 for y in ivalues(x) do walk.stat(cfg, y, x, ...) end
227 function walk.traverse.expr_list (cfg, x, ...)
228 assert(type(x)=='table', "traverse.expr_list() expects a table")
229 -- x doesn't appear in the log
230 for y in ivalues(x) do walk.expr(cfg, y, ...) end
233 ----------------------------------------------------------------------
234 -- Generic walker generator.
235 ----------------------------------------------------------------------
236 local walker_builder = |cfg_field, traverse| function (cfg, x, ...)
237 local sub_cfg = cfg[cfg_field] or { }
240 if sub_cfg.down=='break' then broken='break'
241 else broken = sub_cfg.down (x, ...) end
242 assert(not broken or broken=='break',
243 "Map functions must return 'break' or nil")
245 if not broken then traverse (cfg, x, ...) end
246 if sub_cfg.up then sub_cfg.up (x, ...) end
249 ----------------------------------------------------------------------
250 -- Declare [walk.stat], [walk.expr], [walk.block] and [walk.expr_list]
251 ----------------------------------------------------------------------
252 for w in values{ "stat", "expr", "block", "expr_list" } do
253 walk[w] = walker_builder (w, walk.traverse[w])
256 ----------------------------------------------------------------------
257 -- Walk a list of `Id{...} (mainly a helper function actually).
258 ----------------------------------------------------------------------
259 function walk.binder_list (cfg, x, ...)
261 if f then for v in ivalues(x) do f(v, ...) end end
264 ----------------------------------------------------------------------
265 -- Tries to guess the type of the AST then choose the right walkker.
266 ----------------------------------------------------------------------
267 function walk.guess (cfg, x, ...)
268 assert(type(x)=='table', "arg #2 in a walker must be an AST")
269 if walk.tags.expr[x.tag] then return walk.expr(cfg, x, ...) end
270 if walk.tags.stat[x.tag] then return walk.stat(cfg, x, ...) end
271 if not x.tag then return walk.block(cfg, x, ...) end
272 error ("Can't guess the AST type from tag "..(x.tag or '<none>'))