2010-11-19 93 views
3

我正在尋找一種方法來訪問來自一些(其他)JavaScript代碼的javascript評論。 我打算使用它來顯示調用各種js函數的頁面上的元素的低級別幫助信息,而不用在多個地方複製該信息。在javascript中檢索javascript評論,或者,如何在js中解析js?

的mypage.html:

... 
<script src="foo.js"></script> 
... 
<span onclick="foo(bar);">clickme</span> 
<span onclick="showhelpfor('foo');>?</span> 
... 

foo.js:

/** 
* This function does foo. 
* Call it with bar. Yadda yadda "groo". 
*/ 
function foo(x) 
{ 
    ... 
} 

我想我可以使用的getElementsByTagName搶script標籤,然後用AJAX請求,以獲得純加載文件它的文字內容。然而,那麼我需要一種可靠的方式來解析JavaScript(即不是一堆黑客一起正則表達式),它保留了簡單評估它的人物會丟棄的字符。

我正在考慮簡單地將文檔放在函數後面,在一個js字符串中,但這很尷尬,我有一種感覺,讓doxygen去挑選它會很困難。

function foo(x) { ... } 
foo.comment = "\ 
This functions does foo.\ 
Call it with bar. Yadda yadda \"groo\".\ 
"; 

回答

8

您可以創建一個不解析完整JS語言的小解析器,但當然只匹配字符串文字,單行和多行註釋和函數。

有一個名爲PEG.js的JS解析器生成器,可以很容易地做到這一點。語法看起來是這樣的:

{ 
var functions = {}; 
var buffer = ''; 
} 

start 
    = unit* {return functions;} 

unit 
    = func 
/string 
/multi_line_comment 
/single_line_comment 
/any_char 

func 
    = m:multi_line_comment spaces? "function" spaces id:identifier {functions[id] = m;} 
/"function" spaces id:identifier        {functions[id] = null;} 

multi_line_comment 
    = "/*" 
    (!{return buffer.match(/\*\//)} c:. {buffer += c;})*    
    { 
     var temp = buffer; 
     buffer = ''; 
     return "/*" + temp.replace(/\s+/g, ' '); 
    } 

single_line_comment 
    = "//" [^\r\n]* 

identifier 
    = a:([a-z]/[A-Z]/"_") b:([a-z]/[A-Z]/[0-9] /"_")* {return a + b.join("");} 

spaces 
    = [ \t\r\n]+ {return "";} 

string 
    = "\"" ("\\" ./[^"])* "\"" 
/"'" ("\\" ./[^'])* "'" 

any_char 
    = . 

當你解析與生成的解析器以下來源:

/** 
* This function does foo. 
* Call it with bar. Yadda yadda "groo". 
*/ 
function foo(x) 
{ 
    ... 
} 

var s = " /* ... */ function notAFunction() {} ... "; 

// function alsoNotAFunction() 
// { ... } 

function withoutMultiLineComment() { 
} 

var t = ' /* ... */ function notAFunction() {} ... '; 

/** 
* BAR! 
* Call it? 
*/ 





      function doc_way_above(x, y, z) { 
    ... 
} 

// function done(){}; 

解析器的start()函數返回以下地圖:

{ 
    "foo": "/** * This function does foo. * Call it with bar. Yadda yadda \"groo\". */", 
    "withoutMultiLineComment": null, 
    "doc_way_above": "/** * BAR! * Call it? */" 
} 

我意識到有一些需要填補的空白(如this.id = function() { ... }),但在閱讀the docs from PEG.js之後,這應該不是什麼大問題(諷刺g你知道一些解析器生成器)。如果這是一個問題,請回復並將其添加到語法中,並解釋一下語法中發生的事情。

你甚至可以在test the grammar以上發佈在線!

+0

eek,這比我所希望的要多一點,但它看起來應該做我所需要的。謝謝! – Eric 2013-04-09 16:54:19

0

你可以在每一個註釋的開始使用一個唯一的字符串標識,然後使用唯一的標識符,你可以很容易地製作一個正則表達式來提取評論。