What is the easiest way to get the text that matches an entire parser rule?

Terence Parr

There are three ways:

  1. 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";}
    	;
    
  2. 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"
    	;
    
  3. 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"
    	;
    
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact