为什么 Lexer.cs 不能识别词法模式?

Why doesn't the Lexer.cs recognize a lexical mode?

我在本网站和其他地方看到过很多词法模式的实施示例,例如 ANTLR4 权威指南。在用词法模式编写我自己的词法分析器语法之前,我只是想尝试一个例子。所以我从 ANTLR Mega Tutorial:

复制了示例
lexer grammar MarkupLexer;
OPEN                : '[' -> pushMode(BBCODE) ;
TEXT                : ~('[')+ ;
// Parsing content inside tags
mode BBCODE;
CLOSE               : ']' -> popMode ;
SLASH               : '/' ;
EQUALS              : '=' ;
STRING              : '"' .*? '"' ;
ID                  : LETTERS+ ;
WS                  : [ \t\r\n] -> skip ;
fragment LETTERS    : [a-zA-Z] ;

并将其导入到一个非常简单的语法分析器中:

grammar Example1;
import MarkupLexer;

any                 : .*;

我只想看看它是否会成功构建。但是,我遇到了同样的错误:The name 'BBCODE' does not exist in the current context 在此自动生成的方法中发生错误:

private void OPEN_action(RuleContext _localctz, int actionIndex) {
    switch (actionIndex) {
    case 0: PushMode(BBCODE); break;
    }
}

我注意到自动生成的 Lexer 中的 modeNames 数组只包含 "DEFAULT_MODE".

我在这里错过了什么?为什么不能构建?

问题是您使用了 "import",而您应该使用 "options { tokenVocab = MarkupLexer; }"。你的语法应该是:

MarkupParser.g4:

parser grammar MarkupParser;

options {
    tokenVocab = MarkupLexer ;
}

any                 : .*;

MarkupLexer.g4:

lexer grammar MarkupLexer;
OPEN                : '[' -> pushMode(BBCODE) ;
TEXT                : ~('[')+ ;
// Parsing content inside tags
mode BBCODE;
CLOSE               : ']' -> popMode ;
SLASH               : '/' ;
EQUALS              : '=' ;
STRING              : '"' .*? '"' ;
ID                  : LETTERS+ ;
WS                  : [ \t\r\n] -> skip ;
fragment LETTERS    : [a-zA-Z] ;