Skip to content

NoViableAltException was thrown at a incorrect position #4885

@LKY-Lockee

Description

@LKY-Lockee

Part of my .g4 file:

modifiers
    : modifier+
    ;

modifier
    : Public
    | Internal
    | Protected
    | Private
    | Static
    | Unsafe
    | Extern
    ;

classDefinition
    : attributes? modifiers? Class typeDefName classBody
    ;
	
classBody
    : '{' classMemberDeclarations? '}'
    | ';'
    ;
	
classMemberDeclarations
    : classMemberDeclaration+
    ;
	
classMemberDeclaration
    : attributes? modifiers? classMember
    ;
    
classMember
    : property
    | method
    ;

method
    : typeName methodName '(' parameterList? ')' (block | ';')
    ;

Test input:

public stati void Main()
{
}

NoViableAltException shows offending token is Main, it should be stati (only in runtime, correct in Rider plugin)
Inline rules can solve the problem:

classDefinition
    : attributes? modifiers? Class typeDefName 
        ( '{' ( property
              | method
              )* 
          '}'
        | ';'
        )
    ;

method
    : attributes? modifiers? typeName methodName '(' parameterList? ')' (block | ';')
    ;

But this results in bad error recovery strategy, all members after a wrongly typed member will broken.
My parser structure refers to this.

Target language is C#

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions