即使预期输入,Antlr4也会打印“外部输入”错误

时间:2014-10-05 19:03:09

标签: antlr4

我尝试使用SMILES规范解析OpenSMILES个字符串。

语法:

grammar SMILES;

atom: bracket_atom | aliphatic_organic | aromatic_organic | '*';

aliphatic_organic: 'B' | 'C' | 'N' | 'O' | 'S' | 'P' | 'F' | 'Cl' | 'Br' | 'I';
aromatic_organic: 'b' | 'c' | 'n' | 'o' | 's' | 'p';

bracket_atom: '[' isotope? symbol chiral? hcount? charge? atom_class? ']';
symbol: element_symbols | aromatic_symbols | '*';
isotope: NUMBER;
element_symbols: UPPER_CASE_CHAR LOWER_CASE_CHAR?;
aromatic_symbols: 'c' | 'n' | 'o' | 'p' | 's' | 'se' | 'as';

chiral: '@'
        |  '@@'
        |  '@TH1' | '@TH2'
        |  '@AL1' | '@AL2'
        |  '@SP1' | '@SP2' | '@SP3'
        |  '@TB1' | '@TB2' | '@TB3' | DOT DOT DOT | '@TB29' | '@TB30'
        |  '@OH1' | '@OH2' | '@OH3' | DOT DOT DOT | '@OH29' | '@OH30';

hcount: 'H' |  'H' DIGIT;

charge: '-'
        |  '-' DIGIT
        |  '+'
        |  '+' DIGIT
        |  '--'
        |  '++';

atom_class:':' NUMBER;

bond: '-' | '=' | '#' | '$' | ':' | '/' | '\\';
ringbond: (bond? DIGIT |  bond? '%' DIGIT DIGIT);
branched_atom: atom ringbond* branch*?;
branch: '(' chain ')' |  '(' bond chain ')' |  '(' dot chain ')';
chain: branched_atom
    |  chain branched_atom
    |  chain bond branched_atom
    |  chain dot branched_atom;
dot: '.';

DOT: .;
DIGIT: [0-9];
NUMBER: DIGIT+;
UPPER_CASE_CHAR: [A-Z];
LOWER_CASE_CHAR: [a-z];

ONE_TO_NINE: [1-9];

smiles: chain;

WS: [ \t\n\r]+ -> skip ;

尝试使用AntlrWorks2的TestRig解析以下内容时:

CCc(c1)ccc2[n+]1ccc3c2Nc4c3cccc4

打印以下错误(为简洁起见缩短):

line 1:5 extraneous input '1' expecting {'*', '[', 'N', 'O', 'I', 'S', '%', ')',..., DIGIT}
...
line 1:31 extraneous input '4' expecting {<EOF>, '*', '[', 'N', 'O',..., DIGIT}

对于字符串中遇到的每个数字都会发生这种情况。

编辑1

按照@Lucas Trzesniewski的建议修复DOT规则后,extraneous input错误消失了。但是,在测试不同的SMILES字符串时,现在出现了新的错误。

例如,测试:

[Cu+2].[O-]S(=O)(=O)[O-]

产生错误:

line 1:1 no viable alternative at input 'C'

编辑2

来自编辑1 的问题归因于我的element_symbols规则。使用文字符号字符串似乎已经解决了它。

element_symbols: 'H' | 'He' | 'Li' | 'Be' | 'B' | 'C' | 'N' | 'O' | 'F' | 'Ne' | //...and so on

1 个答案:

答案 0 :(得分:3)

你的词法分析器规则是错误的。

第一个错误:

DOT: .;

这是一个全能的。你的真正含义是:

DOT: '.';

第二个错误:您对以下规则感到困惑:

DIGIT: [0-9];
NUMBER: DIGIT+;
ONE_TO_NINE: [1-9];

ONE_TO_NINE永远不会匹配任何内容,因为它已包含在DIGIT中,DIGIT首先出现。由于ONE_TO_NINE规则从未使用过,因此您只需将其删除即可。

然后,解析器规则中的DIGIT DIGIT之类的内容将不匹配,如果您期望一个2位数字,那么除非您将数字与数字分开,否则您将获得NUMBER代币空白(我不知道你的意思是什么,所以也许这不是错误)。