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