1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2008 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Program used to test the NIT parser
24 # A basic visitor that prints AST trees to the screen
25 class PrintTreeVisitor
27 private var rank
: Int = 0
31 printn
(" " * rank
, n
.class_name
, " \"", n.text.escape_to_c, "\
" ", n
.location
, "\n")
33 printn
(" " * rank
, n
.class_name
, " ", n
.location
, "\n")
42 var only_lexer
= false
45 var interactive
= false
48 while not args
.is_empty
and args
.first
.chars
.first
== '-' do
49 if args
.first
== "-n" then
51 else if args
.first
== "-l" then
53 else if args
.first
== "-p" then
55 else if args
.first
== "-x" then
57 else if args
.first
== "-e" then
59 else if args
.first
== "-i" then
61 else if args
.first
== "-h" or args
.first
== "-?" then
64 stderr
.write
("Unknown option {args.first}.\n")
70 if (args
.is_empty
and not interactive
) or need_help
then
72 print
(" test_parser [options]... <filename.nit>...")
73 print
(" test_parser -e [options]... <text>...")
74 print
(" test_parser -i [options]...")
76 print
(" -n do not print anything")
77 print
(" -l only lexer")
78 print
(" -p lexer and parser (default)")
79 print
(" -x instead of a ascii tree, output a XML document")
80 print
(" -e instead on files, each argument is a content to parse")
81 print
(" -i tree to parse are read interactively")
82 print
(" -h print this help")
83 else if interactive
then
85 print
"Error: -l and -i are incompatible"
88 print
"Error: -e and -i are incompatible"
90 else if not args
.is_empty
then
91 print
"Error: -i works without arguments"
95 var tc
= new ToolContext
98 var n
= tc
.interactive_parse
("-->")
110 print
"{n.location.colored_line("0;31")}: {n.message}"
115 (new PrintTreeVisitor).enter_visit
(n
)
122 source
= new SourceFile.from_string
("", a
)
124 var f
= new FileReader.open
(a
)
125 source
= new SourceFile(a
, f
)
128 var lexer
= new Lexer(source
)
130 var token
= lexer
.next
131 while not token
isa EOF do
133 print
("Read token at {token.location} text='{token.text}'")
138 var parser
= new Parser(lexer
)
139 var tree
= parser
.parse
141 var error
= tree
.n_eof
142 if error
isa AError then
143 print
("Error at {error.location}:\n\t{error.message}")
148 tree
.parentize_tokens
149 tree
.to_xml
.write_to
(stdout
)
150 else if not no_print
then
151 (new PrintTreeVisitor).enter_visit
(tree
)