04 Oct 2012, 00:09
Generic-user-small

Kurt Leistentritt (2 posts)

Hi Terence,

when I label the top alternatives in the JSON grammar

json
    :   object                      # ObjectTree                
    |   array                       # ArrayTree
    ;

I get the following error:

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

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;
			parent.removeLastChild();
			if ( parent!=null )	parent.addChild(localctx);
		}
		_ctx = localctx;
		_ctx.altNum = altNum;
	}

Best regards, Kurt

03 Oct 2012, 23:47
Australia-3_pragsmall

Terence Parr (37 posts)

Thanks. noted. what was your input?

04 Oct 2012, 07:49
Generic-user-small

Kurt Leistentritt (2 posts)

I did add following lines

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

to JSON2XML.java from the book source code.

After removing the labels this code worked as expected:

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

I really enjoy reading your book :-)

08 Oct 2012, 18:28
Australia-3_pragsmall

Terence Parr (37 posts)

ok, fixed for 4.0b3. thanks!

  You must be logged in to comment