在javascript中检索javascript注释,或者,如何在js中解析js?

Eri*_*ric 3 javascript parsing comments

我正在寻找一种方法来从一些(其他)JavaScript代码访问JavaScript的评论.我计划使用它来显示页面上调用各种js函数的元素的低级帮助信息,而不会在多个位置复制该信息.

的mypage.html:

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

foo.js:

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

我想我可以使用getElementsByTagName来获取脚本标记,然后使用AJAX请求加载文件以获取它的纯文本内容.然而,那时我需要一种方法来以可靠的方式解析javascript(即不是一堆乱砍的regexp),它们保留了那些简单地评估它会抛弃的字符.

我想把简单地把文档放在函数之后,用js字符串,但这很尴尬,我觉得让doxygen选择那个很难.

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

Bar*_*ers 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
  =  .
Run Code Online (Sandbox Code Playgroud)

使用生成的解析器解析以下源时:

/**
 * 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(){};
Run Code Online (Sandbox Code Playgroud)

start()解析器的功能返回以下映射:

{
   "foo": "/** * This function does foo. * Call it with bar. Yadda yadda \"groo\". */",
   "withoutMultiLineComment": null,
   "doc_way_above": "/** * BAR! * Call it? */"
}
Run Code Online (Sandbox Code Playgroud)

我知道有一些空白需要填补(像this.id = function() { ... }),但看完后从PEG.js的文档了一下,不应该是一个大问题(假设你知道一点点解析器发电机).如果它是一个问题,回发后我会将它添加到语法中并解释一下语法中发生了什么.

您甚至可以在线测试上面发布的语法!