]> git.lizzy.rs Git - metalua.git/blob - src/compiler/gg.lua
486752d537e8f8db33a24db11c6b717844d59c8b
[metalua.git] / src / compiler / gg.lua
1 ----------------------------------------------------------------------
2 -- Metalua.
3 --
4 -- Summary: parser generator. Collection of higher order functors,
5 --   which allow to build and combine parsers. Relies on a lexer
6 --   that supports the same API as the one exposed in mll.lua.
7 --
8 ----------------------------------------------------------------------
9 --
10 -- Copyright (c) 2006-2008, Fabien Fleutot <metalua@gmail.com>.
11 --
12 -- This software is released under the MIT Licence, see licence.txt
13 -- for details.
14 --
15 ----------------------------------------------------------------------
16
17 --------------------------------------------------------------------------------
18 --
19 -- Exported API:
20 --
21 -- Parser generators:
22 -- * [gg.sequence()]
23 -- * [gg.multisequence()]
24 -- * [gg.expr()]
25 -- * [gg.list()]
26 -- * [gg.onkeyword()]
27 -- * [gg.optkeyword()]
28 --
29 -- Other functions: 
30 -- * [gg.parse_error()]
31 -- * [gg.make_parser()]
32 -- * [gg.is_parser()]
33 --
34 --------------------------------------------------------------------------------
35
36 module("gg", package.seeall)
37
38 -------------------------------------------------------------------------------
39 -- parser metatable, which maps __call to method parse, and adds some
40 -- error tracing boilerplate.
41 -------------------------------------------------------------------------------
42 local parser_metatable = { }
43 function parser_metatable.__call (parser, lx, ...)
44    --printf ("Call parser %q of type %q", parser.name or "?", parser.kind)
45    if mlc.metabugs then 
46       return parser:parse (lx, ...) 
47       --local x = parser:parse (lx, ...) 
48       --printf ("Result of parser %q: %s", 
49       --        parser.name or "?",
50       --        _G.table.tostring(x, "nohash", 80))
51       --return x
52    else
53       local li = lx:lineinfo_right() or { "?", "?", "?", "?" }
54       local status, ast = pcall (parser.parse, parser, lx, ...)      
55       if status then return ast else
56          error (string.format ("%s\n - (l.%s, c.%s, k.%s) in parser %s", 
57                                ast:strmatch "gg.lua:%d+: (.*)" or ast,
58                                li[1], li[2], li[3], parser.name or parser.kind))
59       end
60    end
61 end
62
63 -------------------------------------------------------------------------------
64 -- Turn a table into a parser, mainly by setting the metatable.
65 -------------------------------------------------------------------------------
66 function make_parser(kind, p)
67    p.kind = kind
68    if not p.transformers then p.transformers = { } end
69    function p.transformers:add (x)
70       table.insert (self, x)
71    end
72    setmetatable (p, parser_metatable)
73    return p
74 end
75
76 -------------------------------------------------------------------------------
77 -- Return true iff [x] is a parser.
78 -- If it's a gg-generated parser, return the name of its kind.
79 -------------------------------------------------------------------------------
80 function is_parser (x)
81    return type(x)=="function" or getmetatable(x)==parser_metatable and x.kind
82 end
83
84 -------------------------------------------------------------------------------
85 -- Parse a sequence, without applying builder nor transformers
86 -------------------------------------------------------------------------------
87 local function raw_parse_sequence (lx, p)
88    local r = { }
89    for i=1, #p do
90       e=p[i]
91       if type(e) == "string" then 
92          if not lx:is_keyword (lx:next(), e) then
93             parse_error (lx, "Keyword '%s' expected", e) end
94       elseif is_parser (e) then
95          table.insert (r, e (lx)) 
96       else 
97          gg.parse_error (lx,"Sequence `%s': element #%i is not a string "..
98                          "nor a parser: %s", 
99                          p.name, i, table.tostring(e))
100       end
101    end
102    return r
103 end
104
105 -------------------------------------------------------------------------------
106 -- Parse a multisequence, without applying multisequence transformers.
107 -- The sequences are completely parsed.
108 -------------------------------------------------------------------------------
109 local function raw_parse_multisequence (lx, sequence_table, default)
110    local seq_parser = sequence_table[lx:is_keyword(lx:peek())]
111    if seq_parser  then return seq_parser (lx)
112    elseif default then return default (lx)
113    else return false end
114 end
115
116 -------------------------------------------------------------------------------
117 -- Applies all transformers listed in parser on ast.
118 -------------------------------------------------------------------------------
119 local function transform (ast, parser, fli, lli)
120    if parser.transformers then
121       for _, t in ipairs (parser.transformers) do ast = t(ast) or ast end
122    end
123    if type(ast) == 'table'then
124       local ali = ast.lineinfo
125       if not ali or ali.first~=fli or ali.last~=lli then
126          ast.lineinfo = { first = fli, last = lli }
127       end
128    end
129    return ast
130 end
131
132 -------------------------------------------------------------------------------
133 -- Generate a tracable parsing error (not implemented yet)
134 -------------------------------------------------------------------------------
135 function parse_error(lx, fmt, ...)
136    local li = lx:lineinfo_left() or {-1,-1,-1, "<unknown file>"}
137    local msg  = string.format("line %i, char %i: "..fmt, li[1], li[2], ...)   
138    local src = lx.src
139    if li[3]>0 and src then
140       local i, j = li[3], li[3]
141       while src:sub(i,i) ~= '\n' and i>=0    do i=i-1 end
142       while src:sub(j,j) ~= '\n' and j<=#src do j=j+1 end      
143       local srcline = src:sub (i+1, j-1)
144       local idx  = string.rep (" ", li[2]).."^"
145       msg = string.format("%s\n>>> %s\n>>> %s", msg, srcline, idx)
146    end
147    error(msg)
148 end
149    
150 -------------------------------------------------------------------------------
151 --
152 -- Sequence parser generator
153 --
154 -------------------------------------------------------------------------------
155 -- Input fields:
156 --
157 -- * [builder]: how to build an AST out of sequence parts. let [x] be the list
158 --   of subparser results (keywords are simply omitted). [builder] can be:
159 --    - [nil], in which case the result of parsing is simply [x]
160 --    - a string, which is then put as a tag on [x]
161 --    - a function, which takes [x] as a parameter and returns an AST.
162 --
163 -- * [name]: the name of the parser. Used for debug messages
164 --
165 -- * [transformers]: a list of AST->AST functions, applied in order on ASTs
166 --   returned by the parser.
167 --
168 -- * Table-part entries corresponds to keywords (strings) and subparsers 
169 --   (function and callable objects).
170 --
171 -- After creation, the following fields are added:
172 -- * [parse] the parsing function lexer->AST
173 -- * [kind] == "sequence"
174 -- * [name] is set, if it wasn't in the input.
175 --
176 -------------------------------------------------------------------------------
177 function sequence (p)
178    make_parser ("sequence", p)
179
180    -------------------------------------------------------------------
181    -- Parsing method
182    -------------------------------------------------------------------
183    function p:parse (lx)
184       -- Raw parsing:
185       local fli = lx:lineinfo_right()
186       local seq = raw_parse_sequence (lx, self)
187       local lli = lx:lineinfo_left()
188
189       -- Builder application:
190       local builder, tb = self.builder, type (self.builder)
191       if tb == "string" then seq.tag = builder
192       elseif tb == "function" or builder and builder.__call then seq = builder(seq)
193       elseif builder == nil then -- nothing
194       else error ("Invalid builder of type "..tb.." in sequence") end
195       seq = transform (seq, self, fli, lli)
196       assert (not seq or seq.lineinfo)
197       return seq
198    end
199
200    -------------------------------------------------------------------
201    -- Construction
202    -------------------------------------------------------------------
203    -- Try to build a proper name
204    if not p.name and type(p[1])=="string" then 
205       p.name = p[1].." ..." 
206       if type(p[#p])=="string" then p.name = p.name .. " " .. p[#p] end
207    else
208       p.name = "<anonymous>"
209    end
210
211    return p
212 end --</sequence>
213
214
215 -------------------------------------------------------------------------------
216 --
217 -- Multiple, keyword-driven, sequence parser generator
218 --
219 -------------------------------------------------------------------------------
220 -- in [p], useful fields are:
221 --
222 -- * [transformers]: as usual
223 --
224 -- * [name]: as usual
225 --
226 -- * Table-part entries must be sequence parsers, or tables which can
227 --   be turned into a sequence parser by [gg.sequence]. These
228 --   sequences must start with a keyword, and this initial keyword
229 --   must be different for each sequence.  The table-part entries will
230 --   be removed after [gg.multisequence] returns.
231 --
232 -- * [default]: the parser to run if the next keyword in the lexer is
233 --   none of the registered initial keywords. If there's no default
234 --   parser and no suitable initial keyword, the multisequence parser
235 --   simply returns [false].
236 --
237 -- After creation, the following fields are added:
238 --
239 -- * [parse] the parsing function lexer->AST
240 --
241 -- * [sequences] the table of sequences, indexed by initial keywords.
242 --
243 -- * [add] method takes a sequence parser or a config table for
244 --   [gg.sequence], and adds/replaces the corresponding sequence
245 --   parser. If the keyword was already used, the former sequence is
246 --   removed and a warning is issued.
247 --
248 -- * [get] method returns a sequence by its initial keyword
249 --
250 -- * [kind] == "multisequence"
251 --
252 -------------------------------------------------------------------------------
253 function multisequence (p)   
254    make_parser ("multisequence", p)
255
256    -------------------------------------------------------------------
257    -- Add a sequence (might be just a config table for [gg.sequence])
258    -------------------------------------------------------------------
259    function p:add (s)
260       -- compile if necessary:
261       if not is_parser(s) then sequence(s) end
262       if is_parser(s) ~= 'sequence' or type(s[1]) ~= "string" then 
263          if self.default then
264             error "Invalid sequence for multiseq, there is already a default"
265          else
266             self.default = s
267          end
268       elseif self.sequences[s[1]] then 
269          eprintf (" *** Warning: keyword %q overloaded in multisequence ***", s[1])
270       end
271       self.sequences[s[1]] = s
272    end -- </multisequence.add>
273
274    -------------------------------------------------------------------
275    -- Get the sequence starting with this keyword. [kw :: string]
276    -------------------------------------------------------------------
277    function p:get (kw) return self.sequences [kw] end
278
279    -------------------------------------------------------------------
280    -- Remove the sequence starting with keyword [kw :: string]
281    -------------------------------------------------------------------
282    function p:del (kw) 
283       if not self.sequences[kw] then 
284          eprintf("*** Warning: trying to delete sequence starting "..
285                  "with %q from a multisequence having no such "..
286                  "entry ***", kw) end
287       local removed = self.sequences[kw]
288       self.sequences[kw] = nil 
289       return removed
290    end
291
292    -------------------------------------------------------------------
293    -- Parsing method
294    -------------------------------------------------------------------
295    function p:parse (lx)
296       local fli = lx:lineinfo_right()
297       local x = raw_parse_multisequence (lx, self.sequences, self.default)
298       local lli = lx:lineinfo_left()
299       return transform (x, self, fli, lli)
300    end
301
302    -------------------------------------------------------------------
303    -- Construction
304    -------------------------------------------------------------------
305    -- Register the sequences passed to the constructor. They're going
306    -- from the array part of the parser to the hash part of field
307    -- [sequences]
308    p.sequences = { }
309    for i=1, #p do p:add (p[i]); p[i] = nil end
310
311    -- FIXME: why is this commented out?
312    --if p.default and not is_parser(p.default) then sequence(p.default) end
313    return p
314 end --</multisequence>
315
316
317 -------------------------------------------------------------------------------
318 --
319 -- Expression parser generator
320 --
321 -------------------------------------------------------------------------------
322 --
323 -- Expression configuration relies on three tables: [prefix], [infix]
324 -- and [suffix]. Moreover, the primary parser can be replaced by a
325 -- table: in this case the [primary] table will be passed to
326 -- [gg.multisequence] to create a parser.
327 --
328 -- Each of these tables is a modified multisequence parser: the
329 -- differences with respect to regular multisequence config tables are:
330 --
331 -- * the builder takes specific parameters:
332 --   - for [prefix], it takes the result of the prefix sequence parser,
333 --     and the prefixed expression
334 --   - for [infix], it takes the left-hand-side expression, the results 
335 --     of the infix sequence parser, and the right-hand-side expression.
336 --   - for [suffix], it takes the suffixed expression, and theresult 
337 --     of the suffix sequence parser.
338 --
339 -- * the default field is a list, with parameters:
340 --   - [parser] the raw parsing function
341 --   - [transformers], as usual
342 --   - [prec], the operator's precedence
343 --   - [assoc] for [infix] table, the operator's associativity, which
344 --     can be "left", "right" or "flat" (default to left)
345 --
346 -- In [p], useful fields are:
347 -- * [transformers]: as usual
348 -- * [name]: as usual
349 -- * [primary]: the atomic expression parser, or a multisequence config 
350 --   table (mandatory)
351 -- * [prefix]:  prefix  operators config table, see above.
352 -- * [infix]:   infix   operators config table, see above.
353 -- * [suffix]: suffix operators config table, see above.
354 --
355 -- After creation, these fields are added:
356 -- * [kind] == "expr"
357 -- * [parse] as usual
358 -- * each table is turned into a multisequence, and therefore has an 
359 --   [add] method
360 --
361 -------------------------------------------------------------------------------
362 function expr (p)
363    make_parser ("expr", p)
364
365    -------------------------------------------------------------------
366    -- parser method.
367    -- In addition to the lexer, it takes an optional precedence:
368    -- it won't read expressions whose precedence is lower or equal
369    -- to [prec].
370    -------------------------------------------------------------------
371    function p:parse (lx, prec)
372       prec = prec or 0
373
374       ------------------------------------------------------
375       -- Extract the right parser and the corresponding
376       -- options table, for (pre|in|suff)fix operators.
377       -- Options include prec, assoc, transformers.
378       ------------------------------------------------------
379       local function get_parser_info (tab)
380          local p2 = tab:get (lx:is_keyword (lx:peek()))
381          if p2 then -- keyword-based sequence found
382             local function parser(lx) return raw_parse_sequence(lx, p2) end
383             return parser, p2
384          else -- Got to use the default parser
385             local d = tab.default
386             if d then return d.parse or d.parser, d
387             else return false, false end
388          end
389       end
390
391       ------------------------------------------------------
392       -- Look for a prefix sequence. Multiple prefixes are
393       -- handled through the recursive [p.parse] call.
394       -- Notice the double-transform: one for the primary
395       -- expr, and one for the one with the prefix op.
396       ------------------------------------------------------
397       local function handle_prefix ()
398          local fli = lx:lineinfo_right()
399          local p2_func, p2 = get_parser_info (self.prefix)
400          local op = p2_func and p2_func (lx)
401          if op then -- Keyword-based sequence found
402             local ili = lx:lineinfo_right() -- Intermediate LineInfo
403             local e = p2.builder (op, self:parse (lx, p2.prec))
404             local lli = lx:lineinfo_left()
405             return transform (transform (e, p2, ili, lli), self, fli, lli)
406          else -- No prefix found, get a primary expression         
407             local e = self.primary(lx)
408             local lli = lx:lineinfo_left()
409             return transform (e, self, fli, lli)
410          end
411       end --</expr.parse.handle_prefix>
412
413       ------------------------------------------------------
414       -- Look for an infix sequence+right-hand-side operand.
415       -- Return the whole binary expression result,
416       -- or false if no operator was found.
417       ------------------------------------------------------
418       local function handle_infix (e)
419          local p2_func, p2 = get_parser_info (self.infix)
420          if not p2 then return false end
421
422          -----------------------------------------
423          -- Handle flattening operators: gather all operands
424          -- of the series in [list]; when a different operator 
425          -- is found, stop, build from [list], [transform] and
426          -- return.
427          -----------------------------------------
428          if (not p2.prec or p2.prec>prec) and p2.assoc=="flat" then
429             local fli = lx:lineinfo_right()
430             local pflat, list = p2, { e }
431             repeat
432                local op = p2_func(lx)
433                if not op then break end
434                table.insert (list, self:parse (lx, p2.prec))
435                local _ -- We only care about checking that p2==pflat
436                _, p2 = get_parser_info (self.infix)
437             until p2 ~= pflat
438             local e2 = pflat.builder (list)
439             local lli = lx:lineinfo_left()
440             return transform (transform (e2, pflat, fli, lli), self, fli, lli)
441  
442          -----------------------------------------
443          -- Handle regular infix operators: [e] the LHS is known,
444          -- just gather the operator and [e2] the RHS.
445          -- Result goes in [e3].
446          -----------------------------------------
447          elseif p2.prec and p2.prec>prec or 
448                 p2.prec==prec and p2.assoc=="right" then
449             local fli = e.lineinfo.first -- lx:lineinfo_right()
450             local op = p2_func(lx)
451             if not op then return false end
452             local e2 = self:parse (lx, p2.prec)
453             local e3 = p2.builder (e, op, e2)
454             local lli = lx:lineinfo_left()
455             return transform (transform (e3, p2, fli, lli), self, fli, lli)
456
457          -----------------------------------------
458          -- Check for non-associative operators, and complain if applicable. 
459          -----------------------------------------
460          elseif p2.assoc=="none" and p2.prec==prec then
461             parser_error (lx, "non-associative operator!")
462
463          -----------------------------------------
464          -- No infix operator suitable at that precedence
465          -----------------------------------------
466          else return false end
467
468       end --</expr.parse.handle_infix>
469
470       ------------------------------------------------------
471       -- Look for a suffix sequence.
472       -- Return the result of suffix operator on [e],
473       -- or false if no operator was found.
474       ------------------------------------------------------
475       local function handle_suffix (e)
476          -- FIXME bad fli, must take e.lineinfo.first
477          local p2_func, p2 = get_parser_info (self.suffix)
478          if not p2 then return false end
479          if not p2.prec or p2.prec>=prec then
480             --local fli = lx:lineinfo_right()
481             local fli = e.lineinfo.first
482             local op = p2_func(lx)
483             if not op then return false end
484             local lli = lx:lineinfo_left()
485             e = p2.builder (e, op)
486             e = transform (transform (e, p2, fli, lli), self, fli, lli)
487             return e
488          end
489          return false
490       end --</expr.parse.handle_suffix>
491
492       ------------------------------------------------------
493       -- Parser body: read suffix and (infix+operand) 
494       -- extensions as long as we're able to fetch more at
495       -- this precedence level.
496       ------------------------------------------------------
497       local e = handle_prefix()
498       repeat
499          local x = handle_suffix (e); e = x or e
500          local y = handle_infix   (e); e = y or e
501       until not (x or y)
502
503       -- No transform: it already happened in operators handling
504       return e
505    end --</expr.parse>
506
507    -------------------------------------------------------------------
508    -- Construction
509    -------------------------------------------------------------------
510    if not p.primary then p.primary=p[1]; p[1]=nil end
511    for _, t in ipairs{ "primary", "prefix", "infix", "suffix" } do
512       if not p[t] then p[t] = { } end
513       if not is_parser(p[t]) then multisequence(p[t]) end
514    end
515    function p:add(...) return self.primary:add(...) end
516    return p
517 end --</expr>
518
519
520 -------------------------------------------------------------------------------
521 --
522 -- List parser generator
523 --
524 -------------------------------------------------------------------------------
525 -- In [p], the following fields can be provided in input:
526 --
527 -- * [builder]: takes list of subparser results, returns AST
528 -- * [transformers]: as usual
529 -- * [name]: as usual
530 --
531 -- * [terminators]: list of strings representing the keywords which
532 --   might mark the end of the list. When non-empty, the list is
533 --   allowed to be empty. A string is treated as a single-element
534 --   table, whose element is that string, e.g. ["do"] is the same as
535 --   [{"do"}].
536 --
537 -- * [separators]: list of strings representing the keywords which can
538 --   separate elements of the list. When non-empty, one of these
539 --   keyword has to be found between each element. Lack of a separator
540 --   indicates the end of the list. A string is treated as a
541 --   single-element table, whose element is that string, e.g. ["do"]
542 --   is the same as [{"do"}]. If [terminators] is empty/nil, then
543 --   [separators] has to be non-empty.
544 --
545 -- After creation, the following fields are added:
546 -- * [parse] the parsing function lexer->AST
547 -- * [kind] == "list"
548 --
549 -------------------------------------------------------------------------------
550 function list (p)
551    make_parser ("list", p)
552
553    -------------------------------------------------------------------
554    -- Parsing method
555    -------------------------------------------------------------------
556    function p:parse (lx)
557
558       ------------------------------------------------------
559       -- Used to quickly check whether there's a terminator 
560       -- or a separator immediately ahead
561       ------------------------------------------------------
562       local function peek_is_in (keywords) 
563          return keywords and lx:is_keyword(lx:peek(), unpack(keywords)) end
564
565       local x = { }
566       local fli = lx:lineinfo_right()
567
568       -- if there's a terminator to start with, don't bother trying
569       if not peek_is_in (self.terminators) then 
570          repeat table.insert (x, self.primary (lx)) -- read one element
571          until
572             -- First reason to stop: There's a separator list specified,
573             -- and next token isn't one. Otherwise, consume it with [lx:next()]
574             self.separators and not(peek_is_in (self.separators) and lx:next()) or
575             -- Other reason to stop: terminator token ahead
576             peek_is_in (self.terminators) or
577             -- Last reason: end of file reached
578             lx:peek().tag=="Eof"
579       end
580
581       local lli = lx:lineinfo_left()
582       
583       -- Apply the builder. It can be a string, or a callable value, 
584       -- or simply nothing.
585       local b = self.builder
586       if b then
587          if type(b)=="string" then x.tag = b -- b is a string, use it as a tag
588          elseif type(b)=="function" then x=b(x)
589          else
590             local bmt = getmetatable(b)
591             if bmt and bmt.__call then x=b(x) end
592          end
593       end
594       return transform (x, self, fli, lli)
595    end --</list.parse>
596
597    -------------------------------------------------------------------
598    -- Construction
599    -------------------------------------------------------------------
600    if not p.primary then p.primary = p[1]; p[1] = nil end
601    if type(p.terminators) == "string" then p.terminators = { p.terminators }
602    elseif p.terminators and #p.terminators == 0 then p.terminators = nil end
603    if type(p.separators) == "string" then p.separators = { p.separators }
604    elseif p.separators and #p.separators == 0 then p.separators = nil end
605
606    return p
607 end --</list>
608
609
610 -------------------------------------------------------------------------------
611 --
612 -- Keyword-conditionned parser generator
613 --
614 -------------------------------------------------------------------------------
615 -- 
616 -- Only apply a parser if a given keyword is found. The result of
617 -- [gg.onkeyword] parser is the result of the subparser (modulo
618 -- [transformers] applications).
619 --
620 -- lineinfo: the keyword is *not* included in the boundaries of the
621 -- resulting lineinfo. A review of all usages of gg.onkeyword() in the
622 -- implementation of metalua has shown that it was the appropriate choice
623 -- in every case.
624 --
625 -- Input fields:
626 --
627 -- * [name]: as usual
628 --
629 -- * [transformers]: as usual
630 --
631 -- * [peek]: if non-nil, the conditionning keyword is left in the lexeme
632 --   stream instead of being consumed.
633 --
634 -- * [primary]: the subparser. 
635 --
636 -- * [keywords]: list of strings representing triggering keywords.
637 --
638 -- * Table-part entries can contain strings, and/or exactly one parser.
639 --   Strings are put in [keywords], and the parser is put in [primary].
640 --
641 -- After the call, the following fields will be set:
642 --   
643 -- * [parse] the parsing method
644 -- * [kind] == "onkeyword"
645 -- * [primary]
646 -- * [keywords]
647 --
648 -------------------------------------------------------------------------------
649 function onkeyword (p)
650    make_parser ("onkeyword", p)
651
652    -------------------------------------------------------------------
653    -- Parsing method
654    -------------------------------------------------------------------
655    function p:parse(lx)
656       if lx:is_keyword (lx:peek(), unpack(self.keywords)) then
657          --local fli = lx:lineinfo_right()
658          if not self.peek then lx:next() end
659          local content = self.primary (lx)
660          --local lli = lx:lineinfo_left()
661          local fli, lli = content.lineinfo.first, content.lineinfo.last
662          return transform (content, p, fli, lli)
663       else return false end
664    end
665
666    -------------------------------------------------------------------
667    -- Construction
668    -------------------------------------------------------------------
669    if not p.keywords then p.keywords = { } end
670    for _, x in ipairs(p) do
671       if type(x)=="string" then table.insert (p.keywords, x)
672       else assert (not p.primary and is_parser (x)); p.primary = x end
673    end
674    assert (p.primary, 'no primary parser in gg.onkeyword')
675    return p
676 end --</onkeyword>
677
678
679 -------------------------------------------------------------------------------
680 --
681 -- Optional keyword consummer pseudo-parser generator
682 --
683 -------------------------------------------------------------------------------
684 --
685 -- This doesn't return a real parser, just a function. That function parses
686 -- one of the keywords passed as parameters, and returns it. It returns 
687 -- [false] if no matching keyword is found.
688 --
689 -- Notice that tokens returned by lexer already carry lineinfo, therefore
690 -- there's no need to add them, as done usually through transform() calls.
691 -------------------------------------------------------------------------------
692 function optkeyword (...)
693    local args = {...}
694    if type (args[1]) == "table" then 
695       assert (#args == 1)
696       args = args[1]
697    end
698    for _, v in ipairs(args) do assert (type(v)=="string") end
699    return function (lx)
700       local x = lx:is_keyword (lx:peek(), unpack (args))
701       if x then lx:next(); return x
702       else return false end
703    end
704 end
705
706
707 -------------------------------------------------------------------------------
708 --
709 -- Run a parser with a special lexer
710 --
711 -------------------------------------------------------------------------------
712 --
713 -- This doesn't return a real parser, just a function.
714 -- First argument is the lexer class to be used with the parser,
715 -- 2nd is the parser itself.
716 -- The resulting parser returns whatever the argument parser does.
717 --
718 -------------------------------------------------------------------------------
719 function with_lexer(new_lexer, parser)
720
721    -------------------------------------------------------------------
722    -- Most gg functions take their parameters in a table, so it's 
723    -- better to silently accept when with_lexer{ } is called with
724    -- its arguments in a list:
725    -------------------------------------------------------------------
726    if not parser and #new_lexer==2 and type(new_lexer[1])=='table' then
727       return with_lexer(unpack(new_lexer))
728    end
729
730    -------------------------------------------------------------------
731    -- Save the current lexer, switch it for the new one, run the parser,
732    -- restore the previous lexer, even if the parser caused an error.
733    -------------------------------------------------------------------
734    return function (lx)
735       local old_lexer = getmetatable(lx)
736       lx:sync()
737       setmetatable(lx, new_lexer)
738       local status, result = pcall(parser, lx)
739       lx:sync()
740       setmetatable(lx, old_lexer)
741       if status then return result else error(result) end
742    end
743 end