On 20 Φεβ, 22:14, wolffiex <[email protected]> wrote: > On Jan 30, 10:49 am, wolffiex <[email protected]> wrote: > > > > > > > Hi list, > > I've been a happy Rhino user for a long time, but I'm looking at > > getting deeper into it, in order to add this feature to my app: Given > > the string source of a function, I'd like to get a list of all the > > closed-over variables within it. So, for instance: > > > myNewApi.getFreeVariables("function(a){ var b = 2; return a+b+c > > +d; }"); > > > would return the list of "c" and "d". > > > I've poked around the source for 1.7R2 but I didn't see any javadoc > > that would suggest how to do this. Even a pointer in the right > > direction would be very helpful. > > > Thanks! > > A > > Ok solved. I've pasted example code below. Now a follow up question: > is Parser.parse thread safe, or do I need a new instance for each > thread? > > public ScriptableObject getFreeVariables(String f){ > ScriptOrFnNode firstFunction = null; > try{ > ScriptOrFnNode node = parser.parse(f, "free variable > getter", 0); > firstFunction = node.getFunctionNode(0); > }catch (Exception e){ > logger.error("Can't find function in " + f); > } > ScriptableObject jsSet = makeJSObject(); > if (firstFunction != null){ > Set<String> varNames = new HashSet<String>(); > addVarNames(firstFunction, varNames); > final Map<String,? extends Object> symbolTable = > firstFunction.getSymbolTable(); > if (symbolTable != null) > varNames.removeAll(symbolTable.keySet()); > for (String varName : varNames){ > jsSet.put(varName, jsSet, true); > } > } > return jsSet; > } > > private void addVarNames(final Node fn, final Set<String> vars) { > if (fn.getType() == Token.NAME) { > vars.add(fn.getString()); > } > > if (fn.hasChildren()){ > Node p = fn.getFirstChild(); > do{ > addVarNames(p, vars); > p = p.getNext(); > }while(p!=null); > > } > > }
i have been looking for this long time! How ever do you have any idea how to replace the name of the variable? _______________________________________________ dev-tech-js-engine-rhino mailing list [email protected] https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino
