]> git.lizzy.rs Git - metalua.git/blob - src/compiler/gg.lua
minor refactoring in gg
[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       local keyword = s[1]
262       if not is_parser(s) then sequence(s) end
263       if is_parser(s) ~= 'sequence' or type(keyword) ~= "string" then 
264          if self.default then -- two defaults
265             error ("In a multisequence parser, all but one sequences "..
266                    "must start with a keyword")
267          else self.default = s end -- first default
268       elseif self.sequences[keyword] then -- duplicate keyword
269          eprintf (" *** Warning: keyword %q overloaded in multisequence ***", keyword)
270          self.sequences[keyword] = s
271       else -- newly caught keyword
272          self.sequences[keyword] = s
273       end
274    end -- </multisequence.add>
275
276    -------------------------------------------------------------------
277    -- Get the sequence starting with this keyword. [kw :: string]
278    -------------------------------------------------------------------
279    function p:get (kw) return self.sequences [kw] end
280
281    -------------------------------------------------------------------
282    -- Remove the sequence starting with keyword [kw :: string]
283    -------------------------------------------------------------------
284    function p:del (kw) 
285       if not self.sequences[kw] then 
286          eprintf("*** Warning: trying to delete sequence starting "..
287                  "with %q from a multisequence having no such "..
288                  "entry ***", kw) end
289       local removed = self.sequences[kw]
290       self.sequences[kw] = nil 
291       return removed
292    end
293
294    -------------------------------------------------------------------
295    -- Parsing method
296    -------------------------------------------------------------------
297    function p:parse (lx)
298       local fli = lx:lineinfo_right()
299       local x = raw_parse_multisequence (lx, self.sequences, self.default)
300       local lli = lx:lineinfo_left()
301       return transform (x, self, fli, lli)
302    end
303
304    -------------------------------------------------------------------
305    -- Construction
306    -------------------------------------------------------------------
307    -- Register the sequences passed to the constructor. They're going
308    -- from the array part of the parser to the hash part of field
309    -- [sequences]
310    p.sequences = { }
311    for i=1, #p do p:add (p[i]); p[i] = nil end
312
313    -- FIXME: why is this commented out?
314    --if p.default and not is_parser(p.default) then sequence(p.default) end
315    return p
316 end --</multisequence>
317
318
319 -------------------------------------------------------------------------------
320 --
321 -- Expression parser generator
322 --
323 -------------------------------------------------------------------------------
324 --
325 -- Expression configuration relies on three tables: [prefix], [infix]
326 -- and [suffix]. Moreover, the primary parser can be replaced by a
327 -- table: in this case the [primary] table will be passed to
328 -- [gg.multisequence] to create a parser.
329 --
330 -- Each of these tables is a modified multisequence parser: the
331 -- differences with respect to regular multisequence config tables are:
332 --
333 -- * the builder takes specific parameters:
334 --   - for [prefix], it takes the result of the prefix sequence parser,
335 --     and the prefixed expression
336 --   - for [infix], it takes the left-hand-side expression, the results 
337 --     of the infix sequence parser, and the right-hand-side expression.
338 --   - for [suffix], it takes the suffixed expression, and theresult 
339 --     of the suffix sequence parser.
340 --
341 -- * the default field is a list, with parameters:
342 --   - [parser] the raw parsing function
343 --   - [transformers], as usual
344 --   - [prec], the operator's precedence
345 --   - [assoc] for [infix] table, the operator's associativity, which
346 --     can be "left", "right" or "flat" (default to left)
347 --
348 -- In [p], useful fields are:
349 -- * [transformers]: as usual
350 -- * [name]: as usual
351 -- * [primary]: the atomic expression parser, or a multisequence config 
352 --   table (mandatory)
353 -- * [prefix]:  prefix  operators config table, see above.
354 -- * [infix]:   infix   operators config table, see above.
355 -- * [suffix]: suffix operators config table, see above.
356 --
357 -- After creation, these fields are added:
358 -- * [kind] == "expr"
359 -- * [parse] as usual
360 -- * each table is turned into a multisequence, and therefore has an 
361 --   [add] method
362 --
363 -------------------------------------------------------------------------------
364 function expr (p)
365    make_parser ("expr", p)
366
367    -------------------------------------------------------------------
368    -- parser method.
369    -- In addition to the lexer, it takes an optional precedence:
370    -- it won't read expressions whose precedence is lower or equal
371    -- to [prec].
372    -------------------------------------------------------------------
373    function p:parse (lx, prec)
374       prec = prec or 0
375
376       ------------------------------------------------------
377       -- Extract the right parser and the corresponding
378       -- options table, for (pre|in|suff)fix operators.
379       -- Options include prec, assoc, transformers.
380       ------------------------------------------------------
381       local function get_parser_info (tab)
382          local p2 = tab:get (lx:is_keyword (lx:peek()))
383          if p2 then -- keyword-based sequence found
384             local function parser(lx) return raw_parse_sequence(lx, p2) end
385             return parser, p2
386          else -- Got to use the default parser
387             local d = tab.default
388             if d then return d.parse or d.parser, d
389             else return false, false end
390          end
391       end
392
393       ------------------------------------------------------
394       -- Look for a prefix sequence. Multiple prefixes are
395       -- handled through the recursive [p.parse] call.
396       -- Notice the double-transform: one for the primary
397       -- expr, and one for the one with the prefix op.
398       ------------------------------------------------------
399       local function handle_prefix ()
400          local fli = lx:lineinfo_right()
401          local p2_func, p2 = get_parser_info (self.prefix)
402          local op = p2_func and p2_func (lx)
403          if op then -- Keyword-based sequence found
404             local ili = lx:lineinfo_right() -- Intermediate LineInfo
405             local e = p2.builder (op, self:parse (lx, p2.prec))
406             local lli = lx:lineinfo_left()
407             return transform (transform (e, p2, ili, lli), self, fli, lli)
408          else -- No prefix found, get a primary expression         
409             local e = self.primary(lx)
410             local lli = lx:lineinfo_left()
411             return transform (e, self, fli, lli)
412          end
413       end --</expr.parse.handle_prefix>
414
415       ------------------------------------------------------
416       -- Look for an infix sequence+right-hand-side operand.
417       -- Return the whole binary expression result,
418       -- or false if no operator was found.
419       ------------------------------------------------------
420       local function handle_infix (e)
421          local p2_func, p2 = get_parser_info (self.infix)
422          if not p2 then return false end
423
424          -----------------------------------------
425          -- Handle flattening operators: gather all operands
426          -- of the series in [list]; when a different operator 
427          -- is found, stop, build from [list], [transform] and
428          -- return.
429          -----------------------------------------
430          if (not p2.prec or p2.prec>prec) and p2.assoc=="flat" then
431             local fli = lx:lineinfo_right()
432             local pflat, list = p2, { e }
433             repeat
434                local op = p2_func(lx)
435                if not op then break end
436                table.insert (list, self:parse (lx, p2.prec))
437                local _ -- We only care about checking that p2==pflat
438                _, p2 = get_parser_info (self.infix)
439             until p2 ~= pflat
440             local e2 = pflat.builder (list)
441             local lli = lx:lineinfo_left()
442             return transform (transform (e2, pflat, fli, lli), self, fli, lli)
443  
444          -----------------------------------------
445          -- Handle regular infix operators: [e] the LHS is known,
446          -- just gather the operator and [e2] the RHS.
447          -- Result goes in [e3].
448          -----------------------------------------
449          elseif p2.prec and p2.prec>prec or 
450                 p2.prec==prec and p2.assoc=="right" then
451             local fli = e.lineinfo.first -- lx:lineinfo_right()
452             local op = p2_func(lx)
453             if not op then return false end
454             local e2 = self:parse (lx, p2.prec)
455             local e3 = p2.builder (e, op, e2)
456             local lli = lx:lineinfo_left()
457             return transform (transform (e3, p2, fli, lli), self, fli, lli)
458
459          -----------------------------------------
460          -- Check for non-associative operators, and complain if applicable. 
461          -----------------------------------------
462          elseif p2.assoc=="none" and p2.prec==prec then
463             parser_error (lx, "non-associative operator!")
464
465          -----------------------------------------
466          -- No infix operator suitable at that precedence
467          -----------------------------------------
468          else return false end
469
470       end --</expr.parse.handle_infix>
471
472       ------------------------------------------------------
473       -- Look for a suffix sequence.
474       -- Return the result of suffix operator on [e],
475       -- or false if no operator was found.
476       ------------------------------------------------------
477       local function handle_suffix (e)
478          -- FIXME bad fli, must take e.lineinfo.first
479          local p2_func, p2 = get_parser_info (self.suffix)
480          if not p2 then return false end
481          if not p2.prec or p2.prec>=prec then
482             --local fli = lx:lineinfo_right()
483             local fli = e.lineinfo.first
484             local op = p2_func(lx)
485             if not op then return false end
486             local lli = lx:lineinfo_left()
487             e = p2.builder (e, op)
488             e = transform (transform (e, p2, fli, lli), self, fli, lli)
489             return e
490          end
491          return false
492       end --</expr.parse.handle_suffix>
493
494       ------------------------------------------------------
495       -- Parser body: read suffix and (infix+operand) 
496       -- extensions as long as we're able to fetch more at
497       -- this precedence level.
498       ------------------------------------------------------
499       local e = handle_prefix()
500       repeat
501          local x = handle_suffix (e); e = x or e
502          local y = handle_infix   (e); e = y or e
503       until not (x or y)
504
505       -- No transform: it already happened in operators handling
506       return e
507    end --</expr.parse>
508
509    -------------------------------------------------------------------
510    -- Construction
511    -------------------------------------------------------------------
512    if not p.primary then p.primary=p[1]; p[1]=nil end
513    for _, t in ipairs{ "primary", "prefix", "infix", "suffix" } do
514       if not p[t] then p[t] = { } end
515       if not is_parser(p[t]) then multisequence(p[t]) end
516    end
517    function p:add(...) return self.primary:add(...) end
518    return p
519 end --</expr>
520
521
522 -------------------------------------------------------------------------------
523 --
524 -- List parser generator
525 --
526 -------------------------------------------------------------------------------
527 -- In [p], the following fields can be provided in input:
528 --
529 -- * [builder]: takes list of subparser results, returns AST
530 -- * [transformers]: as usual
531 -- * [name]: as usual
532 --
533 -- * [terminators]: list of strings representing the keywords which
534 --   might mark the end of the list. When non-empty, the list is
535 --   allowed to be empty. A string is treated as a single-element
536 --   table, whose element is that string, e.g. ["do"] is the same as
537 --   [{"do"}].
538 --
539 -- * [separators]: list of strings representing the keywords which can
540 --   separate elements of the list. When non-empty, one of these
541 --   keyword has to be found between each element. Lack of a separator
542 --   indicates the end of the list. A string is treated as a
543 --   single-element table, whose element is that string, e.g. ["do"]
544 --   is the same as [{"do"}]. If [terminators] is empty/nil, then
545 --   [separators] has to be non-empty.
546 --
547 -- After creation, the following fields are added:
548 -- * [parse] the parsing function lexer->AST
549 -- * [kind] == "list"
550 --
551 -------------------------------------------------------------------------------
552 function list (p)
553    make_parser ("list", p)
554
555    -------------------------------------------------------------------
556    -- Parsing method
557    -------------------------------------------------------------------
558    function p:parse (lx)
559
560       ------------------------------------------------------
561       -- Used to quickly check whether there's a terminator 
562       -- or a separator immediately ahead
563       ------------------------------------------------------
564       local function peek_is_in (keywords) 
565          return keywords and lx:is_keyword(lx:peek(), unpack(keywords)) end
566
567       local x = { }
568       local fli = lx:lineinfo_right()
569
570       -- if there's a terminator to start with, don't bother trying
571       if not peek_is_in (self.terminators) then 
572          repeat table.insert (x, self.primary (lx)) -- read one element
573          until
574             -- First reason to stop: There's a separator list specified,
575             -- and next token isn't one. Otherwise, consume it with [lx:next()]
576             self.separators and not(peek_is_in (self.separators) and lx:next()) or
577             -- Other reason to stop: terminator token ahead
578             peek_is_in (self.terminators) or
579             -- Last reason: end of file reached
580             lx:peek().tag=="Eof"
581       end
582
583       local lli = lx:lineinfo_left()
584       
585       -- Apply the builder. It can be a string, or a callable value, 
586       -- or simply nothing.
587       local b = self.builder
588       if b then
589          if type(b)=="string" then x.tag = b -- b is a string, use it as a tag
590          elseif type(b)=="function" then x=b(x)
591          else
592             local bmt = getmetatable(b)
593             if bmt and bmt.__call then x=b(x) end
594          end
595       end
596       return transform (x, self, fli, lli)
597    end --</list.parse>
598
599    -------------------------------------------------------------------
600    -- Construction
601    -------------------------------------------------------------------
602    if not p.primary then p.primary = p[1]; p[1] = nil end
603    if type(p.terminators) == "string" then p.terminators = { p.terminators }
604    elseif p.terminators and #p.terminators == 0 then p.terminators = nil end
605    if type(p.separators) == "string" then p.separators = { p.separators }
606    elseif p.separators and #p.separators == 0 then p.separators = nil end
607
608    return p
609 end --</list>
610
611
612 -------------------------------------------------------------------------------
613 --
614 -- Keyword-conditionned parser generator
615 --
616 -------------------------------------------------------------------------------
617 -- 
618 -- Only apply a parser if a given keyword is found. The result of
619 -- [gg.onkeyword] parser is the result of the subparser (modulo
620 -- [transformers] applications).
621 --
622 -- lineinfo: the keyword is *not* included in the boundaries of the
623 -- resulting lineinfo. A review of all usages of gg.onkeyword() in the
624 -- implementation of metalua has shown that it was the appropriate choice
625 -- in every case.
626 --
627 -- Input fields:
628 --
629 -- * [name]: as usual
630 --
631 -- * [transformers]: as usual
632 --
633 -- * [peek]: if non-nil, the conditionning keyword is left in the lexeme
634 --   stream instead of being consumed.
635 --
636 -- * [primary]: the subparser. 
637 --
638 -- * [keywords]: list of strings representing triggering keywords.
639 --
640 -- * Table-part entries can contain strings, and/or exactly one parser.
641 --   Strings are put in [keywords], and the parser is put in [primary].
642 --
643 -- After the call, the following fields will be set:
644 --   
645 -- * [parse] the parsing method
646 -- * [kind] == "onkeyword"
647 -- * [primary]
648 -- * [keywords]
649 --
650 -------------------------------------------------------------------------------
651 function onkeyword (p)
652    make_parser ("onkeyword", p)
653
654    -------------------------------------------------------------------
655    -- Parsing method
656    -------------------------------------------------------------------
657    function p:parse(lx)
658       if lx:is_keyword (lx:peek(), unpack(self.keywords)) then
659          --local fli = lx:lineinfo_right()
660          if not self.peek then lx:next() end
661          local content = self.primary (lx)
662          --local lli = lx:lineinfo_left()
663          local fli, lli = content.lineinfo.first, content.lineinfo.last
664          return transform (content, p, fli, lli)
665       else return false end
666    end
667
668    -------------------------------------------------------------------
669    -- Construction
670    -------------------------------------------------------------------
671    if not p.keywords then p.keywords = { } end
672    for _, x in ipairs(p) do
673       if type(x)=="string" then table.insert (p.keywords, x)
674       else assert (not p.primary and is_parser (x)); p.primary = x end
675    end
676    if not next (p.keywords) then 
677       eprintf("Warning, no keyword to trigger gg.onkeyword") end
678    assert (p.primary, 'no primary parser in gg.onkeyword')
679    return p
680 end --</onkeyword>
681
682
683 -------------------------------------------------------------------------------
684 --
685 -- Optional keyword consummer pseudo-parser generator
686 --
687 -------------------------------------------------------------------------------
688 --
689 -- This doesn't return a real parser, just a function. That function parses
690 -- one of the keywords passed as parameters, and returns it. It returns 
691 -- [false] if no matching keyword is found.
692 --
693 -- Notice that tokens returned by lexer already carry lineinfo, therefore
694 -- there's no need to add them, as done usually through transform() calls.
695 -------------------------------------------------------------------------------
696 function optkeyword (...)
697    local args = {...}
698    if type (args[1]) == "table" then 
699       assert (#args == 1)
700       args = args[1]
701    end
702    for _, v in ipairs(args) do assert (type(v)=="string") end
703    return function (lx)
704       local x = lx:is_keyword (lx:peek(), unpack (args))
705       if x then lx:next(); return x
706       else return false end
707    end
708 end
709
710
711 -------------------------------------------------------------------------------
712 --
713 -- Run a parser with a special lexer
714 --
715 -------------------------------------------------------------------------------
716 --
717 -- This doesn't return a real parser, just a function.
718 -- First argument is the lexer class to be used with the parser,
719 -- 2nd is the parser itself.
720 -- The resulting parser returns whatever the argument parser does.
721 --
722 -------------------------------------------------------------------------------
723 function with_lexer(new_lexer, parser)
724
725    -------------------------------------------------------------------
726    -- Most gg functions take their parameters in a table, so it's 
727    -- better to silently accept when with_lexer{ } is called with
728    -- its arguments in a list:
729    -------------------------------------------------------------------
730    if not parser and #new_lexer==2 and type(new_lexer[1])=='table' then
731       return with_lexer(unpack(new_lexer))
732    end
733
734    -------------------------------------------------------------------
735    -- Save the current lexer, switch it for the new one, run the parser,
736    -- restore the previous lexer, even if the parser caused an error.
737    -------------------------------------------------------------------
738    return function (lx)
739       local old_lexer = getmetatable(lx)
740       lx:sync()
741       setmetatable(lx, new_lexer)
742       local status, result = pcall(parser, lx)
743       lx:sync()
744       setmetatable(lx, old_lexer)
745       if status then return result else error(result) end
746    end
747 end