简体   繁体   English

从javascript表达式获取变量(Rhino)

[英]Get variables from javascript expression (Rhino)

I'm using Rhino to evaluate js expressions, by putting all the possible variable values in the scope and evaluating an anonymous function. 我正在使用Rhino通过将所有可能的变量值放入范围并评估一个匿名函数来评估js表达式。 However the expressions are fairly simple and I would like to put only the values used in the expression, for performance. 但是表达式非常简单,我只想将表达式中使用的值用于性能。

Code sample: 代码示例:

    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);

I want to get all the tokens from the expressions that are variable names. 我想从变量名的表达式中获取所有标记。

For instance, if the expression is 例如,如果表达式为

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

it will return V1ND . 它将返回V1ND

Rhino 1.7 R3 introduced an AST package which can be used to find names: 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);
  }
}

Output: 输出:

[V1ND, abs, Math]

However, I'm not sure this will help much with efficiency unless the expressions are amenable to caching. 但是,我不确定这是否会大大提高效率,除非表达式适合缓存。 You would be parsing the code twice and if you need to disambiguate a variable abs from the function on Math further inspection will be required. 您将解析两次代码,如果需要从Math函数上Math变量abs ,则需要进一步检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM