要创建一个 IDE 来自动完成用户声明的所有变量,但不会注意到其他变量,例如 Math.PI
甚至模块 Math
,IDE 将需要能够识别与用户声明的变量相关的所有标识符。假设您已经可以访问程序的 AST(抽象符号表),可以使用什么机制来捕获所有此类变量?
我正在使用 reflect.js ( https://github.com/zaach/reflect.js ) 生成 AST。
最佳答案
我认为这几乎是不可能的
这就是为什么我认为不执行它几乎是不可能的:
让我们从易到难过一遍未探索的部分。
容易捕捉:
函数作用域在这里遗漏了:
(function(x){
//x is now an object with an a property equal to 3
// for the scope of that IIFE.
x;
})({a:3});
这里有一些有趣的肮脏技巧供大家使用。
介绍...鼓声... block 作用域!!
with({x:3}){
x;//x is now declared in the scope of that with and is equal to 3.
}
try{ throw 5}catch(x){
x // x is now declared in the scope of the try block and is equal to 5;
}
(阅读的人:我求求你不要将最后两个用于代码中的实际范围界定:))
不容易:
括号表示法:
var n = "lo";
a["h"+"e"+"l"+n] = "world"; // need to understand that a.hello is a property.
// not a part of the ast!
真正困难的部分:
让我们不要忘记调用编译器这些不会出现在 AST 中:
eval("var x=5"); // declares x as 5, just a string literal and a function call
new Function("window.x = 5")();// or global in node
在 node.js 中,这也可以通过 vm
模块来完成。在浏览器中使用 document.write 或 script 标签注入(inject)。
还有什么?当然,他们可以混淆所有他们想要的:
new Function(["w","i","n","dow.x"," = ","5"].join(""))(); // Good luck finding this!
new Function('new Function(["w","i","n","dow.x"," = ","5"].join(""))()')();// Getting dizzy already?
那么可以做什么呢?
- 在更新符号表(仅相关部分)时在封闭的定时环境中执行一次代码
- 查看执行生成的符号表是什么
- Boom,你得到了一个符号表。
这并不可靠,但它可能与您得到的一样接近。
我能想到的唯一其他选择,也是大多数 IDE 正在做的,就是简单地忽略任何不是:
object.property = ... //property definition
var a = ... //scoped
b = ... //global, or error in strict mode
function fn(){ //function declaration
object["property"] //property with a _fixed_ literal in bracket notation.
还有函数参数。
我见过 没有 IDE 能够处理任何,除了这些。由于它们是迄今为止最常见的,因此我认为计算它们是完全合理的。
关于javascript - 声明 Javascript 变量的所有可能方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17351705/