This is a Go module to parse Solidity, based on Federico 's ANTLR grammar for the language.
package main
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/duaraghav8/solidityparser"
)
var code = `
contract Foo {
function bar(uint x) {}
}
contract Bar {
constructor(){}
}
`
// EverythingListener listens for all rules, i.e., it visits
// all AST nodes.
type EverythingListener struct {
*solidityparser.BaseSolidityListener
}
func NewEverythingListener() *EverythingListener {
return new(EverythingListener)
}
func (l *EverythingListener) EnterEveryRule(ctx antlr.ParserRuleContext) {
fmt.Println("Entered a rule")
fmt.Println(ctx.GetRuleIndex())
fmt.Printf("Text: %s\nStart line: %d\n", ctx.GetText(), ctx.GetStart().GetLine())
fmt.Println("--------------")
}
func main() {
code := antlr.NewInputStream(code)
lexer := solidityparser.NewSolidityLexer(code)
stream := antlr.NewCommonTokenStream(lexer, 0)
parser := solidityparser.NewSolidityParser(stream)
parser.AddErrorListener(antlr.NewDiagnosticErrorListener(true))
parser.BuildParseTrees = true
tree := parser.SourceUnit()
antlr.ParseTreeWalkerDefault.Walk(NewEverythingListener(), tree)
}
Install the ANTLR4 tool and the Go runtime as described here & here.
To generate this Parser:
- Update the
solidity-antlr4
submodule to the appropriate commit. - Run
scripts/generate-solidity-parser.sh
in the root directory of this repository. - Run
go mod tidy && go mod vendor
- Commit and push.