これはおよそトークン曖昧です。この質問は、これらの最後の数週間に何度か聞かれました。特にのを明確にして、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
run
がCLASS_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.text
:
methodReturnValue
とmethodName
はctx
からリスナーで使用可能な、ルールをコンテキスト。
ありがとうございました!特に '-tokens'の場合。 –