Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 74 additions & 88 deletions DEVELOPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,122 +6,112 @@ If you notice that this document is outdated, or if something isn't clear to you

## Architecture

This package is a wrapper around a parser generated by [ANTLR](https://www.antlr.org/). This makes it hard to describe the components, since there are two parsers: the one exported by this project, and the one generated by ANTLR. To avoid confusion, we will call "parser" to the one exported by this project, and "generated parser" to the one generated by ANTLR.
This package wraps a parser generated by [ANTLR](https://www.antlr.org/). In this guide, "parser" means the public API exported by this package, and "generated parser" means the code produced by ANTLR.

The grammar description used as input for ANTLR lives in [this repo](https://github.com/solidity-parser/antlr), which is included here as a git submodule. The grammar file is `Solidity.g4`. This means that some issues can be fixed just in this repository, while others depend on updates to the ANTLR grammar. In the latter case, the fix usually involves updating the grammar, updating the submodule in this repository, updating the generated parser and probably updating the parser to handle these changes.
The grammar lives in the [solidity-parser/antlr repository](https://github.com/solidity-parser/antlr), included here as a Git submodule at `antlr/`. Its `Solidity.g4` file defines the syntax accepted by the generated parser. Grammar changes belong in that repository; consuming them here involves updating the submodule commit, regenerating the parser, and adapting the AST builder if needed.

For example, an issue like "the list of state variables in the generated AST code should be in the same order than in the solidity file" probably can be done by just updating the code in the parser. On the other hand, an issue like "support this new keyword" will need an update to the grammar.
For example, changing the order of state variables in the public AST may only require a change to the AST builder. Supporting a new Solidity keyword usually also requires a grammar change.

The entry point of the project is [`src/index.js`](src/index.js), but most of the important logic is in [`src/ASTBuilder.js`](src/ASTBuilder.js). `ASTBuilder` is a [visitor](https://en.wikipedia.org/wiki/Visitor_pattern) object that traverses the AST returned by the generated parser, and produces the AST that will be returned by the parser.
The public entry point is [`src/index.ts`](src/index.ts), which re-exports the API from [`src/parser.ts`](src/parser.ts). The `parse()` implementation runs the generated lexer and parser in [`src/antlr/`](src/antlr/), then uses [`src/ASTBuilder.ts`](src/ASTBuilder.ts) to turn their parse tree into the public AST. `ASTBuilder` is a [visitor](https://en.wikipedia.org/wiki/Visitor_pattern); its `visit...` methods handle grammar contexts and construct the node types declared in [`src/ast-types.ts`](src/ast-types.ts). Its `_addMeta()` helper adds location and range information when requested.

## Setup

```bash
# clone the repository
git clone git@github.com:solidity-parser/parser.git solidity-parser
Install Node.js and npm, then clone the repository and install its dependencies:

# initialize the submodule
```bash
git clone https://github.com/solidity-parser/parser.git solidity-parser
cd solidity-parser
git submodule update --init
npm ci
```

## Updating the grammar
The generated TypeScript parser is checked in, so editing the wrapper and running the Node.js tests do not require ANTLR tooling. Grammar regeneration requires the additional setup below.

If you want to try changes made to the `antlr/Solidity.g4` file you need to generate the typescript files to reflect the changes.
## Updating the grammar

To accomplish that, we rely on [antlr4-tools](https://github.com/antlr/antlr4-tools) to generate the grammar.
We use [antlr4-tools](https://github.com/antlr/antlr4-tools) to run ANTLR. Install it with Python 3 and ensure its `antlr4` and `antlr4-parse` commands are on your `PATH`:

```bash
# it requires Python 3 but doesn't require Java.
# install antlr4-tools
pip install antlr4-tools
python -m pip install antlr4-tools
```

Once it is installed you just need to run the following `npm` script to generate the new grammar files.
The tool uses Java and can download a Java runtime and the ANTLR JAR on first use if needed. To select a generator version, set `ANTLR4_TOOLS_ANTLR_VERSION`; keep it compatible with the `antlr4` runtime version in [`package.json`](package.json).

After editing `antlr/Solidity.g4` or updating the submodule to a new grammar commit, run:

```bash
# generate the grammar Typescript files
npm run antlr
```

## Updating the parser
This generates TypeScript files under `src/antlr/` and runs the token-string generation script. Update `ASTBuilder.ts` and the AST types for any changed contexts or public nodes. Include the regenerated files and the updated submodule commit when submitting a grammar update to this repository.

Run `npm run build` to build the parser.
## Building and testing the parser

## Quick testing
For wrapper changes that do not need grammar regeneration, use:

```bash
npm run build:node
npm run build:browser
npm run generate-types
```

These commands build the CommonJS bundle at `dist/index.cjs.js`, the browser bundle at `dist/index.umd.js`, and the TypeScript declarations under `dist/`, respectively. `npm run build` runs all three after regenerating the grammar, so it also requires the ANTLR setup.

Right now the easier way to test something is to start the node REPL and import the project:
Run the Node.js tests with:

```bash
npm run test:node
```
npm run build
node
> parser = require('.')
> ast = parser.parse('contract Foo {}')
> console.log(ast.children[0].name)

Mocha loads the TypeScript tests in `test/` through `ts-node`; they exercise the source directly. Add regression tests there when changing parser behavior.

The browser tests in `browser-test/` use the built browser bundle:

```bash
npm run build:browser
npm run test:browser
```

## Understanding the generated parser
Karma launches the headless Chrome supplied by Puppeteer, so its browser download must be available. `npm test` runs both the Node.js and browser suites; build the browser bundle first. Run `npm run lint` to check ESLint and Prettier formatting.

The AST returned by the generated parser is very low level and tightly coupled to the grammar definition, that's why
using this wrapper is much easier. But if you want to contribute to this parser, you need to deal with this low level
representation. Let's see some examples of how to interpret it.
## Quick testing

### Example 1: PragmaDirective
Build the Node.js bundle, then start a REPL from the repository root:

At the moment of writing this, the function that handles pragma directives in `ASTBuilder` is this one:
```bash
npm run build:node
node
```

```javascript
PragmaDirective(ctx) {
return {
name: toText(ctx.pragmaName()),
value: toText(ctx.pragmaValue())
}
},
const parser = require('.')
const ast = parser.parse('contract Foo {}')
console.log(ast.children[0].name) // Foo
```

In this function, we are in the context of a pragma directive. In `Solidity.g4`, a pragma directive is defined like
this:
Rebuild the bundle after source edits before testing it with `require('.')` again. A running REPL also caches loaded modules; restart it to pick up the new bundle.

```
pragmaDirective : 'pragma' pragmaName pragmaValue ';' ;
```
## Understanding the generated parser

This means that the context will have a `pragmaName` and a `pragmaValue` function. Since we are only interested in their
verbatim content, we use the `toText` helper to obtain their values.
ANTLR produces a parse tree that follows the grammar closely. The public AST removes syntax details and represents Solidity constructs as typed nodes. To change that conversion, follow the corresponding context through the `visit...` methods in `ASTBuilder.ts`.

### Example 2: FunctionCall
### Example 1: PragmaDirective

Let's look now at how `FunctionCall` is handled:
The grammar defines a pragma directive as:

```javascript
FunctionCall(ctx) {
let args = []
const names = []

const ctxArgs = ctx.functionCallArguments()
if (ctxArgs.expressionList()) {
args = ctxArgs
.expressionList()
.expression()
.map(exprCtx => this.visit(exprCtx))
} else if (ctxArgs.nameValueList()) {
for (const nameValue of ctxArgs.nameValueList().nameValue()) {
args.push(this.visit(nameValue.expression()))
names.push(toText(nameValue.identifier()))
}
}

return {
expression: this.visit(ctx.expression()),
arguments: args,
names
}
},
```text
pragmaDirective : 'pragma' pragmaName pragmaValue ';' ;
```

This function is a little more involved. The relevant parts of the grammar are:
`visitPragmaDirective()` receives a `PragmaDirectiveContext`, with `pragmaName()` and `pragmaValue()` accessors. It uses `_toText()` to read their text. For a version pragma, it joins the version components with spaces to normalize an expression such as `>= 0.5.0 <0.7.0` to `>=0.5.0 <0.7.0`.

```
The method constructs a node with `type: 'PragmaDirective'`, `name`, and `value`, then returns it through `_addMeta()`.

### Example 2: FunctionCall

`visitFunctionCall()` receives a `FunctionCallContext` and reads its `functionCallArguments()`. The relevant grammar rules are:

```text
functionCall : expression '(' functionCallArguments ')' ;

functionCallArguments
Expand All @@ -135,28 +125,24 @@ nameValue
: identifier ':' expression ;
```

Let's focus on the return. Here we are returning our parser's representation of a `FunctionCall` node. We decide to
return the expression that represents the function called (and for this we recursively use `this.visit`), along with the
names and values of the arguments. `names` only makes sense when using the `f({a: 1})` syntax, otherwise it will be
empty. If the `f(1, 2)` syntax is used, then `ctxArgs.expressionList()` will be truthy, and then we visit each expression in
turn to generate the list of arguments. Otherwise, if `ctxArgs.nameValueList()` is truthy, we traverse the list of
`nameValue`s and use their `identifier`s as argument names and their `expression`s as values.
For a positional call such as `f(1, 2)`, `expressionList()` supplies an `expression_list()`. The builder visits each expression with `visitExpression()` to populate the `arguments` array.

## Using ANTLR for visualizing the AST
For a named call such as `f({a: 1})`, `nameValueList()` supplies a `nameValue_list()`. The builder collects each value in `arguments`, its name as text in `names`, and its identifier node in `identifiers`. The latter two arrays are empty for positional calls.

Sometimes is helpful to visualize the AST generated by the ANTLR parser. For example, let's say we are interested in
this contract:
The resulting `FunctionCall` node also contains the called `expression`, converted with `visitExpression()`, and is returned through `_addMeta()`.

```
## Visualizing the ANTLR parse tree

With `antlr4-tools` installed, use its grammar interpreter to inspect the parse tree directly. From the `antlr/` directory, create an `example.sol` file containing:

```solidity
contract Example is Base1, Base2(0) {}
```

Go to the `antlr` directory and run:
Then run:

```
./build.sh
echo 'contract Example is Base1, Base2(0) {}' > example.sol
java -classpath antlr4.jar:target/ org.antlr.v4.gui.TestRig Solidity sourceUnit -gui < example.sol
```bash
antlr4-parse Solidity.g4 sourceUnit -gui example.sol
```

And you'll get a window where you can see an inspect the generated tree.
This opens the parse tree in a Java GUI. Use `-tree` instead of `-gui` for text output. This is the grammar's parse tree, before the conversion performed by `ASTBuilder`.