ANTLR 4-输入不匹配

时间:2019-07-02 13:15:49

标签: antlr antlr4

我正在为我的一个项目尝试使用ANTLR开发小型DSL。 因此,我为词法分析器写了定义...

lexer grammar SpamkillerLexer;

MAILBOX: 'Mailbox';
PASSWORD: 'Password';
HOST: 'Host';
USER: 'User';
FOLDER: 'Folder';
PORT: 'Port';
ACTIONS: 'Actions';

WHEN: 'When';
SUBJECT: 'Subject';
BODY: 'Body';
EQUALS: 'Equals';
CONTAINS: 'Contains';
THEN: 'Then';
DELETE: 'Delete';
REDIRECT: 'Redirect';
TO: 'to';

BR_OP: '{';
BR_CL: '}';
EQ: '=';

STRING: '"' ( '\\"' | . )*? '"';
LITERAL: [a-zA-Z_0-9]+;

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

...和解析器...

parser grammar SpamkillerParser;
mailboxes: mailbox+;
mailbox: MAILBOX LITERAL BR_OP settings BR_CL;

settings: setting+;
setting: (key EQ STRING | ACTIONS EQ actions);
key: MAILBOX | PASSWORD | HOST | USER | FOLDER | PORT;

actions: BR_OP action* BR_CL;
action: WHEN condition THEN job;
condition: (SUBJECT | BODY) (EQUALS | CONTAINS) STRING;
job: (DELETE | (REDIRECT TO STRING));

我的测试文件如下:

Mailbox Foobar {
    Port = "123"
    Host = "foohost"
    User = "foouser"
    Password = "foopass"
    Folder = "Inbox"
    Actions = {
        When Subject Equals "fooooo" Then Delete
        When Body Contains "fooooo" Then Redirect to "foo@bar.baz"
    }
}

当我在ANTLR IntelliJ插件中测试mailboxes时,它可以正常工作,并且得到相应的AST:

AST

但是当我尝试以编程方式解析我的测试文件时,出现错误...

line 1:8 mismatched input 'Foobar' expecting LITERAL

我试图重新排列我的词法分析器规则,但是我的尝试都没有帮助我摆脱错误。有人知道如何解决吗?

我用于解析文件的代码如下:

String input = FileUtils.readFileToString(new File("test.txt"), Charsets.UTF_8);
CodePointCharStream inputStream = CharStreams.fromString(input);
SpamkillerLexer lexer = new SpamkillerLexer(inputStream);
CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
SpamkillerParser parser = new SpamkillerParser(commonTokenStream);
SpamkillerParser.MailboxesContext mailboxes = parser.mailboxes();

1 个答案:

答案 0 :(得分:2)

您没有在解析器中指定必须使用的令牌词汇表。因此,ANTLR可以为解析器创建隐式令牌(实际上是简单的终端),而不是在词法分析器中使用令牌。

要解决此问题,请提供tokenVocab选项:

parser grammar SpamkillerParser;

options {
   tokenVocab=SpamkillerLexer;
}

mailboxes: mailbox+;
mailbox: MAILBOX LITERAL BR_OP settings BR_CL;

settings: setting+;
setting: (key EQ STRING | ACTIONS EQ actions);
key: MAILBOX | PASSWORD | HOST | USER | FOLDER | PORT;

actions: BR_OP action* BR_CL;
action: WHEN condition THEN job;
condition: (SUBJECT | BODY) (EQUALS | CONTAINS) STRING;
job: (DELETE | (REDIRECT TO STRING));