2012-08-09 39 views
0

我想通過javascript解析並查找所有變量聲明,歸因和對特定庫函數的調用。如何通過javascript文件解析?

什麼是最好的方法:正則表達式,詞法分析器,使用已經完成的事情(它是否存在?)....?

我想要的其實是要確保一個對象的命名空間和方法不會被修改,而這是通過一個靜態分析。

+0

瀏覽器已經這樣做非常好。您可以使用檢查器/分析器來查看解析的結果。 – 2012-08-09 07:37:17

回答

1

你不能用正則表達式來做,也可能你也不想寫你自己的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] } 
+0

您是否在Windows或Linux上使用pyV8? – 2012-08-09 08:19:26

+0

@EduardFlorinescu,當然是Linux! =) – Sergey 2012-08-09 08:22:31

+0

我在安裝boost.python – 2012-08-09 08:23:29

0

您可以使用Mozilla中的Rhino。這是一個用Java編寫的Javascript實現。 1.7R3版本開始有一個新的AST API。如果你想這樣做在Javascript中的類在org.mozilla.javascript.ast

用,請參閱該討論JavaScript parser in JavaScript

希望它能幫助。

+0

我已經在考慮pynoceros(python rhino port),pynarcissus和pyV8,所以感謝您確認我的aproach :),也感謝jslint解析器的消化,也許我還可以找到python的jslint端口並在正則表達式中查找。我發現它是從像'這樣的代碼對象構建的,任何想法我怎樣才能通過它來跟蹤變量?我不知道如何有效地使用它。 – 2012-08-09 08:33:18