stdlib/strings: Removed usage of Strings as SequenceRead by using chars.
[nit.git] / src / test_parser.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Jean Privat <jean@pryen.org>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Program used to test the NIT parser
18 module test_parser
19
20 import parser
21
22 class PrintTreeVisitor
23 super Visitor
24 var _rank: Int
25 redef fun visit(n)
26 do
27 if n isa Token then
28 printn(" " * _rank, n.class_name, " \"", n.text.escape_to_c, "\" ", n.location, "\n")
29 else
30 printn(" " * _rank, n.class_name, " ", n.location, "\n")
31 end
32 _rank = _rank + 1
33 n.visit_all(self)
34 _rank = _rank - 1
35 end
36
37 init
38 do
39 _rank = 0
40 end
41 end
42
43 var no_print = false
44 var only_lexer = false
45 var need_help = false
46 var no_file = false
47
48 while not args.is_empty and args.first.chars.first == '-' do
49 if args.first == "-n" then
50 no_print = true
51 else if args.first == "-l" then
52 only_lexer = true
53 else if args.first == "-p" then
54 only_lexer = false
55 else if args.first == "-e" then
56 no_file = true
57 else if args.first == "-h" or args.first == "-?" then
58 need_help = true
59 else
60 stderr.write("Unknown option {args.first}.\n")
61 exit(0)
62 end
63 args.shift
64 end
65
66 if args.is_empty or need_help then
67 print("usage:")
68 print(" test_parser [options]... <filename.nit>...")
69 print("options:")
70 print(" -n do not print anything")
71 print(" -l only lexer")
72 print(" -p lexer and parser (default)")
73 print(" -e instead on files, each argument is a content to parse")
74 print(" -h print this help")
75 else
76 for a in args do
77 var source
78 if no_file then
79 source = new SourceFile.from_string("", a)
80 else
81 var f = new IFStream.open(a)
82 source = new SourceFile(a, f)
83 f.close
84 end
85 var lexer = new Lexer(source)
86 if only_lexer then
87 var token = lexer.next
88 while not token isa EOF do
89 if not no_print then
90 print("Read token at {token.location} text='{token.text}'")
91 end
92 token = lexer.next
93 end
94 else
95 var parser = new Parser(lexer)
96 var tree = parser.parse
97
98 var error = tree.n_eof
99 if error isa AError then
100 print("Error at {error.location}:\n\t{error.message}")
101 return
102 end
103
104 if not no_print then
105 (new PrintTreeVisitor).enter_visit(tree)
106 end
107 end
108 end
109 end