nitcc_rt: do not create ignored tokens
[nit.git] / lib / nitcc_runtime.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Runtime library required by parsers and lexers generated by nitcc
16 module nitcc_runtime
17
18 # A abstract parser engine generated by nitcc
19 abstract class Parser
20 # The list of tokens
21 # FIXME: provide something better, like a lexer?
22 var tokens = new CircularArray[NToken]
23
24 # Look at the next token
25 # Used by generated parsers
26 fun peek_token: NToken do return tokens.first
27
28 # Consume the next token
29 # Used by generated parsers
30 fun get_token: NToken do return tokens.shift
31
32 # Consume the next token and shift to the state `dest`.
33 # Used by generated parsers
34 fun shift(dest: LRState)
35 do
36 var t = get_token
37 #print "shift {t} -> {dest}"
38 node_stack.push t
39 state_stack.push state
40 state = dest
41 end
42
43 # After a reduction on `goto` go to the next state
44 # Used by generated parsers
45 fun goto(goto: LRGoto)
46 do
47 #print "reduce from {state} -> {prod}"
48 state.goto(self, goto)
49 end
50
51 # push a new state on the stack of states (
52 # Used by generated parsers
53 fun push(dest: LRState)
54 do
55 #print "push prod {prod} -> {dest}"
56 state_stack.push state
57 state = dest
58 end
59
60 # Pop and return the last node
61 # Also pop (and discard) the associated state
62 # Used by generated parsers
63 fun pop: Node
64 do
65 var res = node_stack.pop
66 state = state_stack.pop
67 return res
68 end
69
70 # Produce a parse error and stop the parsing
71 # Used by generated parsers
72 fun parse_error
73 do
74 var token = peek_token
75 #print "* parse error in state {state} on token {token}"
76 #print " expected: {state.error_msg}"
77 #print " node_stack={node_stack.join(", ")}"
78 #print " state_stack={state_stack.join(", ")}"
79 node_stack.add(token)
80 var error: NError
81 if token isa NLexerError then
82 error = token
83 else
84 error = new NParserError
85 error.position = token.position
86 error.text = token.text
87 error.token = token
88 end
89 error.error_tree.children.add_all(node_stack)
90 error.expected = state.error_msg
91 node_stack.clear
92 node_stack.add error
93 stop = true
94 end
95
96 # The stating state for parsing
97 # Used by generated parsers
98 protected fun start_state: LRState is abstract
99
100 # The current state
101 # Used by generated parsers
102 var state: LRState is noinit
103
104 init
105 do
106 state = start_state
107 end
108
109 # The stack of nodes
110 # Used by generated parsers
111 var node_stack = new Array[Node]
112
113 # The stack of states
114 # Used by generated parsers
115 var state_stack = new Array[LRState]
116
117 # Should the parser stop
118 # Used by generated parsers
119 var stop = true is writable
120
121 # Parse a full sequence of tokens and return a complete syntactic tree
122 fun parse: Node
123 do
124 state = start_state
125 state_stack.clear
126 node_stack.clear
127 stop = false
128 while not stop do
129 #print "* current state {state}"
130 #print " tokens={tokens.join(" ")}"
131 #print " node_stack={node_stack.join(" ")}"
132 #print " state_stack={state_stack.join(" ")}"
133 state.action(self)
134 end
135 #print "* over"
136 return node_stack.first
137 end
138 end
139
140 # A state in a parser LR automaton generated by nitcc
141 # Used by generated parsers
142 abstract class LRState
143 fun action(parser: Parser) is abstract
144 fun goto(parser: Parser, goto: LRGoto) is abstract
145 fun error_msg: String do return "FIXME"
146 end
147
148 # A concrete production in a parser LR automation generated by nitcc
149 # Used by generated parsers
150 abstract class LRGoto
151 end
152
153 ###
154
155 # A abstract lexer engine generated by nitcc
156 abstract class Lexer
157 # The input stream of characters
158 var stream: String
159
160 # The stating state for lexing
161 # Used by generated parsers
162 protected fun start_state: DFAState is abstract
163
164 # Lexize a stream of characters and return a sequence of tokens
165 fun lex: CircularArray[NToken]
166 do
167 var res = new CircularArray[NToken]
168 var state = start_state
169 var pos = 0
170 var pos_start = 0
171 var pos_end = 0
172 var line = 1
173 var line_start = 1
174 var line_end = 0
175 var col = 1
176 var col_start = 1
177 var col_end = 0
178 var last_state: nullable DFAState = null
179 var text = stream
180 var length = text.length
181 loop
182 if state.is_accept then
183 pos_end = pos - 1
184 line_end = line
185 col_end = col
186 last_state = state
187 end
188 var c
189 var next
190 if pos >= length then
191 c = '\0'
192 next = null
193 else
194 c = text.chars[pos]
195 next = state.trans(c)
196 end
197 if next == null then
198 if pos_start < length then
199 if last_state == null then
200 var token = new NLexerError
201 var position = new Position(pos_start, pos, line_start, line, col_start, col)
202 token.position = position
203 token.text = text.substring(pos_start, pos-pos_start+1)
204 res.add token
205 break
206 end
207 if not last_state.is_ignored then
208 var position = new Position(pos_start, pos_end, line_start, line_end, col_start, col_end)
209 var token = last_state.make_token(position, text.substring(pos_start, pos_end-pos_start+1))
210 if token != null then res.add(token)
211 end
212 end
213 if pos >= length then
214 var token = new NEof
215 var position = new Position(pos, pos, line, line, col, col)
216 token.position = position
217 token.text = ""
218 res.add token
219 break
220 end
221 state = start_state
222 pos_start = pos_end + 1
223 pos = pos_start
224 line_start = line_end
225 line = line_start
226 col_start = col_end
227 col = col_start
228
229 last_state = null
230 continue
231 end
232 state = next
233 pos += 1
234 col += 1
235 if c == '\n' then
236 line += 1
237 col = 1
238 end
239 end
240 return res
241 end
242 end
243
244 # A state in a lexer automaton generated by nitcc
245 # Used by generated lexers
246 interface DFAState
247 fun is_accept: Bool do return false
248 fun trans(c: Char): nullable DFAState do return null
249 fun make_token(position: Position, text: String): nullable NToken is abstract
250 fun is_ignored: Bool do return false
251 end
252
253 ###
254
255 # A abstract visitor on syntactic trees generated by nitcc
256 abstract class Visitor
257 # The main entry point to visit a node `n`
258 # Should not be redefined
259 fun enter_visit(n: Node)
260 do
261 visit(n)
262 end
263
264 # The specific implementation of a visit
265 #
266 # Should be redefined by concrete visitors
267 #
268 # Should not be called directly (use `enter_visit` instead)
269 #
270 # By default, the visitor just rescursively visit the children of `n`
271 protected fun visit(n: Node)
272 do
273 n.visit_children(self)
274 end
275 end
276
277 # Print a node (using to_s) on a line and recustively each children indented (with two spaces)
278 class TreePrinterVisitor
279 super Visitor
280 var writer: Writer
281 private var indent = 0
282 redef fun visit(n)
283 do
284 for i in [0..indent[ do writer.write(" ")
285 writer.write(n.to_s)
286 writer.write("\n")
287 indent += 1
288 super
289 indent -= 1
290 end
291 end
292
293 # A position into a input stream
294 # Used to give position to tokens
295 class Position
296 var pos_start: Int
297 var pos_end: Int
298 var line_start: Int
299 var line_end: Int
300 var col_start: Int
301 var col_end: Int
302
303 redef fun to_s do return "{line_start}:{col_start}-{line_end}:{col_end}"
304
305 # Get the lines covered by `self` and underline the target columns.
306 #
307 # This is useful for pretty printing errors or debug the output
308 #
309 # ~~~
310 # var src = "var Foo = new Array[Int]"
311 # var pos = new Position(0,0, 1, 1, 5, 8)
312 #
313 # assert pos.underline(src) == """
314 # var Foo = new Array[Int]
315 # ^^^"""
316 # ~~~
317 fun underline(source: Text): String
318 do
319 var res = new FlatBuffer
320
321 # All the concerned lines
322 var lines = source.split("\n")
323 for line in [line_start..line_end] do
324 res.append lines[line-1]
325 res.append "\n"
326 end
327
328 # Cover all columns, no matter their lines
329 var col_start = col_start.min(col_end)
330 var col_end = self.col_start.max(col_end)
331
332 # " ^^^^"
333 var ptr = " "*(col_start-1).max(0) + "^"*(col_end-col_start)
334 res.append ptr
335
336 return res.to_s
337 end
338 end
339
340 # A node of a syntactic tree
341 abstract class Node
342 # The name of the node (as used in the grammar file)
343 fun node_name: String do return class_name
344
345 # A point of view on the direct children of the node
346 fun children: SequenceRead[nullable Node] is abstract
347
348 # A point of view of a depth-first visit of all non-null children
349 var depth: Collection[Node] = new DephCollection(self) is lazy
350
351 # Visit all the children of the node with the visitor `v`
352 protected fun visit_children(v: Visitor)
353 do
354 for c in children do if c != null then v.enter_visit(c)
355 end
356
357 # The position of the node in the input stream
358 var position: nullable Position = null is writable
359
360 # Produce a graphiz file for the syntaxtic tree rooted at `self`.
361 fun to_dot(filepath: String)
362 do
363 var f = new FileWriter.open(filepath)
364 f.write("digraph g \{\n")
365 f.write("rankdir=BT;\n")
366
367 var a = new Array[NToken]
368 to_dot_visitor(f, a)
369
370 f.write("\{ rank=same\n")
371 var first = true
372 for n in a do
373 if first then
374 first = false
375 else
376 f.write("->")
377 end
378 f.write("n{n.object_id}")
379 end
380 f.write("[style=invis];\n")
381 f.write("\}\n")
382
383 f.write("\}\n")
384 f.close
385 end
386
387 private fun to_dot_visitor(f: Writer, a: Array[NToken])
388 do
389 f.write("n{object_id} [label=\"{node_name}\"];\n")
390 for x in children do
391 if x == null then continue
392 f.write("n{x.object_id} -> n{object_id};\n")
393 x.to_dot_visitor(f,a )
394 end
395 end
396
397 redef fun to_s do
398 var pos = position
399 if pos == null then
400 return "{node_name}"
401 else
402 return "{node_name}@({pos})"
403 end
404 end
405 end
406
407 private class DephCollection
408 super Collection[Node]
409 var node: Node
410 redef fun iterator do return new DephIterator([node].iterator)
411 end
412
413 private class DephIterator
414 super Iterator[Node]
415
416 var stack = new List[Iterator[nullable Node]]
417
418 init(i: Iterator[nullable Node]) is old_style_init do
419 stack.add i
420 end
421
422 redef fun is_ok do return not stack.is_empty
423 redef fun item do return stack.last.item.as(not null)
424 redef fun next
425 do
426 var i = stack.last
427 stack.push i.item.children.iterator
428 i.next
429 while is_ok do
430 if not stack.last.is_ok then
431 stack.pop
432 continue
433 end
434 if stack.last.item == null then
435 stack.last.next
436 continue
437 end
438 return
439 end
440 end
441 end
442
443 # A token produced by the lexer and used in a syntactic tree
444 abstract class NToken
445 super Node
446
447 redef fun children do return once new Array[Node]
448
449 redef fun to_dot_visitor(f, a)
450 do
451 var labe = "{node_name}"
452 var pos = position
453 if pos != null then labe += "\\n{pos}"
454 var text = self.text
455 if node_name != "'{text}'" then
456 labe += "\\n'{text.escape_to_c}'"
457 end
458 f.write("n{object_id} [label=\"{labe}\",shape=box];\n")
459 a.add(self)
460 end
461
462 # The text associated with the token
463 var text: String = "" is writable
464
465 redef fun to_s do
466 var res = super
467 var text = self.text
468 if node_name != "'{text}'" then
469 res += "='{text.escape_to_c}'"
470 end
471 return res
472 end
473 end
474
475 # The special token for the end of stream
476 class NEof
477 super NToken
478 end
479
480 # A special token used to represent a parser or lexer error
481 abstract class NError
482 super NToken
483
484 # All the partially built tree during parsing (aka the node_stack)
485 var error_tree = new Nodes[Node]
486
487 # The things unexpected
488 fun unexpected: String is abstract
489
490 # The things expected (if any)
491 var expected: nullable String = null
492
493 # The error message,using `expected` and `unexpected`
494 fun message: String
495 do
496 var exp = expected
497 var res = "Unexpected {unexpected}"
498 if exp != null then res += "; is acceptable instead: {exp}"
499 return res
500 end
501 end
502
503 # A lexer error as a token for the unexpected characted
504 class NLexerError
505 super NError
506
507 redef fun unexpected do return "character '{text.chars.first}'"
508 end
509
510 # A parser error linked to a unexpected token
511 class NParserError
512 super NError
513
514 # The unexpected token
515 var token: nullable NToken = null
516
517 redef fun unexpected
518 do
519 var res = token.node_name
520 var text = token.text
521 if not text.is_empty and res != "'{text}'" then
522 res += " '{text.escape_to_c}'"
523 end
524 return res
525 end
526 end
527
528 # A hogeneous sequence of node, used to represent unbounded lists (and + modifier)
529 class Nodes[T: Node]
530 super Node
531 redef var children: Array[T] = new Array[T]
532 end
533
534 # A production with a specific, named and statically typed children
535 abstract class NProd
536 super Node
537 redef var children: SequenceRead[nullable Node] = new NProdChildren(self)
538
539 # The exact number of direct children
540 # Used to implement `children` by generated parsers
541 fun number_of_children: Int is abstract
542
543 # The specific children got by its index
544 # Used to implement `children` by generated parsers
545 fun child(x: Int): nullable Node is abstract
546 end
547
548
549 private class NProdChildren
550 super SequenceRead[nullable Node]
551 var prod: NProd
552 redef fun iterator do return new NProdIterator(prod)
553 redef fun length do return prod.number_of_children
554 redef fun is_empty do return prod.number_of_children == 0
555 redef fun [](i) do return prod.child(i)
556 end
557
558 private class NProdIterator
559 super IndexedIterator[nullable Node]
560 var prod: NProd
561 redef var index = 0
562 redef fun is_ok do return index < prod.number_of_children
563 redef fun next do index += 1
564 redef fun item do return prod.child(index)
565 end
566
567 # All-in-one abstract class to test generated parsers on a given
568 abstract class TestParser
569 # How to get a new lexer on a given stream of character
570 fun new_lexer(text: String): Lexer is abstract
571
572 # How to get a new parser
573 fun new_parser: Parser is abstract
574
575 # The name of the language (used for generated files)
576 fun name: String is abstract
577
578 # Use the class as the main enrty point of the program
579 # - parse arguments and options of the command
580 # - test the parser (see `work`)
581 fun main: Node
582 do
583 if args.is_empty then
584 print "usage {name}_test <filepath> | - | -e <text>"
585 exit 0
586 end
587
588 var filepath = args.shift
589 var text
590 if filepath == "-" then
591 text = sys.stdin.read_all
592 else if filepath == "-e" then
593 if args.is_empty then
594 print "Error: -e need a text"
595 exit 1
596 end
597 text = args.shift
598 else
599 var f = new FileReader.open(filepath)
600 text = f.read_all
601 f.close
602 end
603
604 if not args.is_empty then
605 print "Error: superfluous arguments."
606 exit 1
607 end
608
609 return work(text)
610 end
611
612 # Produce a full syntactic tree for a given stream of character
613 # Produce also statistics and output files
614 fun work(text: String): Node
615 do
616 print "INPUT: {text.length} chars"
617 var l = new_lexer(text)
618 var tokens = l.lex
619
620 var tokout = "{name}.tokens.out"
621 print "TOKEN: {tokens.length} tokens (see {tokout})"
622
623 var f = new FileWriter.open(tokout)
624 for t in tokens do
625 f.write "{t.to_s}\n"
626 end
627 f.close
628
629 var p = new_parser
630 p.tokens.add_all(tokens)
631
632 var n = p.parse
633
634 var astout = "{name}.ast.out"
635 f = new FileWriter.open(astout)
636 var tpv = new TreePrinterVisitor(f)
637 var astdotout = "{name}.ast.dot"
638 if n isa NError then
639 print "Syntax error: {n.message}"
640 print "ERROR: {n} (see {astout} and {astdotout})"
641 tpv.enter_visit(n)
642 n = n.error_tree
643 else
644 print "ROOT: {n}; {n.depth.length} nodes (see {astout} and {astdotout})"
645 end
646 tpv.enter_visit(n)
647 n.to_dot(astdotout)
648 f.close
649
650 return n
651 end
652 end