parser: locate errors with locations in ANode
[nit.git] / src / parser / 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 package test_parser
19
20 import parser
21
22 class PrintTreeVisitor
23 super Visitor
24 var _rank: Int
25 redef fun visit(n: nullable ANode)
26 do
27 if n == null then return
28 printn(" " * _rank, n.to_s, " ... ", n.location, "\n")
29 _rank = _rank + 1
30 n.visit_all(self)
31 _rank = _rank - 1
32 end
33
34 init
35 do
36 _rank = 0
37 end
38 end
39
40 var no_print = false
41 var only_lexer = false
42 var need_help = false
43
44 while not args.is_empty and args.first.first == '-' do
45 if args.first == "-n" then
46 no_print = true
47 else if args.first == "-l" then
48 only_lexer = true
49 else if args.first == "-p" then
50 only_lexer = false
51 else if args.first == "-h" or args.first == "-?" then
52 need_help = true
53 else
54 stderr.write("Unknown option {args.first}.\n")
55 exit(0)
56 end
57 args.shift
58 end
59
60 if args.is_empty or need_help then
61 print("usage:")
62 print(" test_parser [options]... <filename.nit>...")
63 print("options:")
64 print(" -n do not print anything")
65 print(" -l only lexer")
66 print(" -p lexer and parser (default)")
67 print(" -h print this help")
68 else
69 for a in args do
70 var f = new IFStream.open(a)
71 var lexer = new Lexer(f, a)
72 if only_lexer then
73 var token = lexer.next
74 while not token isa EOF do
75 if not no_print then
76 print("Read token at {token.location} text='{token.text}'")
77 end
78 token = lexer.next
79 end
80 f.close
81 else
82 var parser = new Parser(lexer)
83 var tree = parser.parse
84 f.close
85
86 if not no_print then
87 (new PrintTreeVisitor).enter_visit(tree)
88 end
89 end
90 end
91 end