package org.antlr.runtime.tree;
import org.antlr.runtime.Token;
import org.antlr.runtime.CommonToken;
public class TreePatternParser {
protected TreePatternLexer tokenizer;
protected int ttype;
protected TreeWizard wizard;
protected TreeAdaptor adaptor;
public TreePatternParser(TreePatternLexer tokenizer, TreeWizard wizard, TreeAdaptor adaptor) {
this.tokenizer = tokenizer;
this.wizard = wizard;
this.adaptor = adaptor;
ttype = tokenizer.nextToken();
}
public Object pattern() {
if ( ttype==TreePatternLexer.BEGIN ) {
return parseTree();
}
else if ( ttype==TreePatternLexer.ID ) {
Object node = parseNode();
if ( ttype==TreePatternLexer.EOF ) {
return node;
}
return null;
}
return null;
}
public Object parseTree() {
if ( ttype != TreePatternLexer.BEGIN ) {
throw new RuntimeException("no BEGIN");
}
ttype = tokenizer.nextToken();
Object root = parseNode();
if ( root==null ) {
return null;
}
while ( ttype==TreePatternLexer.BEGIN ||
ttype==TreePatternLexer.ID ||
ttype==TreePatternLexer.PERCENT ||
ttype==TreePatternLexer.DOT )
{
if ( ttype==TreePatternLexer.BEGIN ) {
Object subtree = parseTree();
adaptor.addChild(root, subtree);
}
else {
Object child = parseNode();
if ( child==null ) {
return null;
}
adaptor.addChild(root, child);
}
}
if ( ttype != TreePatternLexer.END ) {
throw new RuntimeException("no END");
}
ttype = tokenizer.nextToken();
return root;
}
public Object parseNode() {
String label = null;
if ( ttype == TreePatternLexer.PERCENT ) {
ttype = tokenizer.nextToken();
if ( ttype != TreePatternLexer.ID ) {
return null;
}
label = tokenizer.sval.toString();
ttype = tokenizer.nextToken();
if ( ttype != TreePatternLexer.COLON ) {
return null;
}
ttype = tokenizer.nextToken();
}
if ( ttype == TreePatternLexer.DOT ) {
ttype = tokenizer.nextToken();
Token wildcardPayload = new CommonToken(0, ".");
TreeWizard.TreePattern node =
new TreeWizard.WildcardTreePattern(wildcardPayload);
if ( label!=null ) {
node.label = label;
}
return node;
}
if ( ttype != TreePatternLexer.ID ) {
return null;
}
String tokenName = tokenizer.sval.toString();
ttype = tokenizer.nextToken();
if ( tokenName.equals("nil") ) {
return adaptor.nil();
}
String text = tokenName;
String arg = null;
if ( ttype == TreePatternLexer.ARG ) {
arg = tokenizer.sval.toString();
text = arg;
ttype = tokenizer.nextToken();
}
int treeNodeType = wizard.getTokenType(tokenName);
if ( treeNodeType==Token.INVALID_TOKEN_TYPE ) {
return null;
}
Object node;
node = adaptor.create(treeNodeType, text);
if ( label!=null && node.getClass()==TreeWizard.TreePattern.class ) {
((TreeWizard.TreePattern)node).label = label;
}
if ( arg!=null && node.getClass()==TreeWizard.TreePattern.class ) {
((TreeWizard.TreePattern)node).hasTextArg = true;
}
return node;
}
}