nitcc: add new PoV Node::depth
[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 List[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
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 writable = true
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: List[NToken]
166 do
167 var res = new List[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 if pos >= length then
190 c = '\0'
191 else
192 c = text[pos]
193 end
194 var next = state.trans(c)
195 if next == null then
196 if pos_start < length then
197 if last_state == null then
198 var token = new NLexerError
199 var position = new Position(pos_start, pos, line_start, line, col_start, col)
200 token.position = position
201 token.text = text.substring(pos_start, pos-pos_start+1)
202 res.add token
203 break
204 end
205 var position = new Position(pos_start, pos_end, line_start, line_end, col_start, col_end)
206 var token = last_state.make_token(position, text.substring(pos_start, pos_end-pos_start+1))
207 if token != null then res.add(token)
208 end
209 if pos >= length then
210 var token = new NEof
211 var position = new Position(pos, pos, line, line, col, col)
212 token.position = position
213 token.text = ""
214 res.add token
215 break
216 end
217 state = start_state
218 pos_start = pos_end + 1
219 pos = pos_start
220 line_start = line_end
221 line = line_start
222 col_start = col_end
223 col = col_start
224
225 last_state = null
226 continue
227 end
228 state = next
229 pos += 1
230 col += 1
231 if c == '\n' then
232 line += 1
233 col = 1
234 end
235 end
236 return res
237 end
238 end
239
240 # A state in a lexer automaton generated by nitcc
241 # Used by generated lexers
242 interface DFAState
243 fun is_accept: Bool do return false
244 fun trans(c: Char): nullable DFAState do return null
245 fun make_token(position: Position, text: String): nullable NToken is abstract
246 end
247
248 ###
249
250 # A abstract visitor on syntactic trees generated by nitcc
251 abstract class Visitor
252 # The main entry point to visit a node `n`
253 # Should not be redefined
254 fun enter_visit(n: Node)
255 do
256 visit(n)
257 end
258
259 # The specific implementation of a visit
260 #
261 # Should be redefined by concrete visitors
262 #
263 # Should not be called directly (use `enter_visit` instead)
264 #
265 # By default, the visitor just rescursively visit the children of `n`
266 protected fun visit(n: Node)
267 do
268 n.visit_children(self)
269 end
270 end
271
272 # Print a node (using to_s) on a line and recustively each children indented (with two spaces)
273 class TreePrinterVisitor
274 super Visitor
275 var writer: OStream
276 private var indent = 0
277 init(writer: OStream) do self.writer = writer
278 redef fun visit(n)
279 do
280 for i in [0..indent[ do writer.write(" ")
281 writer.write(n.to_s)
282 writer.write("\n")
283 indent += 1
284 super
285 indent -= 1
286 end
287 end
288
289 # A position into a input stream
290 # Used to give position to tokens
291 class Position
292 var pos_start: Int
293 var pos_end: Int
294 var line_start: Int
295 var line_end: Int
296 var col_start: Int
297 var col_end: Int
298 redef fun to_s do return "{line_start}:{col_start}-{line_end}:{col_end}"
299 end
300
301 # A node of a syntactic tree
302 abstract class Node
303 # The name of the node (as used in the grammar file)
304 fun node_name: String do return class_name
305
306 # A point of view on the direct children of the node
307 fun children: SequenceRead[nullable Node] is abstract
308
309 # A point of view of a depth-first visit of all non-null children
310 var depth: Collection[Node] = new DephCollection(self)
311
312 # Visit all the children of the node with the visitor `v`
313 protected fun visit_children(v: Visitor)
314 do
315 for c in children do if c != null then v.enter_visit(c)
316 end
317
318 # The position of the node in the input stream
319 var position: nullable Position writable = null
320
321 # Produce a graphiz file for the syntaxtic tree rooted at `self`.
322 fun to_dot(filepath: String)
323 do
324 var f = new OFStream.open(filepath)
325 f.write("digraph g \{\n")
326 f.write("rankdir=BT;\n")
327
328 var a = new Array[NToken]
329 to_dot_visitor(f, a)
330
331 f.write("\{ rank=same\n")
332 var first = true
333 for n in a do
334 if first then
335 first = false
336 else
337 f.write("->")
338 end
339 f.write("n{n.object_id}")
340 end
341 f.write("[style=invis];\n")
342 f.write("\}\n")
343
344 f.write("\}\n")
345 f.close
346 end
347
348 private fun to_dot_visitor(f: OStream, a: Array[NToken])
349 do
350 f.write("n{object_id} [label=\"{node_name}\"];\n")
351 for x in children do
352 if x == null then continue
353 f.write("n{x.object_id} -> n{object_id};\n")
354 x.to_dot_visitor(f,a )
355 end
356 end
357
358 redef fun to_s do
359 var pos = position
360 if pos == null then
361 return "{node_name}"
362 else
363 return "{node_name}@({pos})"
364 end
365 end
366 end
367
368 private class DephCollection
369 super NaiveCollection[Node]
370 var node: Node
371 redef fun iterator do return new DephIterator([node].iterator)
372 end
373
374 private class DephIterator
375 super Iterator[Node]
376 var stack = new List[Iterator[nullable Node]]
377
378 init(i: Iterator[nullable Node])
379 do
380 stack.add i
381 end
382
383 redef fun is_ok do return not stack.is_empty
384 redef fun item do return stack.last.item.as(not null)
385 redef fun next
386 do
387 var i = stack.last
388 stack.push i.item.children.iterator
389 i.next
390 while is_ok do
391 if not stack.last.is_ok then
392 stack.pop
393 continue
394 end
395 if stack.last.item == null then
396 stack.last.next
397 continue
398 end
399 return
400 end
401 end
402 end
403
404 # A token produced by the lexer and used in a syntactic tree
405 abstract class NToken
406 super Node
407
408 redef fun children do return once new Array[Node]
409
410 redef fun to_dot_visitor(f, a)
411 do
412 var labe = "{node_name}"
413 var pos = position
414 if pos != null then labe += "\\n{pos}"
415 var text = self.text
416 if node_name != "'{text}'" then
417 labe += "\\n'{text.escape_to_c}'"
418 end
419 f.write("n{object_id} [label=\"{labe}\",shape=box];\n")
420 a.add(self)
421 end
422
423 # The text associated with the token
424 var text: String writable = ""
425
426 redef fun to_s do
427 var res = super
428 var text = self.text
429 if node_name != "'{text}'" then
430 res += "='{text.escape_to_c}'"
431 end
432 return res
433 end
434 end
435
436 # The special token for the end of stream
437 class NEof
438 super NToken
439 end
440
441 # A special token used to represent a parser or lexer error
442 abstract class NError
443 super NToken
444
445 # All the partially built tree during parsing (aka the node_stack)
446 var error_tree = new Nodes[Node]
447
448 # The things unexpected
449 fun unexpected: String is abstract
450
451 # The things expected (if any)
452 var expected: nullable String = null
453
454 # The error message,using `expected` and `unexpected`
455 fun message: String
456 do
457 var exp = expected
458 var res = "Unexpected {unexpected}"
459 if exp != null then res += "; is acceptable instead: {exp}"
460 return res
461 end
462 end
463
464 # A lexer error as a token for the unexpected characted
465 class NLexerError
466 super NError
467
468 redef fun unexpected do return "character '{text.first}'"
469 end
470
471 # A parser error linked to a unexpected token
472 class NParserError
473 super NError
474 # The unexpected token
475 var token: nullable NToken
476
477 redef fun unexpected
478 do
479 var res = token.node_name
480 var text = token.text
481 if not text.is_empty and res != "'{text}'" then
482 res += " '{text.escape_to_c}'"
483 end
484 return res
485 end
486 end
487
488 # A hogeneous sequence of node, used to represent unbounded lists (and + modifier)
489 class Nodes[T: Node]
490 super Node
491 redef var children = new Array[T]
492 end
493
494 # A production with a specific, named and statically typed children
495 class NProd
496 super Node
497 redef var children: SequenceRead[nullable Node] = new NProdChildren(self)
498
499 # The exact number of direct children
500 # Used to implement `children` by generated parsers
501 fun number_of_children: Int is abstract
502
503 # The specific children got by its index
504 # Used to implement `children` by generated parsers
505 fun child(x: Int): nullable Node is abstract
506 end
507
508
509 private class NProdChildren
510 super SequenceRead[nullable Node]
511 var prod: NProd
512 redef fun iterator do return new NProdIterator(prod)
513 redef fun length do return prod.number_of_children
514 redef fun is_empty do return prod.number_of_children == 0
515 redef fun [](i) do return prod.child(i)
516 end
517
518 private class NProdIterator
519 super IndexedIterator[nullable Node]
520 var prod: NProd
521 redef var index = 0
522 redef fun is_ok do return index < prod.number_of_children
523 redef fun next do index += 1
524 redef fun item do return prod.child(index)
525 end
526
527 # All-in-one abstract class to test generated parsers on a given
528 abstract class TestParser
529 # How to get a new lexer on a given stream of character
530 fun new_lexer(text: String): Lexer is abstract
531
532 # How to get a new parser
533 fun new_parser: Parser is abstract
534
535 # The name of the language (used for generated files)
536 fun name: String is abstract
537
538 # Use the class as the main enrty point of the program
539 # - parse arguments and options of the command
540 # - test the parser (see `work`)
541 fun main: Node
542 do
543 if args.is_empty then
544 print "usage {name}_test <filepath> | - | -e <text>"
545 exit 0
546 end
547
548 var filepath = args.shift
549 var text
550 if filepath == "-" then
551 text = stdin.read_all
552 else if filepath == "-e" then
553 if args.is_empty then
554 print "Error: -e need a text"
555 exit 1
556 end
557 text = args.shift
558 else
559 var f = new IFStream.open(filepath)
560 text = f.read_all
561 f.close
562 end
563
564 if not args.is_empty then
565 print "Error: superfluous arguments."
566 exit 1
567 end
568
569 return work(text)
570 end
571
572 # Produce a full syntactic tree for a given stream of character
573 # Produce also statistics and output files
574 fun work(text: String): Node
575 do
576 print "INPUT: {text.length} chars"
577 var l = new_lexer(text)
578 var tokens = l.lex
579
580 var tokout = "{name}.tokens.out"
581 print "TOKEN: {tokens.length} tokens (see {tokout})"
582
583 var f = new OFStream.open(tokout)
584 for t in tokens do
585 f.write "{t.to_s}\n"
586 end
587 f.close
588
589 var p = new_parser
590 p.tokens.add_all(tokens)
591
592 var n = p.parse
593
594 var astout = "{name}.ast.out"
595 f = new OFStream.open(astout)
596 var tpv = new TreePrinterVisitor(f)
597 var astdotout = "{name}.ast.dot"
598 if n isa NError then
599 print "Syntax error: {n.message}"
600 print "ERROR: {n} (see {astout} and {astdotout})"
601 tpv.enter_visit(n)
602 n = n.error_tree
603 else
604 print "ROOT: {n}; {n.depth.length} nodes (see {astout} and {astdotout})"
605 end
606 tpv.enter_visit(n)
607 n.to_dot(astdotout)
608 f.close
609
610 return n
611 end
612 end