Shift Parser

8.0.0 · active · verified Tue Apr 21

shift-parser is an ECMAScript parser that generates an Abstract Syntax Tree (AST) conforming to the Shift format. Currently at version 8.0.0, the library provides distinct functions for parsing ECMAScript scripts and modules, offering capabilities for static analysis and code transformation. Although its README suggests support for ECMA-262, version 6 (ES2015), the underlying Shift AST Specification, which `shift-parser` implements, states support for ECMAScript 2019. This indicates the parser likely handles features up to ES2019. The package is generally stable, with major versions released periodically rather than on a strict cadence. A key differentiator is its adherence to the machine-readable Shift AST format, which promotes consistency across various JavaScript tooling. It also offers an extended interface for capturing detailed location and comment information using `WeakMap`.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing an ECMAScript module, accessing the AST, retrieving location data for nodes, and extracting comments.

import { parseModuleWithLocation } from 'shift-parser';

const code = `
  // This is a comment
  import { add } from './math.js';
  function calculate(a, b) {
    const result = add(a, b);
    return result; // Another comment
  }
  console.log(calculate(5, 3));
`;

try {
  const { tree, locations, comments } = parseModuleWithLocation(code);

  console.log('Parsed AST root type:', tree.type);
  console.log('Number of top-level statements:', tree.statements.length);

  // Accessing a specific node and its location
  const functionDeclaration = tree.statements[2]; // Assuming 'function calculate' is the third statement
  if (functionDeclaration && locations.has(functionDeclaration)) {
    const loc = locations.get(functionDeclaration);
    console.log(`'calculate' function starts at line ${loc.start.line}, column ${loc.start.column}`);
  }

  // Logging comments
  console.log('Found comments:', comments.map(c => c.text));

} catch (e) {
  if (e instanceof SyntaxError) {
    console.error('Parsing failed:', e.message);
  } else {
    console.error('An unexpected error occurred:', e);
  }
}

view raw JSON →