[antlr-interest] How to remove the rules ambiguity here?

Johannes Luber jaluber at gmx.de
Wed Oct 31 11:17:21 PDT 2007


Johannes Luber wrote:
> Or can I safely use a flag to tell the parser "Here
> aren't global attributes allowed!"?

I've tried to use the following approach:

compilation_unit
@init{
    globalAttributesAllowed = true;
}
    :    extern_alias_directive* using_directive*
        ({globalAttributesAllowed}? global_attribute_section
          {if ((input.LT(1).Type != OPEN_BRACE) ||
           (input.LT(2).Type != IDENTIFIER) ||
           (input.LT(1).Type == OPEN_BRACE &&
              input.LT(2).Type == IDENTIFIER &&
                 (input.LT(2).Text != "assembly" ||
                  input.LT(2).Text != "module")))
                  { globalAttributesAllowed = false; }}
        )*
        namespace_member_declaration* EOF
	;

The following code is generated for the "({globalAttributesAllowed}?
global_attribute_section {if (yes) {globalAttributesAllowed = false;}
)*" snippet:

//
D:\\Studium\\Diplomarbeit_Experimental\\CSharpML\\CSharp3ParserTest.g:148:45:
({...}? global_attribute_section )*
do
{
    int alt7 = 2;
    alt7 = dfa7.Predict(input);
    switch (alt7)
    {
    case 1 :
         // CSharp3ParserTest.g:148:46: {...}? global_attribute_section
         {
             if ( !(globalAttributesAllowed) )
             {
                 if ( backtracking > 0 ) {failed = true; return retval;}
                 throw new FailedPredicateException(input,
                      "compilation_unit", "globalAttributesAllowed");
             }
     PushFollow(FOLLOW_global_attribute_section_in_compilation_unit197);
             global_attribute_section14 = global_attribute_section();
             followingStackPointer_--;
             if (failed) return retval;
             if ( backtracking==0 ) adaptor.AddChild(root_0,
                 global_attribute_section14.Tree);
             if ( backtracking == 0 )
             {
                 if ((input.LT(1).Type != OPEN_BRACE) ||
                    (input.LT(2).Type != IDENTIFIER) ||
                    (input.LT(1).Type == OPEN_BRACE &&
                        input.LT(2).Type == IDENTIFIER &&
                           (input.LT(2).Text != "assembly" ||
                           input.LT(2).Text != "module")))
                           { globalAttributesAllowed = false; }
             }
		
        }
        break;

    default:
        goto loop7;
    }
} while (true);

I'm a bit worried about

if ( !(globalAttributesAllowed) )
{
    if ( backtracking > 0 ) {failed = true; return retval;}
    throw new FailedPredicateException(input,
         "compilation_unit", "globalAttributesAllowed");
}

Will this correctly work?

Johannes




More information about the antlr-interest mailing list