使用ANTLR 4配置解析器

时间:2014-06-02 20:43:56

标签: antlr4

我在使用ANTLR 4创建配置解析器时遇到一些问题。配置文件具有以下语法:

section1{
key=value;
key=value;
}

section2{
key=value;
}

我还写了一个词法分析器/解析器:

grammar Config;

fragment IdentifierText: [A-Za-z]+[A-Za-z0-9]*;
fragment IdentifierNumber:[0-9]+'.'?[0-9]*;
fragment IdentifierBool: 'false'|'true';
Section: IdentifierText;
Key: [A-Za-z]+[A-Za-z0-9]*;
Value: IdentifierText|IdentifierNumber|IdentifierBool;
Whitespace: [\t\b \f\r\n]+ -> skip;

start: configs;

configs: config+;

config:  section  statement ;

statement: '{' assignment+ '}';

section: Section;

assignment:  Key '=' Value ';';

但如果我用它作为样本:

Test{
debug=false;
}

我收到以下错误:

line 2:0 mismatched input 'debug' expecting Key
line 2:5 mismatched input '=' expecting '{'
line 2:11 mismatched input ';' expecting '{'

任何想法如何解决问题? 提前谢谢

1 个答案:

答案 0 :(得分:0)

您的Section词法分析器规则与Key无法区分。当找到匹配这些规则之一的输入时,通过选择语法中出现的第一个来解决歧义;在这种情况下Section。换句话说,词法分析器是不可能的,因为你已经定义它来返回一个Key令牌。

您应该通过对部分和键使用单个Identifier规则来解决此问题,并使用解析器规则来区分它们。

section : Identifier;
key : Identifier;
Identifier : IdentifierText;