4

我正在使用 Rhino 来评估 js 表达式,方法是将所有可能的变量值放在范围内并评估匿名函数。然而,表达式相当简单,我只想把表达式中使用的值,以提高性能。

代码示例:

    Context cx = Context.enter();

    Scriptable scope = cx.initStandardObjects(null);

    // Build javascript anonymous function
    String script = "(function () {" ;

    for (String key : values.keySet()) {
        ScriptableObject.putProperty(scope, key, values.get(key));
    }
    script += "return " + expression + ";})();";

    Object result = cx.evaluateString(scope, script, "<cmd>", 1, null);

我想从作为变量名的表达式中获取所有标记。

例如,如果表达式是

(V1ND < 0 ? Math.abs(V1ND) : 0)

它会回来V1ND的。

4

1 回答 1

6

Rhino 1.7 R3引入了一个可用于查找名称的AST 包:

import java.util.*;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.*;

public class VarFinder {
  public static void main(String[] args) throws IOException {
    final Set<String> names = new HashSet<String>();
    class Visitor implements NodeVisitor {
      @Override public boolean visit(AstNode node) {
        if (node instanceof Name) {
          names.add(node.getString());
        }
        return true;
      }
    }
    String script = "(V1ND < 0 ? Math.abs(V1ND) : 0)";
    AstNode node = new Parser().parse(script, "<cmd>", 1);
    node.visit(new Visitor());
    System.out.println(names);
  }
}

输出:

[V1ND, abs, Math]

但是,我不确定这对效率有多大帮助,除非表达式可以缓存。您将解析代码两次,如果您需要abs在进一步检查时从函数中消除变量的歧义,Math则需要。

于 2013-01-22T14:31:13.450 回答