[antlr-interest] NullPointerException in rewrite rule

Mark Volkmann r.mark.volkmann at gmail.com
Wed Dec 19 06:33:57 PST 2007


On Dec 19, 2007 5:41 AM, Stefan Eder <stefan.eder at ebuconnect.de> wrote:
> Hi,
>
> I get a NullPointerException in a rewrite rule with Antlr 3.01.
> My intention is to concat several tokens to one new token during AST construction.
> Any ideas what I am doing wrong?
>
> Grammar:
>         grammar Test;
>         options {output=AST;}
>         tokens {FLOAT;}
>         floatSequence
>                 :
>                 value=(NumberLiteral ('.' NumberLiteral))

I don't know if this is related to the problem, but why don't you make
a lexer rule that creates a single token for your floating point
numbers? For example,

REAL: INTEGER+ ('.' INTEGER+)?;
INTEGER: '0'..'9';

If you had those then your rule above could be written like this.

floatSequence: REAL -> ^(FLOAT REAL);

>                 -> ^(FLOAT[$value])

Why do you have the square brackets? I don't think you mean to pass
$value as a parameter to the FLOAT rule.

>                 ;
>         NumberLiteral   : ('0'..'9') + ;
>
> Main method:
> public static void main(String[] args)
> throws RecognitionException {
>         CharStream charStream = new ANTLRStringStream("0.815");
>         TestLexer testLexer = new TestLexer(charStream);
>         TokenStream tokenStream = new CommonTokenStream(testLexer);
>         TestParser parser = new TestParser(tokenStream);
>         parser.floatSequence();
> }
>
> Exception stack:
> Exception in thread "main" java.lang.NullPointerException
>         at org.antlr.runtime.CommonToken.<init>(CommonToken.java:72)
>         at org.antlr.runtime.tree.CommonTreeAdaptor.createToken(CommonTreeAdaptor.java:60)
>         at org.antlr.runtime.tree.BaseTreeAdaptor.create(BaseTreeAdaptor.java:102)
>         at TestParser.floatSequence(TestParser.java:105)
>         at Main.main(Main.java:16)
>
>
> Reviewing the generated code:
>     //...
>     Token value=null;
>     //...
>     root_1 =
>       (Object)adaptor.becomeRoot(adaptor.create(FLOAT, value), root_1);
> The variable value has not been initialized between declaration and use.
> Calling adaptor.create(FLOAT, null) causes the exception.
>
> If I remove the rewrite rule, the exception disappears and the input is parsed ok.

-- 
R. Mark Volkmann
Object Computing, Inc.


More information about the antlr-interest mailing list