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