acorn-walk vs esprima
JavaScript Parsing and AST Manipulation
acorn-walkesprimaSimilar Packages:

JavaScript Parsing and AST Manipulation

JavaScript Parsing and AST (Abstract Syntax Tree) Manipulation libraries are essential tools for analyzing, transforming, and understanding JavaScript code programmatically. These libraries parse JavaScript source code and generate a tree-like representation (AST) that reflects the structure of the code. This representation allows developers to perform various tasks such as code analysis, linting, minification, transpilation, and even automated code transformations. esprima is a high-performance, standards-compliant JavaScript parser that generates an AST from JavaScript code, making it suitable for static analysis and tooling. acorn-walk is a lightweight library built on top of the Acorn parser, providing a simple and efficient way to traverse and manipulate the AST, making it ideal for custom transformations and analysis.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
acorn-walk011,34053.8 kB1524 days agoMIT
esprima07,134-1498 years agoBSD-2-Clause

Feature Comparison: acorn-walk vs esprima

Parsing Performance

  • acorn-walk:

    acorn-walk is not a parser itself but a traversal library for the AST generated by the Acorn parser. The performance of acorn-walk depends on the Acorn parser, which is lightweight and fast, making it suitable for quick parsing and traversal tasks.

  • esprima:

    esprima is known for its high-performance parsing capabilities, making it one of the fastest parsers available. It is designed to handle large codebases efficiently while adhering to the ECMAScript specification, ensuring accurate parsing of JavaScript code.

AST Compliance

  • acorn-walk:

    acorn-walk works with the AST generated by the Acorn parser, which is also ESTree-compliant. This compatibility allows developers to use acorn-walk seamlessly with other ESTree-based tools and libraries for analysis and transformation.

  • esprima:

    esprima generates an AST that is compliant with the ESTree specification, which is widely adopted by JavaScript tooling and libraries. This compliance ensures compatibility with other tools that work with ESTree ASTs, making it a reliable choice for developers.

Customization and Extensibility

  • acorn-walk:

    acorn-walk is highly customizable, allowing developers to define their own traversal methods and algorithms. It provides a simple API for walking the AST, making it easy to implement custom logic for analysis, transformation, or manipulation of the AST nodes.

  • esprima:

    esprima provides limited customization options, as it is primarily focused on accurate and fast parsing. However, its AST structure is well-documented and can be extended by developers for specific use cases, such as building custom analyzers or transformers.

Ease of Use: Code Examples

  • acorn-walk:

    Traversing AST with acorn-walk

    const { parse } = require('acorn');
    const walk = require('acorn-walk');
    const code = 'const x = 10;';
    const ast = parse(code);
    walk.simple(ast, {
      VariableDeclaration(node) {
        console.log('Found a variable declaration:', node);
      }
    });
    
  • esprima:

    Parsing JavaScript with esprima

    const esprima = require('esprima');
    const code = 'const x = 10;';
    const ast = esprima.parseScript(code);
    console.log(JSON.stringify(ast, null, 2));
    

How to Choose: acorn-walk vs esprima

  • acorn-walk:

    Choose acorn-walk if you are working with the Acorn parser and need a lightweight, flexible solution for traversing and manipulating the AST. It is particularly useful for projects that require custom traversal algorithms or transformations without the overhead of a full-featured library.

  • esprima:

    Choose esprima if you need a fast, standards-compliant parser that generates a detailed AST for JavaScript code. It is suitable for static analysis, linting, and tools that require a reliable and accurate representation of the code structure.

README for acorn-walk

Acorn AST walker

An abstract syntax tree walker for the ESTree format.

Community

Acorn is open source software released under an MIT license.

You are welcome to report bugs or create pull requests on github.

Installation

The easiest way to install acorn is from npm:

npm install acorn-walk

Alternately, you can download the source and build acorn yourself:

git clone https://github.com/acornjs/acorn.git
cd acorn
npm install

Interface

An algorithm for recursing through a syntax tree is stored as an object, with a property for each tree node type holding a function that will recurse through such a node. There are several ways to run such a walker.

simple(node, visitors, base, state) does a 'simple' walk over a tree. node should be the AST node to walk, and visitors an object with properties whose names correspond to node types in the ESTree spec. The properties should contain functions that will be called with the node object and, if applicable the state at that point. The last two arguments are optional. base is a walker algorithm, and state is a start state. The default walker will simply visit all statements and expressions and not produce a meaningful state. (An example of a use of state is to track scope at each point in the tree.)

import * as acorn from "acorn"
import * as walk from "acorn-walk"

walk.simple(acorn.parse("let x = 10"), {
  Literal(node) {
    console.log(`Found a literal: ${node.value}`)
  }
})

ancestor(node, visitors, base, state) does a 'simple' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter.

import * as acorn from "acorn"
import * as walk from "acorn-walk"

walk.ancestor(acorn.parse("foo('hi')"), {
  Literal(_node, _state, ancestors) {
    console.log("This literal's ancestors are:", ancestors.map(n => n.type))
  }
})

recursive(node, state, functions, base) does a 'recursive' walk, where the walker functions are responsible for continuing the walk on the child nodes of their target node. state is the start state, and functions should contain an object that maps node types to walker functions. Such functions are called with (node, state, c) arguments, and can cause the walk to continue on a sub-node by calling the c argument on it with (node, state) arguments. The optional base argument provides the fallback walker functions for node types that aren't handled in the functions object. If not given, the default walkers will be used.

make(functions, base) builds a new walker object by using the walker functions in functions and filling in the missing ones by taking defaults from base.

full(node, callback, base, state) does a 'full' walk over a tree, calling the callback with the arguments (node, state, type) for each node

fullAncestor(node, callback, base, state) does a 'full' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter.

import * as acorn from "acorn"
import * as walk from "acorn-walk"

walk.full(acorn.parse("1 + 1"), node => {
  console.log(`There's a ${node.type} node at ${node.ch}`)
})

findNodeAt(node, start, end, test, base, state) tries to locate a node in a tree at the given start and/or end offsets, which satisfies the predicate test. start and end can be either null (as wildcard) or a number. test may be a string (indicating a node type) or a function that takes (nodeType, node) arguments and returns a boolean indicating whether this node is interesting. base and state are optional, and can be used to specify a custom walker. Nodes are tested from inner to outer, so if two nodes match the boundaries, the inner one will be preferred.

findNodeAround(node, pos, test, base, state) is a lot like findNodeAt, but will match any node that exists 'around' (spanning) the given position.

findNodeAfter(node, pos, test, base, state) is similar to findNodeAround, but will match all nodes after the given position (testing outer nodes before inner nodes).