首页 > 解决方案 > 想要解析相同的结构

问题描述

我想让 ANTLR4 解析这个:

FSM
name type String
state type State
Relation
name type String

我正在使用这个语法:

grammar Generator;

classToGenerate:
    name=Name NL
    (attributes NL)+
    classToGenerate| EOF;
attributes: attribute=Name WS 'type' WS type=Name;

Name:  ('A'..'Z' | 'a'..'z')+ ;

WS: (' ' | '\t')+;
NL:  '\r'? '\n';

我想成功阅读,我不知道为什么,但每次我运行我的程序时,我都会收到这个错误:

line 6:18 no viable alternative at input '<EOF>'

有什么修复吗?

标签: antlr4

解决方案


尾随EOF为你搞砸了。尝试创建一个与令牌匹配的单独规则EOF,前面有一个或多个classToGenerateparse我的示例中的规则):

grammar Generator;

parse
 : classToGenerate+ EOF
 ;

classToGenerate
 : name=Name NL (attributes NL)+
 ;

attributes
 : attribute=Name WS 'type' WS type=Name
 ;

Name:  ('A'..'Z' | 'a'..'z')+ ;
WS: (' ' | '\t')+;
NL:  '\r'? '\n';

你真的需要保留空格和换行符吗?您可以让词法分析器丢弃它们,这使您的语法更容易阅读:

grammar Generator;

parse
 : classToGenerate+ EOF
 ;

classToGenerate
 : name=Name attributes+
 ;

attributes
 : attribute=Name 'type' type=Name
 ;

Name   : [a-zA-Z]+;
Spaces : [ \t\r\n] -> skip;

推荐阅读