With antlr, I’m trying to make a TreeWalker for a tree like this:
input: int x = 3
output AST: ^(VARDEF int x 3)
My parser works just fine and also generates an AST like shown above, but whenever I want to resolve anything from the AST, like with $variableType.text, there is allways a NullReferenceException in the generated C# 2.0 TreeWalker.
My TreeWalker:
tree grammar SGLTreeWalker;
options {
tokenVocab = SGL;
language = 'CSharp2';
}
[...]
compilationUnit
: (statement)+
;
statement
: variableDefinitionList
;
variableDefinitionList
: ^(VARDEF variableType variableName expression) { Console.WriteLine($variableType.text); }
;
[...]
The problematic part, generated by the rule “variableDefinitionList” looks like this:
Match(input, Token.UP, null);
Console.WriteLine(((variableType1 != null) ? input.TokenStream.ToString(
input.TreeAdaptor.GetTokenStartIndex(variableType1.Start),
input.TreeAdaptor.GetTokenStopIndex(variableType1.Start)) : null));
It turns out that input.TokenStream is null so it throws the NullReferenceException. I read that this can happen if the used TreeNodeStream isn’t buffered, but I used the CommonTreeNodeStream so it should be buffered I think. Here is the code I used to commit the AST:
[...]
SGLParser parser = new SGLParser(tStream);
CommonTree t = (CommonTree) parser.compilationUnit().Tree;
Console.WriteLine("; " + t.ToStringTree());
CommonTreeNodeStream treeStream = new CommonTreeNodeStream(t);
SGLTreeWalker tw = new SGLTreeWalker(treeStream);
tw.compilationUnit();
Any idea on why input.TokenStream resolves to null when I just want to get the $variableType.text attribute?
That is because inside a tree grammar, the production rules return a
TreeRuleReturnScopewhich doesn’t have atextattribute (orGetText()method).If you want to grab the text of a
variableTyperule, you’ll need to explicitly return astring.A demo:
SGL.g
SGLTreeWalker.g
And the class:
produces the following output: