1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013 Fabien Fleutot and others.
--
-- All rights reserved.
--
-- This program and the accompanying materials are made available
-- under the terms of the Eclipse Public License v1.0 which
-- accompanies this distribution, and is available at
-- http://www.eclipse.org/legal/epl-v10.html
--
-- This program and the accompanying materials are also made available
-- under the terms of the MIT public license which accompanies this
-- distribution, and is available at http://www.lua.org/license.html
--
-- Contributors:
--     Fabien Fleutot - API and implementation
--
-------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------
--
-- Summary: metalua parser, statement/block parser. This is part of the
-- definition of module [mlp].
--
-------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------
--
-- Exports API:
-- * [mlp.stat()]
-- * [mlp.block()]
-- * [mlp.for_header()]
--
-------------------------------------------------------------------------------
 
local unpack = table.unpack or unpack
 
local lexer    = require 'metalua.grammar.lexer'
local gg       = require 'metalua.grammar.generator'
 
local annot = require 'metalua.compiler.parser.annot.generator'
 
--------------------------------------------------------------------------------
-- List of all keywords that indicate the end of a statement block. Users are
-- likely to extend this list when designing extensions.
--------------------------------------------------------------------------------
 
 
return function(M)
    local _M = gg.future(M)
 
    M.block_terminators = { "else", "elseif", "end", "until", ")", "}", "]" }
 
    -- FIXME: this must be handled from within GG!!!
    -- FIXME: there's no :add method in the list anyway. Added by gg.list?!
    function M.block_terminators :add(x)
        if type (x) == "table" then for _, y in ipairs(x) do self :add (y) end
        else table.insert (self, x) end
    end
 
    ----------------------------------------------------------------------------
    -- list of statements, possibly followed by semicolons
    ----------------------------------------------------------------------------
    M.block = gg.list {
        name        = "statements block",
        terminators = M.block_terminators,
        primary     = function (lx)
            -- FIXME use gg.optkeyword()
            local x = M.stat (lx)
            if lx:is_keyword (lx:peek(), ";") then lx:next() end
            return x
        end }
 
    ----------------------------------------------------------------------------
    -- Helper function for "return <expr_list>" parsing.
    -- Called when parsing return statements.
    -- The specific test for initial ";" is because it's not a block terminator,
    -- so without it gg.list would choke on "return ;" statements.
    -- We don't make a modified copy of block_terminators because this list
    -- is sometimes modified at runtime, and the return parser would get out of
    -- sync if it was relying on a copy.
    ----------------------------------------------------------------------------
    local return_expr_list_parser = gg.multisequence{
        { ";" , builder = function() return { } end },
        default = gg.list {
            _M.expr, separators = ",", terminators = M.block_terminators } }
 
 
    local for_vars_list = gg.list{
        name        = "for variables list",
        primary     = _M.id,
        separators  = ",",
        terminators = "in" }
 
    ----------------------------------------------------------------------------
    -- for header, between [for] and [do] (exclusive).
    -- Return the `Forxxx{...} AST, without the body element (the last one).
    ----------------------------------------------------------------------------
    function M.for_header (lx)
        local vars = M.id_list(lx)
        if lx :is_keyword (lx:peek(), "=") then
            if #vars ~= 1 then
                gg.parse_error (lx, "numeric for only accepts one variable")
            end
            lx:next() -- skip "="
            local exprs = M.expr_list (lx)
            if #exprs < 2 or #exprs > 3 then
                gg.parse_error (lx, "numeric for requires 2 or 3 boundaries")
            end
            return { tag="Fornum", vars[1], unpack (exprs) }
        else
            if not lx :is_keyword (lx :next(), "in") then
                gg.parse_error (lx, '"=" or "in" expected in for loop')
            end
            local exprs = M.expr_list (lx)
            return { tag="Forin", vars, exprs }
        end
    end
 
    ----------------------------------------------------------------------------
    -- Function def parser helper: id ( . id ) *
    ----------------------------------------------------------------------------
    local function fn_builder (list)
        local acc = list[1]
        local first = acc.lineinfo.first
        for i = 2, #list do
            local index = M.id2string(list[i])
            local li = lexer.new_lineinfo(first, index.lineinfo.last)
            acc = { tag="Index", acc, index, lineinfo=li }
        end
        return acc
    end
    local func_name = gg.list{ _M.id, separators = ".", builder = fn_builder }
 
    ----------------------------------------------------------------------------
    -- Function def parser helper: ( : id )?
    ----------------------------------------------------------------------------
    local method_name = gg.onkeyword{ name = "method invocation", ":", _M.id,
        transformers = { function(x) return x and x.tag=='Id' and M.id2string(x) end } }
 
    ----------------------------------------------------------------------------
    -- Function def builder
    ----------------------------------------------------------------------------
    local function funcdef_builder(x)
        local name, method, func = unpack(x)
        if method then
            name = { tag="Index", name, method,
                     lineinfo = {
                         first = name.lineinfo.first,
                         last  = method.lineinfo.last } }
            table.insert (func[1], 1, {tag="Id", "self"})
        end
        local r = { tag="Set", {name}, {func} }
        r[1].lineinfo = name.lineinfo
        r[2].lineinfo = func.lineinfo
        return r
    end
 
 
    ----------------------------------------------------------------------------
    -- if statement builder
    ----------------------------------------------------------------------------
    local function if_builder (x)
        local cond_block_pairs, else_block, r = x[1], x[2], {tag="If"}
        local n_pairs = #cond_block_pairs
        for i = 1, n_pairs do
            local cond, block = unpack(cond_block_pairs[i])
            r[2*i-1], r[2*i] = cond, block
        end
        if else_block then table.insert(r, #r+1, else_block) end
        return r
    end
 
    --------------------------------------------------------------------------------
    -- produce a list of (expr,block) pairs
    --------------------------------------------------------------------------------
    local elseifs_parser = gg.list {
        gg.sequence { _M.expr, "then", _M.block , name='elseif parser' },
        separators  = "elseif",
        terminators = { "else", "end" }
    }
 
    local annot_expr = gg.sequence {
        _M.expr,
        gg.onkeyword{ "#", gg.future(M, 'annot').tf },
        builder = function(x)
            local e, a = unpack(x)
            if a then return { tag='Annot', e, a }
            else return e end
        end }
 
    local annot_expr_list = gg.list {
        primary = annot.opt(M, _M.expr, 'tf'), separators = ',' }
 
    ------------------------------------------------------------------------
    -- assignments and calls: statements that don't start with a keyword
    ------------------------------------------------------------------------
    local function assign_or_call_stat_parser (lx)
        local e = annot_expr_list (lx)
        local a = lx:is_keyword(lx:peek())
        local op = a and M.assignments[a]
        -- TODO: refactor annotations
        if op then
            --FIXME: check that [e] is a LHS
            lx :next()
            local annots
            e, annots = annot.split(e)
            local v = M.expr_list (lx)
            if type(op)=="string" then return { tag=op, e, v, annots }
            else return op (e, v) end
        else
            assert (#e > 0)
            if #e > 1 then
                gg.parse_error (lx,
                    "comma is not a valid statement separator; statement can be "..
                    "separated by semicolons, or not separated at all")
            elseif e[1].tag ~= "Call" and e[1].tag ~= "Invoke" then
                local typename
                if e[1].tag == 'Id' then
                    typename = '("'..e[1][1]..'") is an identifier'
                elseif e[1].tag == 'Op' then
                    typename = "is an arithmetic operation"
                else typename = "is of type '"..(e[1].tag or "<list>").."'" end
                gg.parse_error (lx,
                     "This expression %s; "..
                     "a statement was expected, and only function and method call "..
                     "expressions can be used as statements", typename);
            end
            return e[1]
        end
    end
 
    M.local_stat_parser = gg.multisequence{
        -- local function <name> <func_val>
        { "function", _M.id, _M.func_val, builder =
          function(x)
              local vars = { x[1], lineinfo = x[1].lineinfo }
              local vals = { x[2], lineinfo = x[2].lineinfo }
              return { tag="Localrec", vars, vals }
          end },
        -- local <id_list> ( = <expr_list> )?
        default = gg.sequence{
            gg.list{
                primary = annot.opt(M, _M.id, 'tf'),
                separators = ',' },
            gg.onkeyword{ "=", _M.expr_list },
            builder = function(x)
                 local annotated_left, right = unpack(x)
                 local left, annotations = annot.split(annotated_left)
                 return {tag="Local", left, right or { }, annotations }
             end } }
 
    ------------------------------------------------------------------------
    -- statement
    ------------------------------------------------------------------------
    M.stat = gg.multisequence {
        name = "statement",
        { "do", _M.block, "end", builder =
          function (x) return { tag="Do", unpack (x[1]) } end },
        { "for", _M.for_header, "do", _M.block, "end", builder =
          function (x) x[1][#x[1]+1] = x[2]; return x[1] end },
        { "function", func_name, method_name, _M.func_val, builder=funcdef_builder },
        { "while", _M.expr, "do", _M.block, "end", builder = "While" },
        { "repeat", _M.block, "until", _M.expr, builder = "Repeat" },
        { "local", _M.local_stat_parser, builder = unpack },
        { "return", return_expr_list_parser, builder =
          function(x) x[1].tag='Return'; return x[1] end },
        { "goto", _M.id, builder =
          function(x) x[1].tag='Goto'; return x[1] end },
        { "::", _M.id, "::", builder =
          function(x) x[1].tag='Label'; return x[1] end },
        { "break", builder = function() return { tag="Break" } end },
        { "-{", gg.future(M, 'meta').splice_content, "}", builder = unpack },
        { "if", gg.nonempty(elseifs_parser), gg.onkeyword{ "else", M.block }, "end",
          builder = if_builder },
        default = assign_or_call_stat_parser }
 
    M.assignments = {
        ["="] = "Set"
    }
 
    function M.assignments:add(k, v) self[k] = v end
 
    return M
end