[antlr-interest] Rule optimization - inline

Alex Lujan alex at apption.com
Tue Feb 22 07:21:46 PST 2011


Hi All,

I'm having a problem with what I believe is an optimization within the ANTLR
code generation.

Consider the following sample grammar:

grammar CharSelectionTest;

@header {
import org.apache.commons.lang.StringUtils;
}

type             :    (type_sell | type_itsp) data ;

type_sell         :    character['s'];

type_itsp         :    character['i'];

data            :    BYTE_VALUE*;

character[char character_to_match]
                :    {input.LT(1).getText().charAt(0) ==
character_to_match}? BYTE_VALUE;

BYTE_VALUE        :    '\u0000'..'\uFFFE';


When ANTLR generates the Parser java code, the type() method seems to be
replacing the call to the character rule with an inline equivalent:

public final void type() throws RecognitionException {
        try {
            {
            int alt1=2;
            int LA1_0 = input.LA(1);

            if ( (LA1_0==BYTE_VALUE) ) {
                int LA1_1 = input.LA(2);

                // Compile error: character_to_match is not defined!
                if ( ((input.LT(1).getText().charAt(0) ==
character_to_match)) ) {
                    alt1=1;
                }
                else if ( ((input.LT(1).getText().charAt(0) ==
character_to_match)) ) {
                    alt1=2;
                }
                else {
                    NoViableAltException nvae =
                        new NoViableAltException("", 1, 1, input);

                    throw nvae;
                }
            }
            ...
    }

Note that the variable character_to_match is not defined, since it's
supposed to be a parameter of the character rule.

Is there anything wrong with the rule definition in this simple grammar?

Is this a known issue?

Any workarounds / solutions to this problem?

Thanks very much for your help.

-- 
Alejandro Lujan


More information about the antlr-interest mailing list