Mai*_*kel 2 c# antlr4 antlr4cs
我定义了一个 ANTLR4 语法,其中词法分析器和解析器位于两个不同的文件中。它是一种类似于 XML 的语法。在我的解析器中,我也想定义一个可以重复使用自身用于计算目的的表达式(如“(1+1)*2”)。
parser grammar TestExpressionParser;
options { tokenVocab=TestExpressionLexer; }
compileUnit : calculator ;
calculator : '<' 'calculator' '>' tiers? rules?'</' 'calculator' '>' ;
// tiers
tiers : '<' 'tiers' '>' tier* '</' 'tiers' '>' ;
tier : '<' 'tier' attrReference '>' '</' 'tier' '>' ;
// rules
rules : '<' 'rules' '>' (rule) '</' 'rules' '>' ;
rule : '<' 'rule' '>' (calculation|reference|description)* '</' 'rule' '>' ;
calculation : '<' 'calculation' '>' expression '</' 'calculation' '>' ;
description : '<' 'description' '>' TEXT '</' 'description' '>' ;
reference : '<' 'reference' '>' TEXT '</' 'reference' '>' ;
attrReference : 'reference' '="' TEXT '"' ;
expression : '(' expression ')' #parentExpression
| expression PLUS expression #plusExpression
| NUMBER #numberExpression
| REF_PARAMETER #parameterExpression
;
lexer grammar TestExpressionLexer;
fragment LOWERCASE : [a-z] ;
fragment UPPERCASE : [A-Z] ;
fragment DIGIT : [0-9] ;
PARENTHESIS_LEFT : '(' ;
PARENTHESIS_RIGHT : ')' ;
ATTR_OPEN : '="' ;
ATTR_CLOSE : '"' ;
TAG_BEGIN_OPEN : '<' ;
TAG_BEGIN_CLOSE : '/>' ;
TAG_END_OPEN : '</' ;
TAG_CLOSE : '>' ;
// common
TAG_ATTR_REFERENCE : 'reference' ;
TAG_CALCULATOR : 'calculator' ;
// tiers
TAG_TIERS : 'tiers' ;
TAG_TIER : 'tier' ;
// rules
TAG_RULES : 'rules' ;
TAG_RULE : 'rule' ;
TAG_GROUP : 'group' ;
TAG_ATTR_RULE_CALCULATION : 'calculation' ;
TAG_ATTR_RULE_DESCRIPTION : 'description' ;
// calculation operations
ASTERISK : '*' ;
SLASH : '/' ;
PLUS : '+' ;
MINUS : '-' ;
TIER : '=>' ;
REF_PARAMETER : '{' TEXT '}' ;
REF_TIER : '[' TEXT ']' ;
// others
TEXT : (UPPERCASE|LOWERCASE) (UPPERCASE|LOWERCASE|DIGIT|'_')* ;
NUMBER : FLOAT | DIGIT+ ;
FLOAT : DIGIT+ (','|'.') DIGIT* | (','|'.') DIGIT+ ;
// whitespaces
WHITESPACE : (' '|'\n'|'\t'|'\r')+ -> skip ;
Run Code Online (Sandbox Code Playgroud)
我添加的最后一件事是expression PLUS expression,从那时起,我在 C# 生成的类中收到以下错误TestExpressionParser:
line 866: 'TestExpressionParser.Sempred(TestExpressionParser.RuleContext, int, int)': no suitable method found to override
line 868: Cannot convert type '(..).Testing.TestExpressionParser.RuleContext' to '(..).Testing.TestExpressionParser.ExpressionContext'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会发生这种情况。我将 ANTLR 语言支持扩展与 Sam Haswell 的 Antlr4 NuGet 包结合使用。我也尝试过使用默认生成工具(这是 ANTLR 的最后一个版本,但没有 VS 扩展),但它给出了相同的错误。
有人知道我做错了什么吗?
在花了几个小时寻找解决方案后,我在搜索时发布了这个问题..并且我刚刚发现了问题。由于规则“rule”的命名而发生错误。
不要使用“rule”作为规则名称,因为它会变成 RuleContext,即预定义的上下文对象。