[英]Nested Boolean Expression Parser using ANTLR
I'm trying to parse a Nested Boolean Expression and get the individual conditions within the expression separately.<\/i>我正在尝试解析嵌套布尔表达式并分别获取表达式中的各个条件。<\/b> For eg, if the input string is:<\/i>例如,如果输入字符串是:<\/b><\/p>
(A = a OR B = b OR C = c AND ((D = d AND E = e) OR (F = f AND G = g)))<\/i> (A = a OR B = b OR C = c AND ((D = d AND E = e) OR (F = f AND G = g)))<\/b><\/p>
I would like to get the conditions with the correct order.<\/i>我想以正确的顺序获得条件。<\/b> ie,<\/i> IE,<\/b><\/p>
D =d AND E = e OR F = f AND G = g AND A = a OR B = b OR C = c<\/i> D =d AND E = e OR F = f AND G = g AND A = a OR B = b OR C = c<\/b><\/p>
I'm using ANTLR 4 to parse the input text and here's my grammar:<\/i>我正在使用 ANTLR 4 解析输入文本,这是我的语法:<\/b><\/p>
grammar SimpleBoolean;
rule_set : nestedCondition* EOF;
AND : 'AND' ;
OR : 'OR' ;
NOT : 'NOT';
TRUE : 'TRUE' ;
FALSE : 'FALSE' ;
GT : '>' ;
GE : '>=' ;
LT : '<' ;
LE : '<=' ;
EQ : '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
DECIMAL : '-'?[0-9]+('.'[0-9]+)? ;
IDENTIFIER : [a-zA-Z_][a-zA-Z_0-9]* ;
WS : [ \r\t\u000C\n]+ -> skip;
nestedCondition : LPAREN condition+ RPAREN (binary nestedCondition)*;
condition: predicate (binary predicate)*
| predicate (binary component)*;
component: predicate | multiAttrComp;
multiAttrComp : LPAREN predicate (and predicate)+ RPAREN;
predicate : IDENTIFIER comparator IDENTIFIER;
comparator : GT | GE | LT | LE | EQ ;
binary: AND | OR ;
unary: NOT;
and: AND;
I'd just wrap all the expressions into a single expression<\/code> rule.<\/i>
我只是将所有表达式包装到一个
expression<\/code>规则中。<\/b> Be sure to define the
comparator<\/code> expressions alternative before<\/em> your
binary<\/code> expression alternative to make sure
comparator<\/code> operators bind more tightly than
OR<\/code> and
AND<\/code> :<\/i>请务必在
binary<\/code>表达式替代之前<\/em>定义
comparator<\/code>表达式替代,以确保比较运算符
comparator<\/code>
OR<\/code>和
AND<\/code>绑定更紧密:<\/b><\/p>
grammar SimpleBoolean;
parse
: expression EOF
;
expression
: LPAREN expression RPAREN #parenExpression
| NOT expression #notExpression
| left=expression op=comparator right=expression #comparatorExpression
| left=expression op=binary right=expression #binaryExpression
| bool #boolExpression
| IDENTIFIER #identifierExpression
| DECIMAL #decimalExpression
;
comparator
: GT | GE | LT | LE | EQ
;
binary
: AND | OR
;
bool
: TRUE | FALSE
;
AND : 'AND' ;
OR : 'OR' ;
NOT : 'NOT';
TRUE : 'TRUE' ;
FALSE : 'FALSE' ;
GT : '>' ;
GE : '>=' ;
LT : '<' ;
LE : '<=' ;
EQ : '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
DECIMAL : '-'? [0-9]+ ( '.' [0-9]+ )? ;
IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]* ;
WS : [ \r\t\u000C\n]+ -> skip;
The C# Equivalent of @Bart Kiers: @Bart Kiers 的 C# 等价物:
EvalVistor.cs
: EvalVistor.cs
:
public class EvalVisitor : NOABaseVisitor<object> {
private readonly Dictionary<string, object> variables = new();
public EvalVisitor(Dictionary<string, object> variables)
{
this.variables = variables;
}
public override object VisitParse([NotNull] NOAParser.ParseContext context)
{
return base.Visit(context.expression());
}
public override object VisitDecimalExpression([NotNull] NOAParser.DecimalExpressionContext context)
{
return Double.Parse(context.DECIMAL().GetText());
}
public override object VisitIdentifierExpression([NotNull] NOAParser.IdentifierExpressionContext context)
{
return variables[context.IDENTIFIER().GetText()];
}
public override object VisitNotExpression([NotNull] NOAParser.NotExpressionContext context)
{
return !((bool)this.Visit(context.expression()));
}
public override object VisitParenExpression([NotNull] NOAParser.ParenExpressionContext context)
{
return base.Visit(context.expression());
}
public override object VisitComparatorExpression([NotNull] NOAParser.ComparatorExpressionContext context)
{
if (context.op.EQ() != null)
{
return this.Visit(context.left).Equals(this.Visit(context.right));
}
else if (context.op.LE() != null)
{
return AsDouble(context.left) <= AsDouble(context.right);
}
else if (context.op.GE() != null)
{
return AsDouble(context.left) >= AsDouble(context.right);
}
else if (context.op.LT() != null)
{
return AsDouble(context.left) < AsDouble(context.right);
}
else if (context.op.GT() != null)
{
return AsDouble(context.left) > AsDouble(context.right);
}
throw new ApplicationException("not implemented: comparator operator " + context.op.GetText());
}
public override object VisitBinaryExpression([NotNull] NOAParser.BinaryExpressionContext context)
{
if (context.op.AND() != null)
{
return AsBool(context.left) && AsBool(context.right);
}
else if (context.op.OR() != null)
{
return AsBool(context.left) || AsBool(context.right);
}
throw new ApplicationException("not implemented: binary operator " + context.op.GetText());
}
public override object VisitBoolExpression([NotNull] NOAParser.BoolExpressionContext context)
{
return bool.Parse(context.GetText());
}
private bool AsBool(NOAParser.ExpressionContext context)
{
return (bool)Visit(context);
}
private double AsDouble(NOAParser.ExpressionContext context)
{
return (double)Visit(context);
}
}
Program.cs
: Program.cs
:
Dictionary<string, object> variables = new()
{
{"a", true },
{"A", true },
{"B", false },
{"b", false },
{"C", 42.0 },
{"c", 42.0 },
{"D", -999.0 },
{"d", -1999.0 },
{"E", 42.001 },
{"e", 142.001 },
{"F", 42.001 },
{"f", 42.001 },
{"G", -1.0 },
{ "g", -1.0 },
};
string[] expressions =
{
"1 > 2",
"1 >= 1.0",
"TRUE = FALSE",
"FALSE = FALSE",
"A OR B",
"B",
"A = B",
"c = C",
"E > D",
"B OR (c = B OR (A = A AND c = C AND E > D))",
"(A = a OR B = b OR C = c AND ((D = d AND E = e) OR (F = f AND G = g)))"
};
foreach (var expression in expressions)
{
NOALexer lexer = new (new AntlrInputStream(expression));
NOAParser parser = new (new CommonTokenStream(lexer));
Object result = new EvalVisitor(variables).Visit(parser.parse());
Console.WriteLine($"{expression} - {result}\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.