Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
@solidity-parser/parser
Advanced tools
@solidity-parser/parser is an npm package designed to parse Solidity source code into an Abstract Syntax Tree (AST). This allows developers to analyze, transform, and manipulate Solidity code programmatically. It is particularly useful for building tools that need to understand the structure of Solidity code, such as linters, code formatters, and static analysis tools.
Parsing Solidity Code
This feature allows you to parse Solidity source code into an Abstract Syntax Tree (AST). The code sample demonstrates how to parse a simple Solidity contract and print the resulting AST.
const parser = require('@solidity-parser/parser');
const sourceCode = 'contract MyContract { uint256 public value; }';
const ast = parser.parse(sourceCode);
console.log(JSON.stringify(ast, null, 2));
Handling Parse Errors
This feature allows you to handle errors that occur during parsing. The code sample demonstrates how to catch and handle a parse error when the Solidity source code is incomplete or malformed.
const parser = require('@solidity-parser/parser');
const sourceCode = 'contract MyContract { uint256 public value;'; // Missing closing brace
try {
const ast = parser.parse(sourceCode);
} catch (error) {
console.error('Parse error:', error);
}
Traversing the AST
This feature allows you to traverse the AST and perform actions on specific nodes. The code sample demonstrates how to traverse the AST and print the name of each contract defined in the Solidity source code.
const parser = require('@solidity-parser/parser');
const sourceCode = 'contract MyContract { uint256 public value; }';
const ast = parser.parse(sourceCode);
parser.visit(ast, {
ContractDefinition: (node) => {
console.log('Contract name:', node.name);
}
});
solidity-ast is a package that provides utilities for working with the AST produced by the Solidity compiler. It is more tightly integrated with the Solidity compiler itself and is useful for tasks that require detailed information from the compiler's output. Compared to @solidity-parser/parser, it is more focused on post-compilation analysis.
solparse is another Solidity parser that converts Solidity code into an AST. It is similar to @solidity-parser/parser but is less actively maintained. It provides basic parsing capabilities but may lack some of the more advanced features and error handling provided by @solidity-parser/parser.
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.
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
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. |
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 } } }
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)
}
})
A browser-friendly version is available in dist/index.iife.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
.
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
FAQs
A Solidity parser built from a robust ANTLR 4 grammar
The npm package @solidity-parser/parser receives a total of 101,633 weekly downloads. As such, @solidity-parser/parser popularity was classified as popular.
We found that @solidity-parser/parser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.