Access the Abstract Syntax Tree of V8 Engine
Asked Answered
H

3

11

Is it possible to access the AST of the v8 engine, for a given JavaScript code? I'm working on a JavaScript Static Analyzer using V8 engine.

Halona answered 26/2, 2012 at 6:24 Comment(1)
possible duplicate of How do i access v8 parse tree how can it be done?Higgler
B
13

This is pretty old but maybe the answer helps someone stumbling upon this. The answer is yes, assuming you are willing to modify V8 and compile your own version of it.

If so, then in compiler.cc you find a spot where MakeCode is called throughout MakeFunctionInfo which transforms the AST that is stored in the passed in CompilationInfo object into native code. You need to write a class that inherits from AstVisitor then you can inspect the AST by inserting the following lines before the call to MakeCode:

MyAstVisitor mAV;
// this will call VisitFunctionLiteral in your AST visitor
info->function()->Accept(mAV);

As V8 compiles functions just-in-time when they are actually called, there is another spot in CompileLazy where you would have to do the same to get their ASTs throughout execution of calling scripts.

Because of the lazy compilation thing this probably won't enable you to do static analysis, because the execution already is in progress before you have access to the ASTs for lazily compiled stuff. But this is how to obtain the ASTs.

Benzoyl answered 4/10, 2012 at 14:53 Comment(0)
A
2

Use --print-ast via SetFlagsFromString

Anatomy answered 3/4, 2012 at 6:17 Comment(2)
I think OP wants access to the AST as a datastructure he can crawl. True, he can export like this and build his own AST reader, and crawl his own data structures, but I suspect he wants to avoid that bit of clumsiness if possible.Neurophysiology
Do you know if that flag still exist?Aryan
V
1

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:

https://chromium.googlesource.com/v8/v8/+/main/src/ast/ast.h

~Cheers

Vallee answered 23/7, 2012 at 8:45 Comment(1)
that link is no longer liveGunther

© 2022 - 2024 — McMap. All rights reserved.