从javascript表达式获取变量(Rhino) [英] Get variables from javascript expression (Rhino)

查看:143
本文介绍了从javascript表达式获取变量(Rhino)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Rhino to evaluate js expressions, by putting all the possible variable values in the scope and evaluating an anonymous function. However the expressions are fairly simple and I would like to put only the values used in the expression, for performance.

代码示例:

    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.

例如,如果表达式是

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

它将返回 V1ND

推荐答案

Rhino 1.7 R3 推出了 AST包,可用于查找名称:

Rhino 1.7 R3 introduced an AST package which can be used to find names:

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]

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

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.

这篇关于从javascript表达式获取变量(Rhino)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆