1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Runtime library required by parsers and lexers generated by nitcc
18 # A abstract parser engine generated by nitcc
21 # FIXME: provide something better, like a lexer?
22 var tokens
= new List[NToken]
24 # Look at the next token
25 # Used by generated parsers
26 fun peek_token
: NToken do return tokens
.first
28 # Consume the next token
29 # Used by generated parsers
30 fun get_token
: NToken do return tokens
.shift
32 # Consume the next token and shift to the state `dest`.
33 # Used by generated parsers
34 fun shift
(dest
: LRState)
37 #print "shift {t} -> {dest}"
39 state_stack
.push state
43 # After a reduction on `goto` go to the next state
44 # Used by generated parsers
45 fun goto
(goto
: LRGoto)
47 #print "reduce from {state} -> {prod}"
48 state
.goto
(self, goto
)
51 # push a new state on the stack of states (
52 # Used by generated parsers
53 fun push
(dest
: LRState)
55 #print "push prod {prod} -> {dest}"
56 state_stack
.push state
60 # Pop and return the last node
61 # Also pop (and discard) the associated state
62 # Used by generated parsers
65 var res
= node_stack
.pop
66 state
= state_stack
.pop
70 # Produce a parse error and stop the parsing
71 # Used by generated parsers
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(", ")}"
80 if token
isa NLexerError then
83 error
= new NParserError
84 error
.position
= token
.position
85 error
.text
= token
.text
88 error
.error_tree
.items
.add_all
(node_stack
)
89 error
.expected
= state
.error_msg
95 # The stating state for parsing
96 # Used by generated parsers
97 protected fun start_state
: LRState is abstract
100 # Used by generated parsers
109 # Used by generated parsers
110 var node_stack
= new Array[Node]
112 # The stack of states
113 # Used by generated parsers
114 var state_stack
= new Array[LRState]
116 # Should the parser stop
117 # Used by generated parsers
118 var stop
writable = true
120 # Parse a full sequence of tokens and return a complete syntactic tree
128 #print "* current state {state}"
129 #print " tokens={tokens.join(" ")}"
130 #print " node_stack={node_stack.join(" ")}"
131 #print " state_stack={state_stack.join(" ")}"
135 return node_stack
.first
139 # A state in a parser LR automaton generated by nitcc
140 # Used by generated parsers
141 abstract class LRState
142 fun action
(parser
: Parser) is abstract
143 fun goto
(parser
: Parser, goto
: LRGoto) is abstract
144 fun error_msg
: String do return "FIXME"
147 # A concrete production in a parser LR automation generated by nitcc
148 # Used by generated parsers
149 abstract class LRGoto
154 # A abstract lexer engine generated by nitcc
156 # The input stream of characters
159 # The stating state for lexing
160 # Used by generated parsers
161 protected fun start_state
: DFAState is abstract
163 # Lexize a stream of characters and return a sequence of tokens
164 fun lex
: List[NToken]
166 var res
= new List[NToken]
167 var state
= start_state
177 var last_state
: nullable DFAState = null
179 var length
= text
.length
181 if state
.is_accept
then
188 if pos
>= length
then
193 var next
= state
.trans
(c
)
195 if pos_start
< length
then
196 if last_state
== null then
197 var token
= new NLexerError
198 var position
= new Position(pos_start
, pos
, line_start
, line
, col_start
, col
)
199 token
.position
= position
200 token
.text
= text
.substring
(pos_start
, pos-pos_start
+1)
204 var position
= new Position(pos_start
, pos_end
, line_start
, line_end
, col_start
, col_end
)
205 var token
= last_state
.make_token
(position
, text
.substring
(pos_start
, pos_end-pos_start
+1))
206 if token
!= null then res
.add
(token
)
208 if pos
>= length
then
210 var position
= new Position(pos
, pos
, line
, line
, col
, col
)
211 token
.position
= position
217 pos_start
= pos_end
+ 1
219 line_start
= line_end
239 # A state in a lexer automaton generated by nitcc
240 # Used by generated lexers
242 fun is_accept
: Bool do return false
243 fun trans
(c
: Char): nullable DFAState do return null
244 fun make_token
(position
: Position, text
: String): nullable NToken is abstract
249 # A abstract visitor on syntactic trees generated by nitcc
250 abstract class Visitor
251 # The main entry point to visit a node `n`
252 # Should not be redefined
253 fun enter_visit
(n
: Node)
258 # The specific implementation of a visit
260 # Should be redefined by concrete visitors
262 # Should not be called directly (use `enter_visit` instead)
264 # By default, the visitor just rescursively visit the children of `n`
265 protected fun visit
(n
: Node)
267 n
.visit_children
(self)
271 # Print a node (using to_s) on a line and recustively each children indented (with two spaces)
272 class TreePrinterVisitor
275 private var indent
= 0
276 init(writer
: OStream) do self.writer
= writer
279 for i
in [0..indent
[ do writer
.write
(" ")
288 # A position into a input stream
289 # Used to give position to tokens
297 redef fun to_s
do return "{line_start}:{col_start}-{line_end}:{col_end}"
300 # A node of a syntactic tree
302 # The name of the node (as used in the grammar file)
303 fun node_name
: String do return class_name
305 # A point of view on the direct childrens of the node
306 fun children
: SequenceRead[nullable Node] is abstract
308 # Visit all the children of the node with the visitor `v`
309 protected fun visit_children
(v
: Visitor)
311 for c
in children
do if c
!= null then v
.enter_visit
(c
)
314 # The position of the node in the input stream
315 var position
: nullable Position writable = null
317 # Produce a graphiz file for the syntaxtic tree rooted at `self`.
318 fun to_dot
(filepath
: String)
320 var f
= new OFStream.open
(filepath
)
321 f
.write
("digraph g \{\n")
322 f
.write
("rankdir=BT;\n")
324 var a
= new Array[NToken]
327 f
.write
("\{ rank=same\n")
335 f
.write
("n{n.object_id}")
337 f
.write
("[style=invis];\n")
344 private fun to_dot_visitor
(f
: OStream, a
: Array[NToken])
346 f
.write
("n{object_id} [label=\"{node_name}\
"];\n")
348 if x
== null then continue
349 f
.write
("n{x.object_id} -> n{object_id};\n")
350 x
.to_dot_visitor
(f
,a
)
359 return "{node_name}@({pos})"
364 # A token produced by the lexer and used in a syntactic tree
365 abstract class NToken
368 redef fun children
do return once
new Array[Node]
370 redef fun to_dot_visitor
(f
, a
)
372 var labe
= "{node_name}"
374 if pos
!= null then labe
+= "\\n{pos}"
376 if node_name
!= "'{text}'" then
377 labe
+= "\\n'{text.escape_to_c}'"
379 f
.write
("n{object_id} [label=\"{labe}\
",shape=box];\n")
383 # The text associated with the token
384 var text
: String writable = ""
389 if node_name
!= "'{text}'" then
390 res
+= "='{text.escape_to_c}'"
396 # The special token for the end of stream
401 # A special token used to represent a parser or lexer error
402 abstract class NError
405 # All the partially built tree during parsing (aka the node_stack)
406 var error_tree
= new Nodes[Node]
408 # The things unexpected
409 fun unexpected
: String is abstract
411 # The things expected (if any)
412 var expected
: nullable String = null
414 # The error message,using `expected` and `unexpected`
418 var res
= "Unexpected {unexpected}"
419 if exp
!= null then res
+= "; is acceptable instead: {exp}"
424 # A lexer error as a token for the unexpected characted
428 redef fun unexpected
do return "character '{text.first}'"
431 # A parser error linked to a unexpected token
434 # The unexpected token
435 var token
: nullable NToken
437 redef fun unexpected
do return token
.node_name
440 # A hogeneous sequence of node, used to represent unbounded lists (and + modifier)
443 redef fun children
do return items
444 var items
= new Array[T
]
447 # A production with a specific, named and statically typed childrens
450 redef var children
: SequenceRead[nullable Node] = new NProdChildren(self)
452 # The exact number of direct children
453 # Used to implement `children` by generated parsers
454 fun number_of_children
: Int is abstract
456 # The specific children got by its index
457 # Used to implement `children` by generated parsers
458 fun child
(x
: Int): nullable Node is abstract
462 private class NProdChildren
463 super SequenceRead[nullable Node]
465 redef fun iterator
do return new NProdIterator(prod
)
466 redef fun length
do return prod
.number_of_children
467 redef fun is_empty
do return prod
.number_of_children
== 0
468 redef fun [](i
) do return prod
.child
(i
)
471 private class NProdIterator
472 super IndexedIterator[nullable Node]
475 redef fun is_ok
do return index
< prod
.number_of_children
476 redef fun next
do index
+= 1
477 redef fun item
do return prod
.child
(index
)
480 # All-in-one abstract class to test generated parsers on a given
481 abstract class TestParser
482 # How to get a new lexer on a given stream of character
483 fun new_lexer
(text
: String): Lexer is abstract
485 # How to get a new parser
486 fun new_parser
: Parser is abstract
488 # The name of the language (used for generated files)
489 fun name
: String is abstract
491 # Use the class as the main enrty point of the program
492 # - parse arguments and options of the command
493 # - test the parser (see `work`)
496 if args
.is_empty
then
497 print
"usage {name}_test <filepath> | - | -e <text>"
501 var filepath
= args
.shift
503 if filepath
== "-" then
504 text
= stdin
.read_all
505 else if filepath
== "-e" then
506 if args
.is_empty
then
507 print
"Error: -e need a text"
512 var f
= new IFStream.open
(filepath
)
517 if not args
.is_empty
then
518 print
"Error: superfluous arguments."
525 # Produce a full syntactic tree for a given stream of character
526 # Produce also statistics and output files
527 fun work
(text
: String): Node
529 print
"INPUT: {text.length} chars"
530 var l
= new_lexer
(text
)
533 var tokout
= "{name}.tokens.out"
534 print
"TOKEN: {tokens.length} tokens (see {tokout})"
536 var f
= new OFStream.open
(tokout
)
543 p
.tokens
.add_all
(tokens
)
547 var astout
= "{name}.ast.out"
548 f
= new OFStream.open
(astout
)
549 var tpv
= new TreePrinterVisitor(f
)
550 var astdotout
= "{name}.ast.dot"
552 print
"Syntax error: {n.message}"
553 print
"ERROR: {n} (see {astout} and {astdotout})"
557 print
"ROOT: {n} (see {astout} and {astdotout})"