[antlr-interest] Beginners Problem: Null Reference Exception

Russell Lear rrlear at gmail.com
Fri Jul 20 15:20:37 PDT 2012

Not sure if this is the right forum - let me know where I should go if it

I just bought the ANTLR reference book and I've been working through the
examples.  I'm working in C# with .NET 4.5 and so some things don't work
exactly the same as what's in the book, but for  the most part it has been
a lot of fun.  However, I do have one issue.

I sometimes get a null reference exception in the parser when I call the
parser with the top-level target at a line that looks like:

root_0 = (CommonTree)adaptor.Nil();

I can fix this fairly easily in my code by setting

parser.TreeAdaptor = new CommonTreeAdaptor();

(TreeAdaptor is a property backed by the field adaptor)

But this seems wrong in that my code probably shouldn't know about, much
less be setting, internal parser variables.

The grammar I'm using comes from tour/trees/Expr.g and the C# code is a
straightforward translation of the Java that's in the book (I've played
with it somewhat so it might not be identical):

            ANTLRStringStream input = new ANTLRStringStream(target);
            ExprLexer lexer = new ExprLexer(input);
            var tokens = new CommonTokenStream(lexer);
            var parser = new ExprParser(tokens);
      //    parser.TreeAdaptor = new CommonTreeAdaptor();   // odd
(required?) addition
            var r = parser.prog(); // Exception occurs here

            CommonTree t = r.Tree;
            var nodes = new CommonTreeNodeStream(t);
            Eval walker = new Eval(nodes);

            foreach (var k in walker.memory.Keys) {
                Console.WriteLine("    {0} ==> {1}", k,
walker.memory[k]);            }

            Console.Write("Done ");

Is this just the way it is?  Or am I missing something?  Thanks for any
help and direction!


More information about the antlr-interest mailing list