要解析相同的结构

时间:2019-06-21 02:33:34

标签: antlr4

我想让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>'

任何解决方法?

1 个答案:

答案 0 :(得分:0)

结尾的EOF为您搞砸了。尝试创建与EOF令牌匹配的单独规则,并在其前面添加一个或多个classToGenerate(在我的示例中为parse规则):

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;