if then else 条件评估

编程入门 行业动态 更新时间:2024-10-27 07:24:08
本文介绍了if then else 条件评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一种语言,它基本上是为了将列映射到数组中的新结构.该语言旨在让产品经理无需了解大量编程细节即可定义映射.我确信这里还有很多需要改进的地方,但这就是我所拥有的.

I have a language which basically is meant to map columns to a new structure in an array. The language is meant for product managers to define mappings without having to know a lot of programming details. I'm sure there is a lot more to improve here but this is what I have.

语言有效,主要是.我的问题是条件语句.

The language works, mostly. The problem I have is with conditional statements.

我的解析器有以下规则:

My parser has the following rule:

conditionalexpr :  IF^ LPAREN! (statement) RPAREN! THEN! LCURLY! statement RCURLY! (ELSE! LCURLY! statement RCURLY!)?;

它可以生成一棵有三个孩子的树.

Which works to generate a tree with three children.

我的问题是在条件不允许的情况下避免评估语句.

My problem is to avoid evaluating the statements if the condition doesn't allow it.

我太天真了:

conditionalexpr returns[Object o]: 
  ^(IF a=statement b=statement (c=statement)?)
  {
    $o = (Boolean)$a.o ? $b.o : $c.o != null ? $c.o : "";
  }
  ;

显然这行不通.

我一直在研究句法谓词,但我无法使它们正常工作.

I have been playing around with syntactic predicates but I can't make those work properly.

语句当前返回一个对象.该语言主要处理字符串,但我也需要支持布尔值和数字(整数和小数).

statement returns an object currently. Mostly the language deals in Strings but I need to support booleans and numbers (integer and decimal) as well.

如果我添加类似 {$a.o}?=> 的内容,我会在生成的代码中得到一个 $a.

If I add anything like {$a.o}?=> I get a $a in the generated code.

我查看了 antlr-interest 列表,但这个问题在那里并没有得到很好的回答,很可能是因为这对他们来说似乎很明显.

I have looked on the antlr-interest list but this question is not really answered well there, most likely because it seems obvious to them.

我愿意发布完整的语法,但为了保持简短而将其省略.

I am willing to post the complete grammar but have left it out to keep this short.

推荐答案

如果您不想评估某些子树,则需要让树规则返回节点而不是实际值.您可以扩展 CommonTree 并提供自定义 TreeAdaptor 来帮助构建您自己的节点,但就个人而言,我发现创建自定义节点类(或多个类)并使用他们代替.一个演示澄清:

If you don't want certain sub-trees to be evaluated, you'll need to let the tree rules return nodes instead of actual values. You can either extend CommonTree and provide a custom TreeAdaptor to help build your own nodes, but personally, I find it easiest to create a custom node class (or classes) and use them instead. A demo to clarify:

grammar T;

options {
  output=AST;
}

tokens {
  ASSIGNMENT;
}

parse
  :  statement+ EOF -> statement+
  ;

statement
  :  ifStatement
  |  assignment
  ;

ifStatement
  :  IF a=expression THEN b=expression (ELSE c=expression)? -> ^(IF $a $b $c?)
  ;

assignment
  :  ID '=' expression -> ^(ASSIGNMENT ID expression)
  ;

expression
  :  orExpression
  ;

orExpression
  :  andExpression (OR^ andExpression)*
  ;

andExpression
  :  equalityExpression (AND^ equalityExpression)*
  ;

equalityExpression
  :  relationalExpression (('==' | '!=')^ relationalExpression)*
  ;

relationalExpression
  :  atom (('<=' | '<' | '>=' | '>')^ atom)*
  ;

atom
  :  BOOLEAN
  |  NUMBER
  |  ID
  |  '(' expression ')' -> expression
  ;

IF      : 'if';
THEN    : 'then';
ELSE    : 'else';
OR      : 'or';
AND     : 'and';
BOOLEAN : 'true' | 'false';
ID      : ('a'..'z' | 'A'..'Z')+;
NUMBER  : '0'..'9'+ ('.' '0'..'9'+)?;
SPACE   : (' ' | '\t' | '\r' | '\n') {skip();};

Main.java

我创建了一个 Node 接口,它有一个 eval(): Object 方法,并且还创建了一个抽象类 BinaryNode 它实现Node 并且总是有 2 个孩子.正如您在这些 Java 类之后的树语法中所见,所有规则现在都返回一个 Node.

Main.java

I've created a Node interface that has a eval(): Object method, and also created an abstract class BinaryNode which implements Node and will have always 2 children. As you can see in the tree grammar that follows after these Java classes, all rule now return a Node.

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;

public class Main {
  public static void main(String[] args) throws Exception {
    String source = "a = 3   b = 4   if b > a then b==b else c==c";
    TLexer lexer = new TLexer(new ANTLRStringStream(source));
    TParser parser = new TParser(new CommonTokenStream(lexer));
    TWalker walker = new TWalker(new CommonTreeNodeStream(parser.parse().getTree()));
    Node root = walker.walk();
    System.out.println(root.eval());
  }
}

interface Node {
  Object eval();
}

abstract class BinaryNode implements Node {

  protected Node left;
  protected Node right;

  public BinaryNode(Node l, Node r) {
    left = l;
    right = r;
  }
}

class AtomNode implements Node {

  private Object value;

  public AtomNode(Object v) {
    value = v;
  }

  @Override
  public Object eval() {
    return value;
  }
}

class OrNode extends BinaryNode {

  public OrNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Boolean)super.left.eval() || (Boolean)super.right.eval();
  }
}

class AndNode extends BinaryNode {

  public AndNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Boolean)super.left.eval() && (Boolean)super.right.eval();
  }
}

class LTNode extends BinaryNode {

  public LTNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Double)super.left.eval() < (Double)super.right.eval();
  }
}

class LTEqNode extends BinaryNode {

  public LTEqNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Double)super.left.eval() <= (Double)super.right.eval();
  }
}

class GTNode extends BinaryNode {

  public GTNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Double)super.left.eval() > (Double)super.right.eval();
  }
}

class GTEqNode extends BinaryNode {

  public GTEqNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return (Double)super.left.eval() >= (Double)super.right.eval();
  }
}

class EqNode extends BinaryNode {

  public EqNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return super.left.eval().equals(super.right.eval());
  }
}

class NEqNode extends BinaryNode {

  public NEqNode(Node left, Node right) { super(left, right); }

  @Override
  public Object eval() {
    return !super.left.eval().equals(super.right.eval());
  }
}

class VarNode implements Node {

  private java.util.Map<String, Object> memory;
  private String var;

  VarNode(java.util.Map<String, Object> m, String v) {
    memory = m;
    var = v;
  }

  @Override
  public Object eval() {
    Object value = memory.get(var);
    if(value == null) {
      throw new RuntimeException("Unknown variable: " + var);
    }
    return value;
  }
}

class IfNode implements Node {

  private Node test;
  private Node ifTrue;
  private Node ifFalse;

  public IfNode(Node a, Node b, Node c) {
    test = a;
    ifTrue = b;
    ifFalse = c;
  }

  @Override
  public Object eval() {
    return (Boolean)test.eval() ? ifTrue.eval() : ifFalse.eval();
  }
}

TWalker.g

tree grammar TWalker;

options {
  tokenVocab=T;
  ASTLabelType=CommonTree;
}

@members {
  private java.util.Map<String, Object> memory = new java.util.HashMap<String, Object>();
}

walk returns [Node n]
  :  (statement {$n = $statement.n;})+
  ;

statement returns [Node n]
  :  ifStatement {$n = $ifStatement.n;}
  |  assignment  {$n = null;}
  ;

assignment
  :  ^(ASSIGNMENT ID expression) {memory.put($ID.text, $expression.n.eval());}
  ;

ifStatement returns [Node n]
  :  ^(IF a=expression b=expression c=expression?) {$n = new IfNode($a.n, $b.n, $c.n);}
  ;

expression returns [Node n]
  :  ^(OR a=expression b=expression)   {$n = new OrNode($a.n, $b.n);}
  |  ^(AND a=expression b=expression)  {$n = new AndNode($a.n, $b.n);}
  |  ^('==' a=expression b=expression) {$n = new EqNode($a.n, $b.n);}
  |  ^('!=' a=expression b=expression) {$n = new NEqNode($a.n, $b.n);}
  |  ^('<=' a=expression b=expression) {$n = new LTEqNode($a.n, $b.n);}
  |  ^('<' a=expression b=expression)  {$n = new LTNode($a.n, $b.n);}
  |  ^('>=' a=expression b=expression) {$n = new GTEqNode($a.n, $b.n);}
  |  ^('>' a=expression b=expression)  {$n = new GTNode($a.n, $b.n);}
  |  BOOLEAN                           {$n = new AtomNode(Boolean.valueOf($BOOLEAN.text));}
  |  NUMBER                            {$n = new AtomNode(Double.valueOf($NUMBER.text));}
  |  ID                                {$n = new VarNode(memory, $ID.text);}
  ;

<小时>

如果你现在运行主类,并评估:


If you now run the main class, and evaluate:

a = 3   
b = 4   
if b > a then 
  b==b 
else 
  c==c

true 正在打印到控制台:

bart@hades:~/Programming/ANTLR/Demos/T$ java -cp antlr-3.3.jar org.antlr.Tool T.g
bart@hades:~/Programming/ANTLR/Demos/T$ java -cp antlr-3.3.jar org.antlr.Tool TWalker.g
bart@hades:~/Programming/ANTLR/Demos/T$ javac -cp antlr-3.3.jar *.java
bart@hades:~/Programming/ANTLR/Demos/T$ java -cp .:antlr-3.3.jar Main
true

但是如果你检查 b ,导致 else 被执行,你会看到以下内容:

But if you check if b < a, causing the else to be executed, you'll see the following:

Exception in thread "main" java.lang.RuntimeException: Unknown variable: c
        at VarNode.eval(Main.java:140)
        at EqNode.eval(Main.java:112)
        at IfNode.eval(Main.java:160)
        at Main.main(Main.java:11)

对于更复杂的语言结构(范围、函数等)的实现,请参见 我的博客.

For implementations of more complicated language constructs (scopes, functions, etc.), see my blog.

祝你好运!

这篇关于if then else 条件评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-20 08:26:59,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!