Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Extract AST of given Typescript code using the open source Typescript compiler code?

As it is known that Typescript is completely opensource now. which is available at Tyescript. I am building an application that will get Typescript code as input and give output the AST of the given code. Provide me a proper way to extract this AST(Abstract Syntax Tree) of input Typescript code rather than comppliling it and converting it into Javascript.

like image 677
Ahmed Raza Avatar asked Apr 08 '16 17:04

Ahmed Raza


People also ask

What is AST in TypeScript?

The AST (Abstract Syntax Tree) quickly comes to your mind to approach this problem. The AST is a data structure to represent the structure of your source file in a format readable by machines. Indeed, if I throw the above example in the TypeScript AST Viewer I get immediate access to the AST.

How does the TypeScript compiler work?

The TypeScript compiler compiles these files and outputs the JavaScript with . js extension by keeping the same file name as the individual input file. The TypeScript compiler also preserves the original file path, hence the . js output file will be generated where the input file was in the directory structure.

What is AST JavaScript?

An AST is the result of parsing code. For JavaScript, an AST is a JavaScript object containing a tree representation of your source. Before we use it, we have to create it. Depending on the code we are parsing, we choose the appropriate parser. Here since the code is ES5-compatible, we can choose the acorn parser.


1 Answers

Basic code:

const fileNames = ["C:\\MyFile.ts"];
const compilerOptions: ts.CompilerOptions = {
    // compiler options go here if any...
    // look at ts.CompilerOptions to see what's available
};
const program = ts.createProgram(fileNames, compilerOptions);
const typeChecker = program.getTypeChecker();
const sourceFiles = program.getSourceFiles();

sourceFiles.filter(f => /MyFile\.ts$/.test(f.fileName)).forEach(sourceFile => {
    ts.forEachChild(sourceFile, node => {
        const declaration = node as ts.Declaration;
        if (declaration.name) {
            console.log(declaration.name.getText());
        }
    });
});

So if you provided that with a C:\MyFile.ts like:

class MyClass {}
interface MyInterface {}

It would output MyClass and MyInterface.

Figuring out everything beyond what I've just shown is a lot of work. It might be more beneficial for you to look at and/or help contribute to this work in progress.

like image 75
David Sherret Avatar answered Nov 15 '22 04:11

David Sherret