我想通过javascript解析并查找所有变量声明,归因和对特定库函数的调用。如何通过javascript文件解析?
什么是最好的方法:正则表达式,词法分析器,使用已经完成的事情(它是否存在?)....?
我想要的其实是要确保一个对象的命名空间和方法不会被修改,而这是通过一个静态分析。
我想通过javascript解析并查找所有变量声明,归因和对特定库函数的调用。如何通过javascript文件解析?
什么是最好的方法:正则表达式,词法分析器,使用已经完成的事情(它是否存在?)....?
我想要的其实是要确保一个对象的命名空间和方法不会被修改,而这是通过一个静态分析。
你不能用正则表达式来做,也可能你也不想写你自己的ecma-standard 262(这是一个总的矫枉过正)的实现。
至于我挖掘谷歌的V8 JavaScript引擎,更准确地说是PyV8。我建议你可以使用它。
如果你有问题,还有就是我用来安装(PIP安装为我的64位系统中的错误,所以我用源)代码:
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
我记得这些命令没有为犯错误我。 (我copypasted,但它的工作)
问题的答案本身:
更复杂你好世界国际例子,列出了全局对象的一些varibales:
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()
(在浏览器中,你应该打电话给你全局对象 - 窗口)
此代码将输出:
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] }
您是否在Windows或Linux上使用pyV8? – 2012-08-09 08:19:26
@EduardFlorinescu,当然是Linux! =) – Sergey 2012-08-09 08:22:31
我在安装boost.python – 2012-08-09 08:23:29
您可以使用Mozilla中的Rhino。这是一个用Java编写的Javascript实现。 1.7R3版本开始有一个新的AST API。如果你想这样做在Javascript中的类在org.mozilla.javascript.ast
用,请参阅该讨论JavaScript parser in JavaScript
希望它能帮助。
我已经在考虑pynoceros(python rhino port),pynarcissus和pyV8,所以感谢您确认我的aproach :),也感谢jslint解析器的消化,也许我还可以找到python的jslint端口并在正则表达式中查找。我发现它是从像'
浏览器已经这样做非常好。您可以使用检查器/分析器来查看解析的结果。 – 2012-08-09 07:37:17