java逻辑表达式解析框架_java – 寻找项目建议.解析逻辑表达式

如果您被允许使用像ANTLR这样的解析器生成器工具,那么您可以从这里开始.简单逻辑语言的语法可能如下所示:

grammar Logic;

parse

: expression EOF

;

expression

: implication

;

implication

: or ('->' or)*

;

or

: and ('||' and)*

;

and

: not ('&&' not)*

;

not

: '~' atom

| atom

;

atom

: ID

| '(' expression ')'

;

ID : ('a'..'z' | 'A'..'Z')+;

Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};

但是,如果您要解析输入,如(P || Q || R)&& ((P – > R) – > Q)使用从上面的语法生成的解析器,解析树将包含括号(解析表达式后您不感兴趣的东西)并且运算符不是根如果你有兴趣评估表达式,那么每个子树都不会让你的生活变得更容易.

你需要告诉ANTLR省略AST中的某些令牌(这可以通过在令牌/规则之后放置一个!来完成)并使某些令牌/规则成为他们(子)树的根(这可以通过放置来完成) a ^之后).最后,您需要在语法的选项部分中指出您希望创建适当的AST而不是简单的解析树.

所以,上面的语法看起来像这样:

// save it in a file called Logic.g

grammar Logic;

options {

output=AST;

}

// parser/production rules start with a lower case letter

parse

: expression EOF! // omit the EOF token

;

expression

: implication

;

implication

: or ('->'^ or)* // make `->` the root

;

or

: and ('||'^ and)* // make `||` the root

;

and

: not ('&&'^ not)* // make `&&` the root

;

not

: '~'^ atom // make `~` the root

| atom

;

atom

: ID

| '('! expression ')'! // omit both `(` and `)`

;

// lexer/terminal rules start with an upper case letter

ID : ('a'..'z' | 'A'..'Z')+;

Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};

您可以使用以下类测试解析器:

import org.antlr.runtime.*;

import org.antlr.runtime.tree.*;

import org.antlr.stringtemplate.*;

public class Main {

public static void main(String[] args) throws Exception {

// the expression

String src = "(P || Q || R) && ((P -> R) -> Q)";

// create a lexer & parser

LogicLexer lexer = new LogicLexer(new ANTLRStringStream(src));

LogicParser parser = new LogicParser(new CommonTokenStream(lexer));

// invoke the entry point of the parser (the parse() method) and get the AST

CommonTree tree = (CommonTree)parser.parse().getTree();

// print the DOT representation of the AST

DOTTreeGenerator gen = new DOTTreeGenerator();

StringTemplate st = gen.toDOT(tree);

System.out.println(st);

}

}

现在运行Main类,执行:

* nix中/ MacOS的

java -cp antlr-3.3.jar org.antlr.Tool Logic.g

javac -cp antlr-3.3.jar *.java

java -cp .:antlr-3.3.jar Main

视窗

java -cp antlr-3.3.jar org.antlr.Tool Logic.g

javac -cp antlr-3.3.jar *.java

java -cp .;antlr-3.3.jar Main

这将打印以下AST的DOT source:

现在您需要做的就是评估此AST! 🙂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值