質問

i have some problems creating a config parser with ANTLR 4. The config files have the following syntax:

section1{
key=value;
key=value;
}

section2{
key=value;
}

I have also written a lexer/parser:

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 ';';

But if I use this as a sample:

Test{
debug=false;
}

I get the following errors:

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

Any ideas how to solve the problem? thanks in advance

役に立ちましたか?

解決

Your Section lexer rule is indistinguishable from Key. When an input matching one of these rules is found, the ambiguity is resolved by choosing the first one that appears in your grammar; in this case Section. In other words, it is impossible for the lexer as you have defined it to return a Key token.

You should resolve this by using a single Identifier rule for both sections and keys, and using parser rules to distinguish between them.

section : Identifier;
key : Identifier;
Identifier : IdentifierText;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top