6 ast_to_string = |x| M.run(x)
8 --------------------------------------------------------------------------------
9 -- Instanciate a new AST->source synthetizer
10 --------------------------------------------------------------------------------
13 _acc = { }, -- Accumulates pieces of source as strings
14 current_indent = 0, -- Current level of line indentation
15 indent_step = " " -- Indentation symbol, normally spaces or '\t'
17 return setmetatable (self, M)
20 --------------------------------------------------------------------------------
21 -- Run a synthetizer on the `ast' arg and return the source as a string.
22 -- Can also be used as a static method `M.run (ast)'; in this case,
23 -- a temporary Metizer is instanciated on the fly.
24 --------------------------------------------------------------------------------
27 self, ast = M.new(), self
31 return table.concat (self._acc)
34 --------------------------------------------------------------------------------
35 -- Accumulate a piece of source file in the synthetizer.
36 --------------------------------------------------------------------------------
38 if x then table.insert (self._acc, x) end
41 --------------------------------------------------------------------------------
42 -- Accumulate an indented newline.
43 -- Jumps an extra line if indentation is 0, so that
44 -- toplevel definitions are separated by an extra empty line.
45 --------------------------------------------------------------------------------
47 if self.current_indent == 0 then self:acc "\n" end
48 self:acc ("\n" .. self.indent_step:rep (self.current_indent))
51 --------------------------------------------------------------------------------
52 -- Increase indentation and accumulate a new line.
53 --------------------------------------------------------------------------------
54 function M:nlindent ()
55 self.current_indent = self.current_indent + 1
59 --------------------------------------------------------------------------------
60 -- Decrease indentation and accumulate a new line.
61 --------------------------------------------------------------------------------
62 function M:nldedent ()
63 self.current_indent = self.current_indent - 1
64 self:acc ("\n" .. self.indent_step:rep (self.current_indent))
67 --------------------------------------------------------------------------------
68 -- Keywords, which are illegal as identifiers.
69 --------------------------------------------------------------------------------
70 local keywords = table.transpose {
71 "and", "break", "do", "else", "elseif",
72 "end", "false", "for", "function", "if",
73 "in", "local", "nil", "not", "or",
74 "repeat", "return", "then", "true", "until",
77 --------------------------------------------------------------------------------
78 -- Return true iff string `id' is a legal identifier name.
79 --------------------------------------------------------------------------------
80 local function is_ident (id)
81 return id:strmatch "^[%a_][%w_]*$" and not keywords[id]
84 --------------------------------------------------------------------------------
85 -- Return true iff ast represents a legal function name for
86 -- syntax sugar ``function foo.bar.gnat() ... end'':
87 -- a series of nested string indexes, with an identifier as
88 -- the innermost node.
89 --------------------------------------------------------------------------------
90 local function is_idx_stack (ast)
92 | `Id{ _ } -> return true
93 | `Index{ left, `String{ _ } } -> return is_idx_stack (left)
98 --------------------------------------------------------------------------------
99 -- Operator precedences, in increasing order.
100 -- This is not directly used, it's used to generate op_prec below.
101 --------------------------------------------------------------------------------
104 { "lt", "le", "eq", "ne" },
107 { "mul", "div", "mod" },
108 { "unary", "not", "len" },
112 --------------------------------------------------------------------------------
113 -- operator --> precedence table, generated from op_preprec.
114 --------------------------------------------------------------------------------
117 for prec, ops in ipairs (op_preprec) do
118 for op in ivalues (ops) do
123 --------------------------------------------------------------------------------
124 -- operator --> source representation.
125 --------------------------------------------------------------------------------
127 add = " + ", sub = " - ", mul = " * ",
128 div = " / ", mod = " % ", pow = " ^ ",
129 concat = " .. ", eq = " == ", ne = " ~= ",
130 lt = " < ", le = " <= ", ["and"] = " and ",
131 ["or"] = " or ", ["not"] = "not ", len = "# " }
133 --------------------------------------------------------------------------------
134 -- Accumulate the source representation of AST `node' in
135 -- the synthetizer. Most of the work is done by delegating to
136 -- the method having the name of the AST tag.
137 -- If something can't be converted to normal sources, it's
138 -- instead dumped as a `-{ ... }' splice in the source accumulator.
139 --------------------------------------------------------------------------------
140 function M:node (node)
141 assert (self~=M and self._acc)
142 if not node.tag then -- tagless block.
143 self:list (node, self.nl)
145 local f = M[node.tag]
146 if type (f) == "function" then -- Delegate to tag method.
147 f (self, node, unpack (node))
148 elseif type (f) == "string" then -- tag string.
150 else -- No appropriate method, fall back to splice dumping.
151 -- This cannot happen in a plain Lua AST.
153 self:acc (table.tostring (node, "nohash"), 80)
159 --------------------------------------------------------------------------------
160 -- Convert every node in the AST list `list' passed as 1st arg.
161 -- `sep' is an optional separator to be accumulated between each list element,
162 -- it can be a string or a synth method.
163 -- `start' is an optional number (default == 1), indicating which is the
164 -- first element of list to be converted, so that we can skip the begining
166 --------------------------------------------------------------------------------
167 function M:list (list, sep, start)
168 for i = start or 1, # list do
172 elseif type (sep) == "function" then sep (self)
173 elseif type (sep) == "string" then self:acc (sep)
174 else error "Invalid list separator" end
179 --------------------------------------------------------------------------------
184 -- Specific AST node dumping methods, associated to their node kinds
185 -- by their name, which is the corresponding AST tag.
186 -- synth:node() is in charge of delegating a node's treatment to the
187 -- appropriate tag method.
189 -- Such tag methods are called with the AST node as 1st arg.
190 -- As a convenience, the n node's children are passed as args #2 ... n+1.
192 -- There are several things that could be refactored into common subroutines
193 -- here: statement blocks dumping, function dumping...
194 -- However, given their small size and linear execution
195 -- (they basically perform series of :acc(), :node(), :list(),
196 -- :nl(), :nlindent() and :nldedent() calls), it seems more readable
197 -- to avoid multiplication of such tiny functions.
199 -- To make sense out of these, you need to know metalua's AST syntax, as
200 -- found in the reference manual or in metalua/doc/ast.txt.
202 --------------------------------------------------------------------------------
207 self:list (node, self.nl)
212 function M:Set (node)
214 | `Set{ { `Index{ lhs, `String{ method } } },
215 { `Function{ { `Id "self", ... } == params, body } } }
216 if is_idx_stack (lhs) and is_ident (method) ->
217 -- ``function foo:bar(...) ... end'' --
223 self:list (params, ", ", 2)
226 self:list (body, self.nl)
230 | `Set{ { lhs }, { `Function{ params, body } } } if is_idx_stack (lhs) ->
231 -- ``function foo(...) ... end'' --
235 self:list (params, ", ")
238 self:list (body, self.nl)
242 | `Set{ { `Id{ lhs1name } == lhs1, ... } == lhs, rhs }
243 if not is_ident (lhs1name) ->
244 -- ``foo, ... = ...'' when foo is *not* a valid identifier.
245 -- In that case, the spliced 1st variable must get parentheses,
246 -- to be distinguished from a statement splice.
247 -- This cannot happen in a plain Lua AST.
251 if lhs[2] then -- more than one lhs variable
253 self:list (lhs, ", ", 2)
256 self:list (rhs, ", ")
258 | `Set{ lhs, rhs } ->
259 -- ``... = ...'', no syntax sugar --
260 self:list (lhs, ", ")
262 self:list (rhs, ", ")
266 function M:While (node, cond, body)
271 self:list (body, self.nl)
276 function M:Repeat (node, body, cond)
279 self:list (body, self.nl)
286 for i = 1, #node-1, 2 do
287 -- for each ``if/then'' and ``elseif/then'' pair --
288 local cond, body = node[i], node[i+1]
289 self:acc (i==1 and "if " or "elseif ")
293 self:list (body, self.nl)
296 -- odd number of children --> last one is an `else' clause --
300 self:list (node[#node], self.nl)
306 function M:Fornum (node, var, first, last)
307 local body = node[#node]
314 if #node==5 then -- 5 children --> child #4 is a step increment.
320 self:list (body, self.nl)
325 function M:Forin (node, vars, generators, body)
327 self:list (vars, ", ")
329 self:list (generators, ", ")
332 self:list (body, self.nl)
337 function M:Local (node, lhs, rhs)
340 self:list (lhs, ", ")
343 self:list (rhs, ", ")
345 else -- Can't create a local statement with 0 variables in plain Lua
346 self:acc (table.tostring (node, 'nohash', 80))
350 function M:Localrec (node, lhs, rhs)
352 | `Localrec{ { `Id{name} }, { `Function{ params, body } } }
353 if is_ident (name) ->
354 -- ``local function name() ... end'' --
355 self:acc "local function "
358 self:list (params, ", ")
361 self:list (body, self.nl)
366 -- Other localrec are unprintable ==> splice them --
367 -- This cannot happen in a plain Lua AST. --
369 self:acc (table.tostring (node, 'nohash', 80))
374 function M:Call (node, f)
375 -- single string or table literal arg ==> no need for parentheses. --
378 | `Call{ _, `String{_} }
379 | `Call{ _, `Table{...}} -> parens = false
383 self:acc (parens and " (" or " ")
384 self:list (node, ", ", 2) -- skip `f'.
385 self:acc (parens and ")")
388 function M:Invoke (node, f, method)
389 -- single string or table literal arg ==> no need for parentheses. --
392 | `Invoke{ _, _, `String{_} }
393 | `Invoke{ _, _, `Table{...}} -> parens = false
399 self:acc (parens and " (" or " ")
400 self:list (node, ", ", 3) -- Skip args #1 and #2, object and method name.
401 self:acc (parens and ")")
404 function M:Return (node)
406 self:list (node, ", ")
415 function M:Number (node, n)
416 self:acc (tostring (n))
419 function M:String (node, str)
420 -- format "%q" prints '\n' in an umpractical way IMO,
421 -- so this is fixed with the :gsub( ) call.
422 self:acc (string.format ("%q", str):gsub ("\\\n", "\\n"))
425 function M:Function (node, params, body)
426 self:acc "function ("
427 self:list (params, ", ")
430 self:list (body, self.nl)
435 function M:Table (node)
436 if not node[1] then self:acc "{ }" else
438 if #node > 1 then self:nlindent () else self:acc " " end
439 for i, elem in ipairs (node) do
441 | `Pair{ `String{ key }, value } if is_ident (key) ->
442 -- ``key = value''. --
447 | `Pair{ key, value } ->
448 -- ``[key] = value''. --
463 if #node > 1 then self:nldedent () else self:acc " " end
468 function M:Op (node, op, a, b)
469 -- Transform ``not (a == b)'' into ``a ~= b''. --
471 | `Op{ "not", `Op{ "eq", _a, _b } }
472 | `Op{ "not", `Paren{ `Op{ "eq", _a, _b } } } ->
473 op, a, b = "ne", _a, _b
477 if b then -- binary operator.
478 local left_paren, right_paren
480 | `Op{ op_a, ...} if op_prec[op] >= op_prec[op_a] -> left_paren = true
481 | _ -> left_paren = false
484 match b with -- FIXME: might not work with right assoc operators ^ and ..
485 | `Op{ op_b, ...} if op_prec[op] >= op_prec[op_b] -> right_paren = true
486 | _ -> right_paren = false
489 self:acc (left_paren and "(")
491 self:acc (left_paren and ")")
493 self:acc (op_symbol [op])
495 self:acc (right_paren and "(")
497 self:acc (right_paren and ")")
499 else -- unary operator.
502 | `Op{ op_a, ... } if op_prec[op] >= op_prec[op_a] -> paren = true
505 self:acc (op_symbol[op])
506 self:acc (paren and "(")
508 self:acc (paren and ")")
512 function M:Paren (node, content)
518 function M:Index (node, table, key)
520 -- Check precedence, see if parens are needed around the table --
522 | `Op{ op, ... } if op_prec[op] < op_prec.index -> paren_table = true
523 | _ -> paren_table = false
526 self:acc (paren_table and "(")
528 self:acc (paren_table and ")")
531 | `String{ field } if is_ident (field) ->
536 -- ``table [key]''. --
543 function M:Id (node, name)
544 if is_ident (name) then
546 else -- Unprintable identifier, fall back to splice representation.
547 -- This cannot happen in a plain Lua AST.
549 self:String (node, name)