small medium large xlarge

04 Oct 2012, 00:09
Kurt Leistentritt (2 posts)

Hi Terence,

when I label the top alternatives in the JSON grammar

    :   object                      # ObjectTree                
    |   array                       # ArrayTree

I get the following error:

 Exception in thread "main" java.lang.NullPointerException
	at org.antlr.v4.runtime.Parser.enterOuterAlt(
	at antlr.tests.listeners.JSONParser.json(
	at antlr.tests.listeners.JSON2XML.main(

Looking at the source code, there is no null check for “parent.removeLastChild();” in method enterOuterAlt of class org.antlr.v4.runtime.Parser:

	public void enterOuterAlt(ParserRuleContext<Token> localctx, int altNum) {
		// if we have new localctx, make sure we replace existing ctx
		// that is previous child of parse tree
		if ( _buildParseTrees && _ctx != localctx ) {
			ParserRuleContext<?> parent = (ParserRuleContext<?>)_ctx.parent;
			if ( parent!=null )	parent.addChild(localctx);
		_ctx = localctx;
		_ctx.altNum = altNum;

Best regards, Kurt

03 Oct 2012, 23:47
Terence Parr (41 posts)

Thanks. noted. what was your input?

04 Oct 2012, 07:49
Kurt Leistentritt (2 posts)

I did add following lines

    public void enterArrayTree(ArrayTreeContext ctx)
      setXML(ctx, "<elements>");
    public void exitArrayTree(ArrayTreeContext ctx)
      setXML(ctx, "</elements>");

to from the book source code.

After removing the labels this code worked as expected:

    public void exitArrayOfValues(JSONParser.ArrayOfValuesContext ctx)
      StringBuilder buf = new StringBuilder();
      for (JSONParser.ValueContext vctx : ctx.value())
        buf.append("  <element>"); // conjure up element for valid XML
        buf.append("  </element>\n");
      setXML(ctx, buf.toString());

I really enjoy reading your book :-)

08 Oct 2012, 18:28
Terence Parr (41 posts)

ok, fixed for 4.0b3. thanks!

  You must be logged in to comment