0

The code tool.process(grammar, false); produces a null pointer exception.

See my code below:

package antlr;

import java.nio.file.Files;
import java.nio.file.Paths;
import org.antlr.v4.Tool;
import org.antlr.v4.tool.Grammar;
import org.antlr.v4.tool.ast.GrammarRootAST;
import org.junit.Test;

// License : Apache License Version 2.0  https://www.apache.org/licenses/LICENSE-2.0
/**
 *
 * @author Peter <peter@quantr.hk>
 */
public class TestDynamicParser {

    @Test
    public void testDynamicParser() throws Exception {
        Tool tool = new Tool();
        String content = new String(Files.readAllBytes(Paths.get(getClass().getResource("Hello.g4").toURI())));
        GrammarRootAST ast = tool.parseGrammarFromString(content);
        Grammar grammar = tool.createGrammar(ast);
        tool.process(grammar, false);
    }
}

Grammar:

grammar Hello;
r   : 'hello' ID;
ID  : [a-z]+ ;
WS  : [ \t\r\n]+ -> skip ;

Error:

java.lang.NullPointerException
    at antlr.TestDynamicParser.testDynamicParser(TestDynamicParser.java:23)

How can I prevent this error from occurring?

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Peter
  • 13
  • 5
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – mustaccio Sep 10 '18 at 18:51
  • Is `content` null? Try it with `String content = "grammar Hello;\nr : 'hello' ID;\nID : [a-z]+ ;\nWS : [ \t\r\n]+ -> skip ;";` – Bart Kiers Sep 10 '18 at 20:50
  • no, content is not null – Peter Sep 12 '18 at 17:29
  • Which line is 23? By my count that is this line: ``` tool.process(grammar, false); ``` I'm not sure how tool could be null. – Terence Parr Sep 12 '18 at 19:29
  • line 23 is tool.process(grammar, false); , i have fixed it myself, please see https://github.com/antlr/antlr4/issues/2362 . I am not sure why the code was working but just not now. Any hints? Anyway I have upgrade my netbenas-antlr plugin to correct code. – Peter Sep 13 '18 at 13:13

0 Answers0