如何通过javascript文件进行解析? [英] How to approach parsing through a javascript file?
问题描述
我想通过JavaScript进行解析,并找到特定库中的所有变量声明,属性和对函数的调用.
I want to parse through a javascript and find all the variable declarations, attributions, and calls to functions from a specific library.
最好的方法是什么:正则表达式,词法分析器(Lexer)使用已经完成的事情(确实存在吗?)....
What would be the best approach:regular expressions, lexer, use something already done that does that (does it exist?)....?
事实上,我要确保不修改对象名称空间和方法,而这是通过静态分析实现的.
What I want in fact is to be assured that an object namespace and methods are not modified, and this through a static analysis.
推荐答案
您无法使用正则表达式执行此操作,并且可能您也不想编写自己的 PyV8 .我建议您可以使用它.
You can not do it with regexes and probably you also do not want to write you own implementation of ecma-standard 262 (It is a total overkill).
As for me I dig google's V8 javascript engine, more precisely PyV8. I suggest you can use it.
如果遇到问题,可以使用我用来安装的代码(x64系统的pip安装有错误,因此我使用了源代码):
If you had problems there is the code I used to install (pip installation had an error for my x64 system, so I used sources):
apt-get install subversion scons libboost-python-dev
svn checkout http://v8.googlecode.com/svn/trunk/ v8
svn checkout http://pyv8.googlecode.com/svn/trunk/ pyv8
cd v8
export PyV8=`pwd`
cd ../pyv8
sudo python setup.py build
sudo python setup.py install
我记得这些命令并没有给我带来错误. (我复制粘贴了它,但是它起作用了)
As I remember these commands did not make errors for me. (I copypasted it but it worked)
问题本身的答案:
更复杂的hello wolrd示例,列出全局对象的一些变量:
Answer to the question itself:
More complex hello wolrd example, list some varibales of the global object:
import PyV8
class Global(PyV8.JSClass): # define a compatible javascript class
def hello(self): # define a method
print "Hello World"
def alert(self, message): # my own alert function
print type(message), ' ', message
@property
def GObject(self): return self
def __setattr__(self, key, value):
super(Global, self).__setattr__(key, value)
print key, '=', value
G = Global()
ctxt = PyV8.JSContext(G)
ctxt.enter()
ctxt.eval("var a=hello; GObject.b=1.0; a();")
list_all_cmd = '''for (myKey in GObject){
alert(GObject[myKey]);
}'''
ctxt.eval(list_all_cmd)
ctxt.leave()
(在浏览器中,您应该将您称为全局对象-窗口)
该代码将输出:
(In browsers you should call you global object - Window)
This code will output:
b = 1
Hello World
<class '__main__.Global'> <__main__.Global object at 0x7f202c9159d0>
<class '_PyV8.JSFunction'> function () { [native code] }
<type 'int'> 1
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
<class '_PyV8.JSFunction'> function () { [native code] }
这篇关于如何通过javascript文件进行解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!