AST operators
Code gen templates for operators; assume root=null, kids=List<Token>
grammar fragment |
code |
---|---|
A |
kids.add($A); _localctx.tree = adaptor.create(root, kids); // A |
A B |
kids.add($A); kids.add($B); _localctx.tree = adaptor.create(root, kids); // ^(nil A B) |
A^ B |
root = root==null ? $A : adaptor.becomeRoot(root, $A, kids); kids.add($ID); _localctx.tree = adaptor.create(root, kids); // ^(A B) |
A B^ |
kids.add($A); root = root==null ? $B : adaptor.becomeRoot(root, $B, kids); _localctx.tree = adaptor.create(root, kids); // ^(B A) |
A B^ C |
kids.add($A); root = root==null ? $B : adaptor.becomeRoot(root, $B, kids); kids.add($C); _localctx.tree = adaptor.create(root, kids); // ^(B A C) |
A B^ C^ D |
kids.add($A); root = root==null ? $B : adaptor.becomeRoot(root, $B, kids); root = root==null ? $C : adaptor.becomeRoot(root, $C, kids); kids.add($D); _localctx.tree = adaptor.create(root, kids); // ^(C ^(B A) D) |
Rewrites
Code gen templates for rewrite rules; assume root=adaptor.nil(), kids is List<Tree>. assume we can't distinguish statically single vs multi-valued elements from left of -> for now.
grammar fragment |
code |
---|---|
A -> A |
A_it = A_list.iterator(); kids.add(adaptor.create(A_it.next())); _localctx.tree = adaptor.create(root, kids); // A |
A -> A A |
A_it = A_list.iterator(); kids.add(adaptor.create(A_it.next())); kids.add(adaptor.create(A_it.next())); // iterator keeps returning A nodes _localctx.tree = adaptor.create(root, kids); // ^(nil A A) |
A B -> ^(A B) |
A_it = A_list.iterator(); B_it = B_list.iterator(); root = adaptor.create(A_it.next()); kids.add(adaptor.create(B_it.next())); _localctx.tree = adaptor.create(root, kids); // ^(nil A A) |
A+ -> A* |
A_it = A_list.iterator(); while (A_it.hasNext()) { kids.add(adaptor.create(A_it.next())); } _localctx.tree = adaptor.create(root, kids); // ^(nil A A ... A) |
A+ -> ^(B A*) |
A_it = A_list.iterator(); B_it = B_list.iterator(); root = adaptor.create(B_it.next()); while (A_it.hasNext()) { kids.add(adaptor.create(A_it.next())); } _localctx.tree = adaptor.create(root, kids); // ^(B A A ... A) |
A+ -> ^(B A)* |
A_it = A_list.iterator(); B_it = B_list.iterator(); root_1 = null; while (A_it.hasNext()) { root_1 = adaptor.create(B_it.next()); kids.add(adaptor.create(A_it.next())); kids.add( adaptor.create(root_1, kids) ); // ^(B A) } _localctx.tree = adaptor.create(root, kids); // ^(nil ^(B A) ^(B A) ...) |