]> git.lizzy.rs Git - metalua.git/blob - src/compiler/lexer.lua
f92ed141167d1da009ce974d3599c791e96a6523
[metalua.git] / src / compiler / lexer.lua
1 ----------------------------------------------------------------------
2 -- Metalua:  $Id: mll.lua,v 1.3 2006/11/15 09:07:50 fab13n Exp $
3 --
4 -- Summary: generic Lua-style lexer definition. You need this plus
5 -- some keyword additions to create the complete Lua lexer,
6 -- as is done in mlp_lexer.lua.
7 --
8 -- TODO: 
9 --
10 -- * Make it possible to change lexer on the fly. This implies the
11 --   ability to easily undo any pre-extracted tokens;
12 --
13 -- * Make it easy to define new flavors of strings. Replacing the
14 --   lexer.patterns.long_string regexp by an extensible list, with
15 --   customizable token tag, would probably be enough. Maybe add:
16 --   + an index of capture for the regexp, that would specify 
17 --     which capture holds the content of the string-like token
18 --   + a token tag
19 --   + or a string->string transformer function.
20 --
21 -- * There are some _G.table to prevent a namespace clash which has
22 --   now disappered. remove them.
23 ----------------------------------------------------------------------
24 --
25 -- Copyright (c) 2006, Fabien Fleutot <metalua@gmail.com>.
26 --
27 -- This software is released under the MIT Licence, see licence.txt
28 -- for details.
29 --
30 ----------------------------------------------------------------------
31
32 module ("lexer", package.seeall)
33
34 require 'metalua.runtime'
35
36
37 lexer = { alpha={ }, sym={ } }
38 lexer.__index=lexer
39
40 local debugf = function() end
41 --local debugf=printf
42
43 ----------------------------------------------------------------------
44 -- Patterns used by [lexer:extract] to decompose the raw string into
45 -- correctly tagged tokens.
46 ----------------------------------------------------------------------
47 lexer.patterns = {
48    spaces              = "^[ \r\n\t]*()",
49    short_comment       = "^%-%-([^\n]*)()\n",
50    final_short_comment = "^%-%-([^\n]*)()$",
51    long_comment        = "^%-%-%[(=*)%[\n?(.-)%]%1%]()",
52    long_string         = "^%[(=*)%[\n?(.-)%]%1%]()",
53    number_mantissa     = {
54       "^%d+%.?%d*()",
55       "^%d*%.%d+()" },
56    number_exponant = "^[eE][%+%-]?%d+()",
57    number_hex      = "^0[xX]%x+()",
58    word            = "^([%a_][%w_]*)()"
59 }
60
61 ----------------------------------------------------------------------
62 -- unescape a whole string, applying [unesc_digits] and
63 -- [unesc_letter] as many times as required.
64 ----------------------------------------------------------------------
65 local function unescape_string (s)
66
67    -- Turn the digits of an escape sequence into the corresponding
68    -- character, e.g. [unesc_digits("123") == string.char(123)].
69    local function unesc_digits (x)
70       local k, j, i = x:reverse():byte(1, 3)
71       local z = _G.string.byte "0"
72       return _G.string.char ((k or z) + 10*(j or z) + 100*(i or z) - 111*z)
73    end
74
75    -- Take a letter [x], and returns the character represented by the 
76    -- sequence ['\\'..x], e.g. [unesc_letter "n" == "\n"].
77    local function unesc_letter(x)
78       local t = { 
79          a = "\a", b = "\b", f = "\f",
80          n = "\n", r = "\r", t = "\t", v = "\v",
81          ["\\"] = "\\", ["'"] = "'", ['"'] = '"', ["\n"] = "\n" }
82       return t[x] or error([[Unknown escape sequence '\]]..x..[[']])
83    end
84
85    return s
86       :gsub ("\\(%D)",unesc_letter)
87       :gsub ("\\([0-9][0-9]?[0-9]?)", unesc_digits)
88 end
89
90 lexer.extractors = {
91    "skip_whitespaces_and_comments",
92    "extract_short_string", "extract_word", "extract_number", 
93    "extract_long_string", "extract_symbol" }
94
95 lexer.token_metatable = { 
96 --         __tostring = function(a) 
97 --            return string.format ("`%s{'%s'}",a.tag, a[1]) 
98 --         end 
99
100       
101 lexer.lineinfo_metatable = { }
102 --[[ 
103 -- The presence of this function prevents serialization by Pluto, 
104 -- I can't figure out why :(
105 function lexer.lineinfo_metatable:__tostring()
106    local txt = string.format("%s:%i(%i,%i)", self[4], self[3], self[1], self[2])
107    if self.comments then 
108       acc = { }
109       for comment in ivalues(self.comments) do
110          local content, loc1, loc2, kind = unpack(comment)
111          table.insert (acc, string.format ("%s@%i..%i:%q", kind, loc1, loc2, content))
112       end
113       txt = txt.."["..table.concat(acc,"; ").."]"
114    end
115    return txt
116 end
117 --]]
118
119 ----------------------------------------------------------------------
120 -- Really extract next token fron the raw string 
121 -- (and update the index).
122 -- loc: offset of the position just after spaces and comments
123 -- previous_i: offset in src before extraction began
124 ----------------------------------------------------------------------
125 function lexer:extract ()
126    local previous_i = self.i
127    local loc = self.i
128    local eof, token
129
130    -- Put line info, comments and metatable arount the tag and content
131    -- provided by extractors, thus returning a complete lexer token.
132    -- first_line: line # at the beginning of token
133    -- first_column_offset: char # of the last '\n' before beginning of token
134    -- i: scans from beginning of prefix spaces/comments to end of token.
135    local function build_token (tag, content)
136       assert (tag and content)
137       local i, first_line, first_column_offset, previous_line_length =
138          previous_i, self.line, self.column_offset, nil
139
140       -- update self.line and first_line. i := indexes of '\n' chars
141       while true do
142          i = self.src :find ("\n", i+1, true)
143          if not i or i>self.i then break end -- no more '\n' until end of token
144          previous_line_length = i - self.column_offset
145          if loc and i <= loc then -- '\n' before beginning of token
146             first_column_offset = i
147             first_line = first_line+1 
148          end
149          self.line   = self.line+1 
150          self.column_offset = i 
151       end
152
153       -- lineinfo entries: [1]=line, [2]=column, [3]=char, [4]=filename
154       local fli = { first_line, loc-first_column_offset, loc, self.src_name }
155       local lli = { self.line, self.i-self.column_offset-1, self.i-1, self.src_name }
156       --Pluto barfes when the metatable is set:(
157       setmetatable(fli, lexer.lineinfo_metatable)
158       setmetatable(lli, lexer.lineinfo_metatable)
159       local a = { tag = tag, lineinfo = { first=fli, last=lli }, content } 
160       if lli[2]==-1 then lli[1], lli[2] = lli[1]-1, previous_line_length-1 end
161       if #self.attached_comments > 0 then 
162          a.lineinfo.comments = self.attached_comments 
163          fli.comments = self.attached_comments
164          if self.lineinfo_last then
165             self.lineinfo_last.comments = self.attached_comments
166          end
167       end
168       self.attached_comments = { }
169       return setmetatable (a, self.token_metatable)
170    end --</function build_token>
171
172    for ext_idx, extractor in ipairs(self.extractors) do
173       -- printf("method = %s", method)
174       local tag, content = self [extractor] (self)
175       -- [loc] is placed just after the leading whitespaces and comments;
176       -- for this to work, the whitespace extractor *must be* at index 1.
177       if ext_idx==1 then loc = self.i end
178
179       if tag then 
180          --printf("`%s{ %q }\t%i", tag, content, loc);
181          return build_token (tag, content) 
182       end
183    end
184
185    error "None of the lexer extractors returned anything!"
186 end   
187
188 ----------------------------------------------------------------------
189 -- skip whites and comments
190 -- FIXME: doesn't take into account:
191 -- - unterminated long comments
192 -- - short comments at last line without a final \n
193 ----------------------------------------------------------------------
194 function lexer:skip_whitespaces_and_comments()
195    local table_insert = _G.table.insert
196    repeat -- loop as long as a space or comment chunk is found
197       local _, j
198       local again = false
199       local last_comment_content = nil
200       -- skip spaces
201       self.i = self.src:match (self.patterns.spaces, self.i)
202       -- skip a long comment if any
203       _, last_comment_content, j = 
204          self.src :match (self.patterns.long_comment, self.i)
205       if j then 
206          table_insert(self.attached_comments, 
207                          {last_comment_content, self.i, j, "long"})
208          self.i=j; again=true 
209       end
210       -- skip a short comment if any
211       last_comment_content, j = self.src:match (self.patterns.short_comment, self.i)
212       if j then
213          table_insert(self.attached_comments, 
214                          {last_comment_content, self.i, j, "short"})
215          self.i=j; again=true 
216       end
217       if self.i>#self.src then return "Eof", "eof" end
218    until not again
219
220    if self.src:match (self.patterns.final_short_comment, self.i) then 
221       return "Eof", "eof" end
222    --assert (not self.src:match(self.patterns.short_comment, self.i))
223    --assert (not self.src:match(self.patterns.long_comment, self.i))
224    -- --assert (not self.src:match(self.patterns.spaces, self.i))
225    return
226 end
227
228 ----------------------------------------------------------------------
229 -- extract a '...' or "..." short string
230 ----------------------------------------------------------------------
231 function lexer:extract_short_string()
232    -- [k] is the first unread char, [self.i] points to [k] in [self.src]
233    local j, k = self.i, self.src :sub (self.i,self.i)
234    if k~="'" and k~='"' then return end
235    local i = self.i + 1
236    local j = i
237    while true do
238       -- k = opening char: either simple-quote or double-quote
239       -- i = index of beginning-of-string
240       -- x = next "interesting" character
241       -- j = position after interesting char
242       -- y = char just after x
243       local x, y
244       x, j, y = self.src :match ("([\\\r\n"..k.."])()(.?)", j)
245       if x == '\\' then j=j+1  -- don't parse escaped char
246       elseif x == k then break -- unescaped end of string
247       else -- eof or '\r' or '\n' reached before end of string
248          assert (not x or x=="\r" or x=="\n")
249          error "Unterminated string"
250       end
251    end
252    self.i = j
253
254    return "String", unescape_string (self.src:sub (i,j-2))
255 end
256
257 ----------------------------------------------------------------------
258 --
259 ----------------------------------------------------------------------
260 function lexer:extract_word()
261    -- Id / keyword
262    local word, j = self.src:match (self.patterns.word, self.i)
263    if word then
264       self.i = j
265       if self.alpha [word] then return "Keyword", word
266       else return "Id", word end
267    end
268 end
269
270 ----------------------------------------------------------------------
271 --
272 ----------------------------------------------------------------------
273 function lexer:extract_number()
274    -- Number
275    local j = self.src:match(self.patterns.number_hex, self.i)
276    if not j then
277       j = self.src:match (self.patterns.number_mantissa[1], self.i) or
278           self.src:match (self.patterns.number_mantissa[2], self.i)
279       if j then
280          j = self.src:match (self.patterns.number_exponant, j) or j;
281       end
282    end
283    if not j then return end
284    -- Number found, interpret with tonumber() and return it
285    local n = tonumber (self.src:sub (self.i, j-1))
286    self.i = j
287    return "Number", n
288 end
289
290 ----------------------------------------------------------------------
291 --
292 ----------------------------------------------------------------------
293 function lexer:extract_long_string()
294    -- Long string
295    local _, content, j = self.src:match (self.patterns.long_string, self.i)
296    if j then self.i = j; return "String", content end
297 end
298
299 ----------------------------------------------------------------------
300 --
301 ----------------------------------------------------------------------
302 function lexer:extract_symbol()
303    -- compound symbol
304    local k = self.src:sub (self.i,self.i)
305    local symk = self.sym [k]
306    if not symk then 
307       self.i = self.i + 1
308       return "Keyword", k
309    end
310    for _, sym in pairs (symk) do
311       if sym == self.src:sub (self.i, self.i + #sym - 1) then 
312          self.i = self.i + #sym; 
313          return "Keyword", sym
314       end
315    end
316    -- single char symbol
317    self.i = self.i+1
318    return "Keyword", k
319 end
320
321 ----------------------------------------------------------------------
322 -- Add a keyword to the list of keywords recognized by the lexer.
323 ----------------------------------------------------------------------
324 function lexer:add (w, ...)
325    assert(not ..., "lexer:add() takes only one arg, although possibly a table")
326    if type (w) == "table" then
327       for _, x in ipairs (w) do self:add (x) end
328    else
329       if w:match (self.patterns.word .. "$") then self.alpha [w] = true
330       elseif w:match "^%p%p+$" then 
331          local k = w:sub(1,1)
332          local list = self.sym [k]
333          if not list then list = { }; self.sym [k] = list end
334          _G.table.insert (list, w)
335       elseif w:match "^%p$" then return
336       else error "Invalid keyword" end
337    end
338 end
339
340 ----------------------------------------------------------------------
341 -- Return the [n]th next token, without consumming it.
342 -- [n] defaults to 1. If it goes pass the end of the stream, an EOF
343 -- token is returned.
344 ----------------------------------------------------------------------
345 function lexer:peek (n)
346    if not n then n=1 end
347    if n > #self.peeked then
348       for i = #self.peeked+1, n do
349          self.peeked [i] = self:extract()
350       end
351    end
352   return self.peeked [n]
353 end
354
355 ----------------------------------------------------------------------
356 -- Return the [n]th next token, removing it as well as the 0..n-1
357 -- previous tokens. [n] defaults to 1. If it goes pass the end of the
358 -- stream, an EOF token is returned.
359 ----------------------------------------------------------------------
360 function lexer:next (n)
361    n = n or 1
362    self:peek (n)
363    local a
364    for i=1,n do 
365       a = _G.table.remove (self.peeked, 1) 
366       if a then 
367          --debugf ("lexer:next() ==> %s %s",
368          --        table.tostring(a), tostring(a))
369       end
370       self.lastline = a.lineinfo.last[1]
371    end
372    self.lineinfo_last = a.lineinfo.last
373    return a or eof_token
374 end
375
376 ----------------------------------------------------------------------
377 -- Returns an object which saves the stream's current state.
378 ----------------------------------------------------------------------
379 -- FIXME there are more fields than that to save
380 function lexer:save () return { self.i; _G.table.cat(self.peeked) } end
381
382 ----------------------------------------------------------------------
383 -- Restore the stream's state, as saved by method [save].
384 ----------------------------------------------------------------------
385 -- FIXME there are more fields than that to restore
386 function lexer:restore (s) self.i=s[1]; self.peeked=s[2] end
387
388 ----------------------------------------------------------------------
389 -- Resynchronize: cancel any token in self.peeked, by emptying the
390 -- list and resetting the indexes
391 ----------------------------------------------------------------------
392 function lexer:sync()
393    local p1 = self.peeked[1]
394    if p1 then 
395       li = p1.lineinfo.first
396       self.line, self.i = li[1], li[3]
397       self.column_offset = self.i - li[2]
398       self.peeked = { }
399       self.attached_comments = p1.lineinfo.first.comments or { }
400    end
401 end
402
403 ----------------------------------------------------------------------
404 -- Take the source and offset of an old lexer.
405 ----------------------------------------------------------------------
406 function lexer:takeover(old)
407    self:sync()
408    self.line, self.column_offset, self.i, self.src, self.attached_comments =
409       old.line, old.column_offset, old.i, old.src, old.attached_comments
410    return self
411 end
412
413 -- function lexer:lineinfo()
414 --      if self.peeked[1] then return self.peeked[1].lineinfo.first
415 --     else return { self.line, self.i-self.column_offset, self.i } end
416 -- end
417
418
419 ----------------------------------------------------------------------
420 -- Return the current position in the sources. This position is between
421 -- two tokens, and can be within a space / comment area, and therefore
422 -- have a non-null width. :lineinfo_left() returns the beginning of the
423 -- separation area, :lineinfo_right() returns the end of that area.
424 --
425 --    ____ last consummed token    ____ first unconsummed token
426 --   /                            /
427 -- XXXXX  <spaces and comments> YYYYY
428 --      \____                    \____
429 --           :lineinfo_left()         :lineinfo_right()
430 ----------------------------------------------------------------------
431 function lexer:lineinfo_right()
432    return self:peek(1).lineinfo.first
433 end
434
435 function lexer:lineinfo_left()
436    return self.lineinfo_last
437 end
438
439 ----------------------------------------------------------------------
440 -- Create a new lexstream.
441 ----------------------------------------------------------------------
442 function lexer:newstream (src_or_stream, name)
443    name = name or "?"
444    if type(src_or_stream)=='table' then -- it's a stream
445       return setmetatable ({ }, self) :takeover (src_or_stream)
446    elseif type(src_or_stream)=='string' then -- it's a source string
447       local src = src_or_stream
448       local stream = { 
449          src_name      = name;   -- Name of the file
450          src           = src;    -- The source, as a single string
451          peeked        = { };    -- Already peeked, but not discarded yet, tokens
452          i             = 1;      -- Character offset in src
453          line          = 1;      -- Current line number
454          column_offset = 0;      -- distance from beginning of file to last '\n'
455          attached_comments = { },-- comments accumulator
456          lineinfo_last = { 1, 1, 1, name }
457       }
458       setmetatable (stream, self)
459
460       -- skip initial sharp-bang for unix scripts
461       -- FIXME: redundant with mlp.chunk()
462       if src and src :match "^#" then stream.i = src :find "\n" + 1 end
463       return stream
464    else
465       assert(false, ":newstream() takes a source string or a stream, not a "..
466                     type(src_or_stream))
467    end
468 end
469
470 ----------------------------------------------------------------------
471 -- if there's no ... args, return the token a (whose truth value is
472 -- true) if it's a `Keyword{ }, or nil.  If there are ... args, they
473 -- have to be strings. if the token a is a keyword, and it's content
474 -- is one of the ... args, then returns it (it's truth value is
475 -- true). If no a keyword or not in ..., return nil.
476 ----------------------------------------------------------------------
477 function lexer:is_keyword (a, ...)
478    if not a or a.tag ~= "Keyword" then return false end
479    local words = {...}
480    if #words == 0 then return a[1] end
481    for _, w in ipairs (words) do
482       if w == a[1] then return w end
483    end
484    return false
485 end
486
487 ----------------------------------------------------------------------
488 -- Cause an error if the next token isn't a keyword whose content
489 -- is listed among ... args (which have to be strings).
490 ----------------------------------------------------------------------
491 function lexer:check (...)
492    local words = {...}
493    local a = self:next()
494    local function err ()
495       error ("Got " .. tostring (a) .. 
496              ", expected one of these keywords : '" ..
497              _G.table.concat (words,"', '") .. "'") end
498           
499    if not a or a.tag ~= "Keyword" then err () end
500    if #words == 0 then return a[1] end
501    for _, w in ipairs (words) do
502        if w == a[1] then return w end
503    end
504    err ()
505 end
506
507 ----------------------------------------------------------------------
508 -- 
509 ----------------------------------------------------------------------
510 function lexer:clone()
511    local clone = {
512       alpha = table.deep_copy(self.alpha),
513       sym   = table.deep_copy(self.sym) }
514    setmetatable(clone, self)
515    clone.__index = clone
516    return clone
517 end