2017-10-30 1 views
1

ANTL文法:シンプルなJavaファイルを解析するためのANTLR文法で何が問題になっていますか?

grammar Java; 

// Parser 

compilationUnit: classDeclaration; 

classDeclaration : 'class' CLASS_NAME classBlock 
    ; 

classBlock: OPEN_BLOCK method* CLOSE_BLOCK 
    ; 

method: methodReturnValue methodName methodArgs methodBlock 
    ; 

methodReturnValue: CLASS_NAME 
    ; 

methodName: METHOD_NAME 
    ; 

methodArgs: OPEN_PAREN CLOSE_PAREN 
    ; 

methodBlock: OPEN_BLOCK CLOSE_BLOCK 
    ; 

// Lexer 

CLASS_NAME: ALPHA; 
METHOD_NAME: ALPHA; 

WS: [ \t\n] -> skip; 

OPEN_BLOCK: '{'; 
CLOSE_BLOCK: '}'; 

OPEN_PAREN: '('; 
CLOSE_PAREN: ')'; 

fragment ALPHA: [a-zA-Z][a-zA-Z0-9]*; 

疑似Javaファイル:

class Test { 

    void run() { } 

} 

ほとんどのものは、それが誤ってmethodArgsと関連付けMETHOD_NAMEを除き一致。

line 3:6 mismatched input 'run' expecting METHOD_NAME 

methodName

答えて

1

これはおよそトークン曖昧です。この質問は、これらの最後の数週間に何度か聞かれました。特にを明確にして、this answerにリンクしてください。

はできるだけ早くあなたがmismatchedエラーを持っているとして、それはあなたがそれが実際に何をレクサーは何だろうと思い、何の間に矛盾を見つけるのに役立ちます、トークンを表示するgrun-tokensを追加します。あなたの文法で:ALPHAにマッチした

CLASS_NAME: ALPHA; 
METHOD_NAME: ALPHA; 

すべての入力が曖昧で、かつ曖昧ANTLRの場合、最初のルールを選択します。

$ grun Question compilationUnit -tokens -diagnostics t.text 
[@0,0:4='class',<'class'>,1:0] 
[@1,6:9='Test',<CLASS_NAME>,1:6] 
[@2,11:11='{',<'{'>,1:11] 
[@3,18:21='void',<CLASS_NAME>,3:4] 
[@4,23:25='run',<CLASS_NAME>,3:9] 
[@5,26:26='(',<'('>,3:12] 
[@6,27:27=')',<')'>,3:13] 
[@7,29:29='{',<'{'>,3:15] 
[@8,31:31='}',<'}'>,3:17] 
[@9,34:34='}',<'}'>,5:0] 
[@10,36:35='<EOF>',<EOF>,6:0] 
Question last update 0841 
line 3:9 mismatched input 'run' expecting METHOD_NAME 

runCLASS_NAMEとして解釈されているからです。

私はそうのような文法記述します。

grammar Question; 

// Parser 

compilationUnit 
@init {System.out.println("Question last update 0919");} 
    : classDeclaration; 

classDeclaration : 'class' ID classBlock 
    ; 

classBlock: OPEN_BLOCK method* CLOSE_BLOCK 
    ; 

method: methodReturnValue=ID methodName=ID methodArgs methodBlock 
     {System.out.println("Method found : " + $methodName.text + 
          " which returns a " + $methodReturnValue.text);} 
    ; 

methodArgs: OPEN_PAREN CLOSE_PAREN 
    ; 

methodBlock: OPEN_BLOCK CLOSE_BLOCK 
    ; 

// Lexer 

ID : ALPHA (ALPHA | DIGIT | '_')* ; 

WS: [ \t\n] -> skip; 

OPEN_BLOCK: '{'; 
CLOSE_BLOCK: '}'; 

OPEN_PAREN: '('; 
CLOSE_PAREN: ')'; 

fragment ALPHA : [a-zA-Z] ; 
fragment DIGIT : [0-9] ; 

実行:

$ grun Question compilationUnit -tokens -diagnostics t.text 
[@0,0:4='class',<'class'>,1:0] 
[@1,6:9='Test',<ID>,1:6] 
[@2,11:11='{',<'{'>,1:11] 
[@3,18:21='void',<ID>,3:4] 
[@4,23:25='run',<ID>,3:9] 
[@5,26:26='(',<'('>,3:12] 
[@6,27:27=')',<')'>,3:13] 
[@7,29:29='{',<'{'>,3:15] 
[@8,31:31='}',<'}'>,3:17] 
[@9,34:34='}',<'}'>,5:0] 
[@10,36:35='<EOF>',<EOF>,6:0] 
Question last update 0919 
Method found : run which returns a void 

$ grun Question compilationUnit -gui t.textenter image description here

methodReturnValuemethodNamectxからリスナーで使用可能な、ルールをコンテキスト。

+0

ありがとうございました!特に '-tokens'の場合。 –

関連する問題