对于给定的 JavaScript 代码,是否可以访问 v8 引擎的 AST?我正在使用 V8 引擎开发 JavaScript 静态分析器。
3 回答
这已经很老了,但也许答案可以帮助偶然发现这一点的人。答案是肯定的,假设您愿意修改 V8 并编译您自己的版本。
如果是这样,那么在compiler.cc中,您会发现MakeCode 在整个MakeFunctionInfo中被调用,它将存储在传入的 CompilationInfo 对象中的 AST 转换为本机代码。您需要编写一个继承自AstVisitor的类,然后您可以通过在调用MakeCode之前插入以下行来检查 AST :
MyAstVisitor mAV;
// this will call VisitFunctionLiteral in your AST visitor
info->function()->Accept(mAV);
由于 V8 会在实际调用函数时即时编译函数,因此在CompileLazy中还有一个地方,您必须在执行调用脚本的整个过程中执行相同的操作才能获取它们的 AST。
由于延迟编译的事情,这可能无法让您进行静态分析,因为在您访问 AST 以获取延迟编译的内容之前,执行已经在进行中。但这就是获取 AST 的方法。
--print-ast
通过使用SetFlagsFromString
Well, I don't know what you want to achieve, but it sounds like you want to modify the AST from inside your C++ code (or maybe write wrapper classes for the JavaScript context for them as well?).
I suggest to take a look at the headers file which pretty explains what's there to be used on V8's AST:
http://v8.googlecode.com/svn/trunk/src/ast.h
~Cheers