]> git.lizzy.rs Git - metalua.git/blob - src/compiler/lexer.lua
Added filename reference in lineinfo, fixed positions reporting
[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%.%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]+)", 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 ----------------------------------------------------------------------
102 -- Really extract next token fron the raw string 
103 -- (and update the index).
104 -- loc: offset of the position just after spaces and comments
105 -- previous_i: offset in src before extraction began
106 ----------------------------------------------------------------------
107 function lexer:extract ()
108    local previous_i = self.i
109    local loc = self.i
110    local eof, token
111
112    -- Put line info, comments and metatable arount the tag and content
113    -- provided by extractors, thus returning a complete lexer token.
114    -- first_line: line # at the beginning of token
115    -- first_column_offset: char # of the last '\n' before beginning of token
116    -- i: scans from beginning of prefix spaces/comments to end of token.
117    local function build_token (tag, content)
118       assert (tag and content)
119       local i, first_line, first_column_offset, previous_line_length =
120          previous_i, self.line, self.column_offset, nil
121
122       -- update self.line and first_line. i := indexes of '\n' chars
123       while true do
124          i = self.src :find ("\n", i+1, true)
125          if not i or i>self.i then break end -- no more '\n' until end of token
126          previous_line_length = i - self.column_offset
127          if loc and i <= loc then -- '\n' before beginning of token
128             first_column_offset = i
129             first_line = first_line+1 
130          end
131          self.line   = self.line+1 
132          self.column_offset = i 
133       end
134
135       -- lineinfo entries: [1]=line, [2]=column, [3]=char, [4]=filename
136       local fli = { first_line, loc-first_column_offset, loc, self.src_name }
137       local lli = { self.line, self.i-self.column_offset-1, self.i-1, self.src_name }
138       local a = { tag = tag, lineinfo = { first=fli, last=lli }, content } 
139       if lli[2]==-1 then lli[1], lli[2] = lli[1]-1, previous_line_length-1 end
140       if #self.attached_comments > 0 then 
141          a.lineinfo.comments = self.attached_comments 
142          self.attached_comments = nil
143       end
144       self.attached_comments = { }
145       return setmetatable (a, self.token_metatable)
146    end --</function build_token>
147
148    for ext_idx, extractor in ipairs(self.extractors) do
149       -- printf("method = %s", method)
150       local tag, content = self [extractor] (self)
151       -- [loc] is placed just after the leading whitespaces and comments;
152       -- for this to work, the whitespace extractor *must be* at index 1.
153       if ext_idx==1 then loc = self.i end
154
155       if tag then 
156          --printf("`%s{ %q }\t%i", tag, content, loc);
157          return build_token (tag, content) 
158       end
159    end
160
161    error "None of the lexer extractors returned anything!"
162 end   
163
164 ----------------------------------------------------------------------
165 -- skip whites and comments
166 -- FIXME: doesn't take into account:
167 -- - unterminated long comments
168 -- - short comments at last line without a final \n
169 ----------------------------------------------------------------------
170 function lexer:skip_whitespaces_and_comments()
171    local table_insert = _G.table.insert
172    repeat -- loop as long as a space or comment chunk is found
173       local _, j
174       local again = false
175       local last_comment_content = nil
176       -- skip spaces
177       self.i = self.src:match (self.patterns.spaces, self.i)
178       -- skip a long comment if any
179       _, last_comment_content, j = 
180          self.src :match (self.patterns.long_comment, self.i)
181       if j then 
182          table_insert(self.attached_comments, 
183                          {last_comment_content, self.i, j, "long"})
184          self.i=j; again=true 
185       end
186       -- skip a short comment if any
187       last_comment_content, j = self.src:match (self.patterns.short_comment, self.i)
188       if j then
189          table_insert(self.attached_comments, 
190                          {last_comment_content, self.i, j, "short"})
191          self.i=j; again=true 
192       end
193       if self.i>#self.src then return "Eof", "eof" end
194    until not again
195
196    if self.src:match (self.patterns.final_short_comment, self.i) then 
197       return "Eof", "eof" end
198    --assert (not self.src:match(self.patterns.short_comment, self.i))
199    --assert (not self.src:match(self.patterns.long_comment, self.i))
200    -- --assert (not self.src:match(self.patterns.spaces, self.i))
201    return
202 end
203
204 ----------------------------------------------------------------------
205 -- extract a '...' or "..." short string
206 ----------------------------------------------------------------------
207 function lexer:extract_short_string()
208    -- [k] is the first unread char, [self.i] points to [k] in [self.src]
209    local j, k = self.i, self.src :sub (self.i,self.i)
210    if k~="'" and k~='"' then return end
211    local i = self.i + 1
212    local j = i
213    while true do
214       -- k = opening char: either simple-quote or double-quote
215       -- i = index of beginning-of-string
216       -- x = next "interesting" character
217       -- j = position after interesting char
218       -- y = char just after x
219       local x, y
220       x, j, y = self.src :match ("([\\\r\n"..k.."])()(.?)", j)
221       if x == '\\' then j=j+1  -- don't parse escaped char
222       elseif x == k then break -- unescaped end of string
223       else -- eof or '\r' or '\n' reached before end of string
224          assert (not x or x=="\r" or x=="\n")
225          error "Unterminated string"
226       end
227    end
228    self.i = j
229
230    return "String", unescape_string (self.src:sub (i,j-2))
231 end
232
233 ----------------------------------------------------------------------
234 --
235 ----------------------------------------------------------------------
236 function lexer:extract_word()
237    -- Id / keyword
238    local word, j = self.src:match (self.patterns.word, self.i)
239    if word then
240       self.i = j
241       if self.alpha [word] then return "Keyword", word
242       else return "Id", word end
243    end
244 end
245
246 ----------------------------------------------------------------------
247 --
248 ----------------------------------------------------------------------
249 function lexer:extract_number()
250    -- Number
251    local j = self.src:match(self.patterns.number_hex, self.i)
252    if not j then
253       j = self.src:match (self.patterns.number_mantissa[1], self.i) or
254           self.src:match (self.patterns.number_mantissa[2], self.i)
255       if j then
256          j = self.src:match (self.patterns.number_exponant, j) or j;
257       end
258    end
259    if not j then return end
260    -- Number found, interpret with tonumber() and return it
261    local n = tonumber (self.src:sub (self.i, j-1))
262    self.i = j
263    return "Number", n
264 end
265
266 ----------------------------------------------------------------------
267 --
268 ----------------------------------------------------------------------
269 function lexer:extract_long_string()
270    -- Long string
271    local _, content, j = self.src:match (self.patterns.long_string, self.i)
272    if j then self.i = j; return "String", content end
273 end
274
275 ----------------------------------------------------------------------
276 --
277 ----------------------------------------------------------------------
278 function lexer:extract_symbol()
279    -- compound symbol
280    local k = self.src:sub (self.i,self.i)
281    local symk = self.sym [k]
282    if not symk then 
283       self.i = self.i + 1
284       return "Keyword", k
285    end
286    for _, sym in pairs (symk) do
287       if sym == self.src:sub (self.i, self.i + #sym - 1) then 
288          self.i = self.i + #sym; 
289          return "Keyword", sym
290       end
291    end
292    -- single char symbol
293    self.i = self.i+1
294    return "Keyword", k
295 end
296
297 ----------------------------------------------------------------------
298 -- Add a keyword to the list of keywords recognized by the lexer.
299 ----------------------------------------------------------------------
300 function lexer:add (w, ...)
301    assert(not ..., "lexer:add() takes only one arg, although possibly a table")
302    if type (w) == "table" then
303       for _, x in ipairs (w) do self:add (x) end
304    else
305       if w:match (self.patterns.word .. "$") then self.alpha [w] = true
306       elseif w:match "^%p%p+$" then 
307          local k = w:sub(1,1)
308          local list = self.sym [k]
309          if not list then list = { }; self.sym [k] = list end
310          _G.table.insert (list, w)
311       elseif w:match "^%p$" then return
312       else error "Invalid keyword" end
313    end
314 end
315
316 ----------------------------------------------------------------------
317 -- Return the [n]th next token, without consumming it.
318 -- [n] defaults to 1. If it goes pass the end of the stream, an EOF
319 -- token is returned.
320 ----------------------------------------------------------------------
321 function lexer:peek (n)
322    if not n then n=1 end
323    if n > #self.peeked then
324       for i = #self.peeked+1, n do
325          self.peeked [i] = self:extract()
326       end
327    end
328   return self.peeked [n]
329 end
330
331 ----------------------------------------------------------------------
332 -- Return the [n]th next token, removing it as well as the 0..n-1
333 -- previous tokens. [n] defaults to 1. If it goes pass the end of the
334 -- stream, an EOF token is returned.
335 ----------------------------------------------------------------------
336 function lexer:next (n)
337    n = n or 1
338    self:peek (n)
339    local a
340    for i=1,n do 
341       a = _G.table.remove (self.peeked, 1) 
342       if a then 
343          --debugf ("lexer:next() ==> %s %s",
344          --        table.tostring(a), tostring(a))
345       end
346       self.lastline = a.lineinfo.last[1]
347    end
348    self.lineinfo_last = a.lineinfo.last
349    return a or eof_token
350 end
351
352 ----------------------------------------------------------------------
353 -- Returns an object which saves the stream's current state.
354 ----------------------------------------------------------------------
355 -- FIXME there are more fields than that to save
356 function lexer:save () return { self.i; _G.table.cat(self.peeked) } end
357
358 ----------------------------------------------------------------------
359 -- Restore the stream's state, as saved by method [save].
360 ----------------------------------------------------------------------
361 -- FIXME there are more fields than that to restore
362 function lexer:restore (s) self.i=s[1]; self.peeked=s[2] end
363
364 ----------------------------------------------------------------------
365 -- Resynchronize: cancel any token in self.peeked, by emptying the
366 -- list and resetting the indexes
367 ----------------------------------------------------------------------
368 function lexer:sync()
369    local p1 = self.peeked[1]
370    if p1 then 
371       li = p1.lineinfo.first
372       self.line, self.i = li[1], li[3]
373       self.column_offset = self.i - li[2]
374       self.peeked = { }
375       self.attached_comments = p1.lineinfo.comments or { }
376    end
377 end
378
379 ----------------------------------------------------------------------
380 -- Take the source and offset of an old lexer.
381 ----------------------------------------------------------------------
382 function lexer:takeover(old)
383    self:sync()
384    self.line, self.column_offset, self.i, self.src, self.attached_comments =
385       old.line, old.column_offset, old.i, old.src, old.attached_comments
386    return self
387 end
388
389 -- function lexer:lineinfo()
390 --      if self.peeked[1] then return self.peeked[1].lineinfo.first
391 --     else return { self.line, self.i-self.column_offset, self.i } end
392 -- end
393
394
395 ----------------------------------------------------------------------
396 -- Return the current position in the sources. This position is between
397 -- two tokens, and can be within a space / comment area, and therefore
398 -- have a non-null width. :lineinfo_left() returns the beginning of the
399 -- separation area, :lineinfo_right() returns the end of that area.
400 --
401 --    ____ last consummed token    ____ first unconsummed token
402 --   /                            /
403 -- XXXXX  <spaces and comments> YYYYY
404 --      \____                    \____
405 --           :lineinfo_left()         :lineinfo_right()
406 ----------------------------------------------------------------------
407 function lexer:lineinfo_right()
408    return self:peek(1).lineinfo.first
409 end
410
411 function lexer:lineinfo_left()
412    return self.lineinfo_last
413 end
414
415 ----------------------------------------------------------------------
416 -- Create a new lexstream.
417 ----------------------------------------------------------------------
418 function lexer:newstream (src_or_stream, name)
419    name = name or "?"
420    if type(src_or_stream)=='table' then -- it's a stream
421       return setmetatable ({ }, self) :takeover (src_or_stream)
422    elseif type(src_or_stream)=='string' then -- it's a source string
423       local src = src_or_stream
424       local stream = { 
425          src_name      = name;   -- Name of the file
426          src           = src;    -- The source, as a single string
427          peeked        = { };    -- Already peeked, but not discarded yet, tokens
428          i             = 1;      -- Character offset in src
429          line          = 1;      -- Current line number
430          column_offset = 0;      -- distance from beginning of file to last '\n'
431          attached_comments = { },-- comments accumulator
432          lineinfo_last = { 1, 1, 1, name }
433       }
434       setmetatable (stream, self)
435
436       -- skip initial sharp-bang for unix scripts
437       -- FIXME: redundant with mlp.chunk()
438       if src and src :match "^#" then stream.i = src :find "\n" + 1 end
439       return stream
440    else
441       assert(false, ":newstream() takes a source string or a stream, not a "..
442                     type(src_or_stream))
443    end
444 end
445
446 ----------------------------------------------------------------------
447 -- if there's no ... args, return the token a (whose truth value is
448 -- true) if it's a `Keyword{ }, or nil.  If there are ... args, they
449 -- have to be strings. if the token a is a keyword, and it's content
450 -- is one of the ... args, then returns it (it's truth value is
451 -- true). If no a keyword or not in ..., return nil.
452 ----------------------------------------------------------------------
453 function lexer:is_keyword (a, ...)
454    if not a or a.tag ~= "Keyword" then return false end
455    local words = {...}
456    if #words == 0 then return a[1] end
457    for _, w in ipairs (words) do
458       if w == a[1] then return w end
459    end
460    return false
461 end
462
463 ----------------------------------------------------------------------
464 -- Cause an error if the next token isn't a keyword whose content
465 -- is listed among ... args (which have to be strings).
466 ----------------------------------------------------------------------
467 function lexer:check (...)
468    local words = {...}
469    local a = self:next()
470    local function err ()
471       error ("Got " .. tostring (a) .. 
472              ", expected one of these keywords : '" ..
473              _G.table.concat (words,"', '") .. "'") end
474           
475    if not a or a.tag ~= "Keyword" then err () end
476    if #words == 0 then return a[1] end
477    for _, w in ipairs (words) do
478        if w == a[1] then return w end
479    end
480    err ()
481 end
482
483 ----------------------------------------------------------------------
484 -- 
485 ----------------------------------------------------------------------
486 function lexer:clone()
487    local clone = {
488       alpha = table.deep_copy(self.alpha),
489       sym   = table.deep_copy(self.sym) }
490    setmetatable(clone, self)
491    clone.__index = clone
492    return clone
493 end