What is the easiest way to get the text that matches an entire parser rule?
Created May 4, 2012
Terence Parr There are three ways:
- The hard way: modify each parser rule so that it returns a String representing the text matched for that rule.
decl returns [String t} : ty=type id:ID ";" {$t = ty+id.getText();} ; type returns [String t} : "int" {$t="int";} | "float" {$t="float";} ;
- Build trees and then convert the tree matched for the rule to a string using either a tree walker or a simple depth-first search.
class P extends Parser; options { buildAST = AST; } decl : type id:ID ";" { String text = myTreeWalker(#decl); System.out.println("text for decl: "+text); } ; type : "int" | "float" ;
- Override Parser.match(). You would set a flag in the parser rule you wanted to track and then make match() sensitive to it.
class P extends Parser; { private boolean track=false; private StringBuffer rbuf = new StringBuffer(); public void match(int t) throws MismatchedTokenException, TokenStreamException { // must be before super.match(t), because that consumes the current token if ( track ) { rbuf.append(LT(1).getText()); } super.match(t); } } ... decl : {track=true;} type id:ID ";" {track=false;} ; type : "int" | "float" ;