Comprehensive Guide to ast-query Enhancing AST Manipulation with Practical Examples

Introduction to ast-query

ast-query is a powerful library that allows developers to traverse and manipulate Abstract Syntax Trees (ASTs) with ease. It provides a rich set of APIs for querying and transforming code structures programmatically. Whether you’re developing code analysis tools, linters, or compilers, ast-query can significantly streamline your workflow.

Key APIs of ast-query

1. Importing the Library


const ASTQuery = require('ast-query');

2. Loading a Source File


const code = `
  function add(a, b) {
    return a + b;
  }`;

const ast = ASTQuery(code);

3. Finding Function Declarations


const functions = ast.find('FunctionDeclaration');
console.log(functions.length); // Output: 1

4. Replacing Identifiers


ast.find('Identifier')
  .filter(node => node.node.name === 'add')
  .replaceWith('sum');

console.log(ast.toString());

5. Adding New Nodes


ast.find('FunctionDeclaration')
  .append('');

console.log(ast.toString());

Example Application with ast-query

Let’s create a simple application using ast-query to rename all function declarations with a prefix and add a return statement to each function.


const ASTQuery = require('ast-query');

const code = `
function greet(name) {
  console.log('Hello, ' + name);
}

function farewell(name) {
  console.log('Goodbye, ' + name);
}`;

const ast = ASTQuery(code);

// Add prefix to function names
ast.find('FunctionDeclaration')
  .forEach(node => {
    const name = node.name;
    node.node.id.name = 'myPrefix_' + name;
  });

// Add a return statement to each function
ast.find('FunctionDeclaration')
  .forEach(node => {
    node.append('');
  });

console.log(ast.toString());

This example demonstrates how ast-query can be used to traverse and transform JavaScript code, making it an invaluable tool for developers working with abstract syntax trees.

Hash: 221d74ea786ffc5c82de70fd84ee84573d10719bd6498925270ee40de54bc0e4

Leave a Reply

Your email address will not be published. Required fields are marked *