Why do I get a null pointer exception when I try to reference text attributes in my tree parser?

Most likely you have not told the tree parser where it can find the token stream from which to obtain text. Recall that the default tree node implementation has a token pointer as a payload. This token pointer points into the original token stream, which might need to point to the character stream from which the tokens were derived. In order to access the text for a tree, you must tell the tree node stream where it can find the token stream. References such as $ruleref.text in the tree parser make no sense unless it knows where to find the stream of token objects. Example:

CommonTokenStream tokens = new CommonTokenStream(lexer); 
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t); 
// AST nodes have payloads that point into token stream 

The generated code for $ruleref.text looks like:


input.getTokenStream() is probably the source of the null pointer if you've not called setTokenStream.