Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@solidity-parser/parser

solidity-parser1.8mMIT0.20.2TypeScript support: included

A Solidity parser built from a robust ANTLR 4 grammar

readme

Solidity Parser for JavaScript

npm version

A JavaScript package for parsing Solidity code using ANTLR (ANother Tool for Language Recognition) grammar.

This is a fork of @federicobond's original repo, with some extra features taken from Consensys Diligence's alternative fork.

Installation

The following installation options assume Node.js has already been installed.

Using Node Package Manager (npm).

npm install @solidity-parser/parser

Using yarn

yarn add @solidity-parser/parser

Usage

const parser = require('@solidity-parser/parser')

const input = `
    contract test {
        uint256 a;
        function f() {}
    }
`
try {
  const ast = parser.parse(input)
  console.log(ast)
} catch (e) {
  if (e instanceof parser.ParserError) {
    console.error(e.errors)
  }
}

The parse method also accepts a second argument which lets you specify the following options, in a style similar to the esprima API:

Key Type Default Description
tolerant Boolean false When set to true it will collect syntax errors and place them in a list under the key errors inside the root node of the returned AST. Otherwise, it will raise a parser.ParserError.
loc Boolean false When set to true, it will add location information to each node, with start and stop keys that contain the corresponding line and column numbers. Column numbers start from 0, lines start from 1.
range Boolean false When set to true, it will add range information to each node, which consists of a two-element array with start and stop character indexes in the input.

Example with location information

parser.parse('contract test { uint a; }', { loc: true })

// { type: 'SourceUnit',
//   children:
//    [ { type: 'ContractDefinition',
//        name: 'test',
//        baseContracts: [],
//        subNodes: [Array],
//        kind: 'contract',
//        loc: [Object] } ],
//   loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 24 } } }

Example using a visitor to walk over the AST

var ast = parser.parse('contract test { uint a; }')

// output the path of each import found
parser.visit(ast, {
  ImportDirective: function (node) {
    console.log(node.path)
  },
})

Usage in the browser

A browser-friendly version is available in dist/index.umd.js (along with its sourcemaps file) in the published version.

If you are using webpack, keep in mind that minimizing your bundle will mangle function names, breaking the parser. To fix this you can just set optimization.minimize to false.

Contribution

This project is dependant on the @solidity-parser/antlr repository via a git submodule. To clone this repository and the submodule, run

git clone --recursive

If you have already cloned this repo, you can load the submodule with

git submodule update --init

This project can be linked to a forked @solidity-parser/antlr project by editing the url in the .gitmodules file to point to the forked repo and running

git submodule sync

The Solidity ANTLR file Solidity.g4 can be built with the following. This will also download the ANTLR Java Archive (jar) file to antlr/antlr4.jar if it doesn't already exist. The generated ANTLR tokens and JavaScript files are copied the src folder.

yarn run antlr

The files to be distributed with the npm package are in the dist folder and built by running

yarn run build

The mocha tests under the test folder can be run with the following. This includes parsing the test.sol Solidity file.

yarn run test

Used by

License

MIT

changelog

0.19.0

  • Add support for transient storage variables. (#119)

0.18.0

  • Parser function now has an option to return comments as part of the parsed result. (#105)
  • We now export umd instead of iife format for browser compatibility. (#106)

0.17.0

  • Using the official typescript target for antlr4. (#103)
  • Exponentiation is right associative. a ** (b ** c) (#99)
  • Conditional expression is right associative. a ? (b ? c : d) : (e ? f : g) (#99)

0.5.0

  • Remove ParameterList and Parameter node types. Parameters are now always of type VariableDeclaration and lists of parameters are represented as lists of nodes of type VariableDeclaration. This is a breaking change.

0.4.12

  • Fix type name expressions to also support user-defined type names.

0.4.11

  • Bugfix release

0.4.9

  • Fix parsing of inheritance specifier with no arguments.

0.4.8

  • Fix parsing of string literals with escaped characters.

0.4.7

  • Fix parsing of underscores in number literals.

0.4.6

  • Add support for the type keyword.
  • Add support for underscores in number literals.

0.4.5

  • Improve TypeScript type definitions.

0.4.4

  • Add missing storageLocation to variables in VariableDeclarationStatement.
  • Return null for arguments instead of [] when ModifierInvocation contains no arguments and no parentheses to distinguish the two cases.
  • Improve TypeScript type definitions.

0.4.3

  • Improve TypeScript type definitions, thanks @Leeleo3x and @yxliang01.

0.4.2

  • Fix parsing of assembly function definitions with no args or return args.

0.4.1

  • Fix parsing of for loops with missing initial and condition statements.

0.4.0

  • Correctly handle non-existent tuple components. Thanks @maxsam4
  • Accept calldata as identifier

0.3.3

  • Add support for address payable typename.

0.3.2

  • Fix parsing of hex numbers with uppercase X.

0.3.1

  • Fix parsing of zero-component tuples.

0.3.0

  • Use components for all TupleExpression nodes. Earlier versions incorrectly stored tuple components under the elements key.
  • Fix parsing of decimal literals without integer part.