我正在使用esprima
andestraverse
模块对 JavaScript 代码进行静态分析。由于 JavaScript 不强制使用分号,因此在分析没有分号的代码时不会引发错误,但我希望这样做。
我想出的唯一解决方案是查找可能需要分号的表达式并检查是否有,但该esprima.parse
函数不记得任何分号的存在。标记化后它们似乎被忽略了。
> esprima.tokenize("a = 3;")
[
{ type: 'Identifier', value: 'a' },
{ type: 'Punctuator', value: '=' },
{ type: 'Numeric', value: '3' },
{ type: 'Punctuator', value: ';' } // <-- Present after tokenization
]
> console.log(JSON.stringify(esprima.parse("a = 3;"), null, 2))
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "AssignmentExpression",
"operator": "=",
"left": {
"type": "Identifier",
"name": "a"
},
"right": {
"type": "Literal",
"value": 3,
"raw": "3"
}
}
}
],
"sourceType": "script"
}
// Not present anywhere
所以,简而言之:有没有办法在使用 esprima 对 javascript 代码进行静态分析时检测丢失的分号?