Last change
on this file since 1 was
1,
checked in by lnalod, 15 years ago
|
Initial import of YAO sources
|
File size:
1.9 KB
|
Line | |
---|
1 | import sys |
---|
2 | import antlr |
---|
3 | |
---|
4 | |
---|
5 | class Visitor(antlr.ASTVisitor): |
---|
6 | def __init__(self,*args): |
---|
7 | super(Visitor,self).__init__(*args) |
---|
8 | self.level = 0 |
---|
9 | if not args: |
---|
10 | self.cout = sys.stdout |
---|
11 | return |
---|
12 | if isinstance(args[0],file): |
---|
13 | self.cout = args[0] |
---|
14 | return |
---|
15 | assert 0 |
---|
16 | |
---|
17 | def tabs(self): |
---|
18 | print " " * self.level |
---|
19 | |
---|
20 | def printf(self,fmt,*args): |
---|
21 | if not args: |
---|
22 | sys.stdout.write(fmt) |
---|
23 | return |
---|
24 | argv = tuple(args) |
---|
25 | self.cout.write(fmt % argv) |
---|
26 | |
---|
27 | def flush(self): |
---|
28 | self.cout.flush() |
---|
29 | |
---|
30 | def visit1(self,node): |
---|
31 | if not node: |
---|
32 | self.printf(" nil ") |
---|
33 | return |
---|
34 | |
---|
35 | c = node.getType() |
---|
36 | t = node.getText() |
---|
37 | k = node.getFirstChild() |
---|
38 | s = node.getNextSibling() |
---|
39 | |
---|
40 | self.printf("( <%s> ",c) |
---|
41 | if t: |
---|
42 | self.printf(" %s ",t) |
---|
43 | self.visit1(k); |
---|
44 | self.visit1(s); |
---|
45 | self.printf(")") |
---|
46 | |
---|
47 | def visit(self,node): |
---|
48 | self.visit1(node); |
---|
49 | self.printf("\n") |
---|
50 | |
---|
51 | |
---|
52 | def main(): |
---|
53 | import treewalk_l |
---|
54 | import treewalk_p |
---|
55 | import treewalk_w |
---|
56 | |
---|
57 | L = treewalk_l.Lexer() |
---|
58 | P = treewalk_p.Parser(L) |
---|
59 | P.setFilename(L.getFilename()) |
---|
60 | |
---|
61 | ### Parse the input expression |
---|
62 | try: |
---|
63 | P.block() |
---|
64 | except antlr.ANTLRException, ex: |
---|
65 | print "*** error(s) while parsing." |
---|
66 | print ">>> exit(1)" |
---|
67 | import sys |
---|
68 | sys.exit(1) |
---|
69 | |
---|
70 | |
---|
71 | ast = P.getAST() |
---|
72 | |
---|
73 | if not ast: |
---|
74 | print "stop - no AST generated." |
---|
75 | import sys |
---|
76 | sys.exit(1) |
---|
77 | |
---|
78 | ###show tree |
---|
79 | print "Tree: " + ast.toStringTree() |
---|
80 | print "List: " + ast.toStringList() |
---|
81 | print "Node: " + ast.toString() |
---|
82 | print "visit>>" |
---|
83 | visitor = Visitor() |
---|
84 | visitor.visit(ast); |
---|
85 | print "visit<<" |
---|
86 | |
---|
87 | W = treewalk_w.Walker(); |
---|
88 | ### Traverse the tree created by the parser |
---|
89 | W.block(ast); |
---|
90 | ast = W.getAST(); |
---|
91 | if ast: print "List: " + ast.toStringList() |
---|
92 | |
---|
93 | if __name__ == "__main__": |
---|
94 | main() |
---|
Note: See
TracBrowser
for help on using the repository browser.