How make AST in typescript
- User
How make AST in typescript
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How make AST in typescript
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating an Abstract Syntax Tree (AST) in TypeScript involves a few different scenarios:
Let's explore these:
The most robust way to get an AST for TypeScript code is to use the TypeScript Compiler API itself. For JavaScript, or if you prefer an ESTree-compliant AST (a widely adopted specification for JS ASTs), you can use parsers like Acorn, Esprima, or @babel/parser.
A. Using the TypeScript Compiler API
This gives you the most accurate AST for TypeScript code, including all its type information and specific syntax.
npm install typescript
# or
yarn add typescript
// ast-parser-ts-api.ts
import * as ts from 'typescript';
function printAST(node: ts.Node, indent: string = ''): void {
console.log(`${indent}Kind: ${ts.SyntaxKind[node.kind]} (Pos: ${node.pos}-${node.end})`);
// You can add more properties like node.getText(), etc.
ts.forEachChild(node, child => {
printAST(child, indent + ' ');
});
}
const sourceCode = `
const x: number = 10;
function greet(name: string): void {
console.log(\`Hello, \${name}!\`);
}
`;
// 1. Create a SourceFile node
const sourceFile = ts.createSourceFile(
'myFile.ts', // fileName
sourceCode, // sourceText
ts.ScriptTarget.ESNext, // langugeVersion
true // setParentNodes
);
console.log('--- TypeScript Compiler API AST ---');
printAST(sourceFile);
// Example: Finding all function declarations
function findFunctionDeclarations(node: ts.Node): ts.FunctionDeclaration[] {
const functions: ts.FunctionDeclaration[] = [];
function visit(n: ts.Node) {
if (ts.isFunctionDeclaration(n) && n.name) {
functions.push(n);
}
ts.forEachChild(n, visit);
}
visit(node);
return functions;
}
const fns = findFunctionDeclarations(sourceFile);
fns.forEach(fn => console.log(`\nFound function: ${fn.name?.getText(sourceFile)}`));
Key typescript module members:
ts.createSourceFile(): Parses code into a SourceFile node (the root of the AST).ts.SyntaxKind: An enum that provides names for all node kinds (e.g., SyntaxKind.Identifier, SyntaxKind.FunctionDeclaration).ts.forEachChild(node, callback): A utility to visit direct children of a node.ts.isIdentifier(node), ts.isFunctionDeclaration(node) are very useful.B. Using an ESTree-compliant Parser (e.g., @babel/parser)
If you need an AST that conforms to the ESTree specification (common for JavaScript tooling like ESLint, Prettier, Babel plugins), @babel/parser is a good choice as it has excellent TypeScript support.
npm install @babel/parser
# or
yarn add @babel/parser
// ast-parser-babel.ts
import * as parser from '@babel/parser';
import { Node } from '@babel/types'; // For type information
function printESTreeAST(node: Node | null | undefined, indent: string = ''): void {
if (!node) return;
console.log(`${indent}Type: ${node.type} (Loc: ${node.loc?.start.line}:${node.loc?.start.column})`);
// Specific properties depend on the node type
// e.g., if (node.type === 'Identifier') console.log(`${indent} Name: ${node.name}`);
// Iterate over known children properties (this is simplified)
for (const key in node) {
if (Object.prototype.hasOwnProperty.call(node, key)) {
const value = (node as any)[key];
if (typeof value === 'object' && value !== null && 'type' in value) {
printESTreeAST(value as Node, indent + ' ');
} else if (Array.isArray(value)) {
value.forEach(item => {
if (typeof item === 'object' && item !== null && 'type' in item) {
printESTreeAST(item as Node, indent + ' ');
}
});
}
}
}
}
const sourceCodeJS = `
const x = 10;
function greet(name) {
console.log(\`Hello, \${name}!\`);
}
`;
const sourceCodeTS = `
const y: number = 20;
interface Person { name: string; }
`;
console.log('--- @babel/parser AST for JavaScript ---');
const astJS = parser.parse(sourceCodeJS, {
sourceType: 'module',
plugins: [] // Add 'jsx' or other JS features if needed
});
// console.log(JSON.stringify(astJS, null, 2)); // For full structure
printESTreeAST(astJS.program);
console.log('\n--- @babel/parser AST for TypeScript ---');
const astTS = parser.parse(sourceCodeTS, {
sourceType: 'module',
plugins: [
'typescript' // Enable TypeScript parsing
// 'jsx' // if you also have JSX
]
});
// console.log(JSON.stringify(astTS, null, 2));
printESTreeAST(astTS.program);
For ESTree, you'd typically use a visitor library like estraverse or @babel/traverse for more complex operations.
This is useful if you're creating a parser for a custom language or need a simplified AST representation for a specific task.
// custom-ast-nodes.ts
// Base node type
interface AstNode {
type: string;
// Common properties like location (optional)
// loc?: { start: number, end: number };
}
// Specific node types
interface LiteralNode extends AstNode {
type: 'Literal';
value: string | number | boolean;
}
interface IdentifierNode extends AstNode {
type: 'Identifier';
name: string;
}
interface BinaryExpressionNode extends AstNode {
type: 'BinaryExpression';
operator: string;
left: ExpressionNode; // Use a union type for children that can be different expression types
right: ExpressionNode;
}
interface VariableDeclarationNode extends AstNode {
type: 'VariableDeclaration';
identifier: IdentifierNode;
initializer: ExpressionNode | null; // Can be uninitialized
}
// Union type for any expression
type ExpressionNode = LiteralNode | IdentifierNode | BinaryExpressionNode;
// Union type for any statement or the program root
type StatementNode = VariableDeclarationNode | BinaryExpressionNode; // BinaryExpression can be top-level
interface ProgramNode extends AstNode {
type: 'Program';
body: StatementNode[];
}
// Example usage (manual construction, see next section)
const myCustomAST: ProgramNode = {
type: 'Program',
body: [
{
type: 'VariableDeclaration',
identifier: { type: 'Identifier', name: 'x' },
initializer: { type: 'Literal', value: 10 }
},
{
type: 'BinaryExpression',
operator: '+',
left: { type: 'Identifier', name: 'x' },
right: {
type: 'BinaryExpression',
operator: '*',
left: { type: 'Literal', value: 2 },
right: { type: 'Identifier', name: 'y' }
}
}
]
};
console.log('\n--- Custom AST Definition ---');
console.log(JSON.stringify(myCustomAST, null, 2));
Using interfaces (or classes) with TypeScript's type system here is highly beneficial for ensuring your AST structure is consistent.
Once you have node type definitions (either your own or from a library like @babel/types or the typescript module's factory functions), you can build an AST programmatically.
A. Using Custom Node Types (from above example)
// manual-ast-construction.ts
// (Assuming AstNode, LiteralNode, etc. interfaces are defined as in the previous example)
// Factory functions can make this cleaner
function createLiteral(value: string | number | boolean): LiteralNode {
return { type: 'Literal', value };
}
function createIdentifier(name: string): IdentifierNode {
return { type: 'Identifier', name };
}
function createBinaryExpression(left: ExpressionNode, operator: string, right: ExpressionNode): BinaryExpressionNode {
return { type: 'BinaryExpression', operator, left, right };
}
function createVariableDeclaration(name: string, initializer: ExpressionNode | null): VariableDeclarationNode {
const identifier = createIdentifier(name);
return { type: 'VariableDeclaration', identifier, initializer };
}
function createProgram(body: StatementNode[]): ProgramNode {
return { type: 'Program', body };
}
const constructedAST: ProgramNode = createProgram([
createVariableDeclaration('a', createLiteral(5)),
createVariableDeclaration('b', createLiteral(10)),
createBinaryExpression(
createIdentifier('a'),
'+',
createBinaryExpression(
createIdentifier('b'),
'*',
createLiteral(2)
)
)
]);
console.log('\n--- Manually Constructed Custom AST ---');
console.log(JSON.stringify(constructedAST, null, 2));
// Representing:
// const a = 5;
// const b = 10;
// a + (b * 2);
B. Using TypeScript Compiler API Factory Functions
The typescript module provides factory functions (e.g., ts.factory.createIdentifier, ts.factory.createNumericLiteral) to programmatically build TypeScript AST nodes. This is useful for code generation or transformation.
// manual-ast-ts-factory.ts
import * as ts from 'typescript';
// Create: const message = "Hello, AST!";
const variableName = ts.factory.createIdentifier("message");
const stringLiteral = ts.factory.createStringLiteral("Hello, AST!");
const variableDeclaration = ts.factory.createVariableDeclaration(
variableName,
undefined, // exclamationToken (for non-null assertion)
undefined, // type
stringLiteral
);
const variableStatement = ts.factory.createVariableStatement(
undefined, // modifiers
ts.factory.createVariableDeclarationList(
[variableDeclaration],
ts.NodeFlags.Const // let, const, var
)
);
// To print this AST as code:
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const resultFile = ts.createSourceFile(
"generated.ts",
"",
ts.ScriptTarget.ESNext,
false,
ts.ScriptKind.TS
);
const generatedCode = printer.printNode(
ts.EmitHint.Unspecified, // Or EmitHint.SourceFile for a whole file
variableStatement,
resultFile
);
console.log('\n--- Manually Constructed AST with TS Factory ---');
console.log("Generated AST Node (VariableStatement):");
// For brevity, just showing the kind, normally you'd inspect its properties
console.log(`Kind: ${ts.SyntaxKind[variableStatement.kind]}`);
variableStatement.declarationList.declarations.forEach(decl => {
console.log(` Var: ${ts.isIdentifier(decl.name) ? decl.name.escapedText : 'complex'}`);
if (decl.initializer) {
console.log(` Init Kind: ${ts.SyntaxKind[decl.initializer.kind]}`);
if (ts.isStringLiteral(decl.initializer)) {
console.log(` Init Value: ${decl.initializer.text}`);
}
}
});
console.log("\nGenerated Code:");
console.log(generatedCode);
Choosing the Right Approach:
@babel/parser or similar.Remember that working with ASTs, especially complex ones like those from the TS Compiler API, involves understanding the various node types and their properties. The AST Explorer website is an invaluable tool for visualizing ASTs generated by different parsers.