galop is a parser generator for ANTLR-style .g4 grammars, written in
GALA.
It reads the grammar you already have and works out parsing decisions when it
generates the parser, not while the parser runs. The output is plain
recursive-descent code with a switch on the next tokens wherever a few tokens of
lookahead decide. Decisions that need unbounded lookahead are settled ahead of
time too: the parser guesses from small automata computed at generation time,
and finishing the parse proves the guess, so it picks exactly what ANTLR would
pick while its first pass predicts nothing at runtime. ANTLR's prediction
algorithm, compiled into the generated file, runs only to recover from a guess
that replaying cannot settle and to report a syntax error; grammars with
embedded actions do not guess and predict as before. It
needs no grammar file at runtime and no deserialization.
Every decision of the first pass is made at generation time: no warm-up. ANTLR's prediction runs only when replaying cannot settle a wrong guess, and to report a syntax error.
Status: early development. galop generates a Go lexer and parser for the GALA compiler's grammar that produce exactly ANTLR's tokens and trees on the whole GALA source corpus (722 of 722 files ANTLR accepts) and on code it was not tuned on, in two flavors: its own compact tree (the default, 11× to 290× faster than ANTLR) or ANTLR's tree types (3× to 54×). Other grammars work as far as their features are supported (see below); see the roadmap.
Time to lex and parse a whole corpus, against ANTLR driven the way the GALA
compiler drives it (SLL, with an LL retry on a syntax error). "Warm" is a repeat
pass in a long-running process; "fresh process" is the first pass after start-up,
which is what a compiler run pays. From bazel run -c opt //differential/cmd/bench,
Go 1.25 on Windows, one machine with 32 hardware threads:
| ANTLR 4.13.1 | galop, native (default) |
galop, antlr flavor |
|
|---|---|---|---|
| GALA compiler (723 files, 1.8 MB) | |||
| Warm, one goroutine | 466 ms | 44 ms (11×) | 163 ms (2.9×) |
| Warm, 32 goroutines | 325 ms | 7.7 ms (42×) | 45 ms (7.2×) |
| Fresh process, one goroutine | 1.48 s | 49 ms (30×) | 174 ms (8.5×) |
| Fresh process, 32 goroutines | 773 ms | 12 ms (66×) | 67 ms (12×) |
| Allocations per warm pass | 6.8 M, 526 MB | 23 k, 75 MB | 4.1 M, 325 MB |
| Code galop was not tuned on (gala_team, gala_tui, gala-server: 247 files, 3.5 MB) | |||
| Warm, one goroutine | 5.76 s | 59 ms (97×) | 227 ms (25×) |
| Warm, 32 goroutines | 3.26 s | 11 ms (286×) | 61 ms (54×) |
| Fresh process, one goroutine | 6.79 s | 59 ms (114×) | 239 ms (28×) |
| Fresh process, 32 goroutines | 2.89 s | 15 ms (187×) | 72 ms (40×) |
The native flavor is the default; the antlr flavor is for programs already
written against ANTLR's trees, and spends most of its time building ANTLR's
token and tree objects. Most of ANTLR's time on the second corpus goes to two
large files where its fast pass fails and it parses the whole file again in its
slow mode. galop's first pass predicts nothing at runtime and settles a wrong
guess by replaying, so a fresh process costs about what a warm pass does (see
design).
On more than 60,000 broken files from both corpora, galop's first syntax error
has the same message, line and column as ANTLR's when ANTLR parses that input in
a fresh process. (ANTLR's error text can depend on what the same process parsed
earlier, because its prediction cache is shared.) ANTLR's own ~set bug is the
one known exception (see design).
The native flavor also recovers from syntax errors as ANTLR does: on 19,000 broken GALA files from both corpora and the generated sentences (mutants, and edits like a file being typed: cut off, a bracket left open or removed, a line half written) and 18,000 mutants of six test grammars, it reports every error ANTLR reports, in order, and builds the error-recovered tree ANTLR builds, more than 10 times faster.
A parser keeps choosing which grammar alternative comes next. ANTLR makes those choices while it parses: it works them out from the grammar at runtime and learns as it goes, starting from scratch in every new process. That warm-up is most of the parse for a short-lived tool like a compiler.
galop makes those choices when it generates the parser, and picks the cheapest form for each:
flowchart LR
g4[".g4 grammar"] --> galop["galop"]
galop --> a["Settled by the next few tokens:<br/>a plain switch"]
galop --> b["Needs a little more lookahead:<br/>a small precomputed state machine"]
galop --> c["Needs unlimited lookahead:<br/>a guess from automata built ahead of time,<br/>proved by finishing the parse"]
In the GALA grammar, 86 of 107 choices land in the first group, so most of the
parser is the kind of code you would write by hand. The other 21 are guessed: a
loop of operators goes on, a long shared prefix is scanned once to see which
token follows it, and the rest read a small automaton over the next tokens, with
every bracketed group like ( … ) read as one step. A guess only rules
alternatives out, so when the parse reaches the end of the input it has built
ANTLR's own tree. A wrong guess makes the parse fail; the parser then replays it
with the next guesses, in ANTLR's order, and only if that cannot settle it does
it fall back to ANTLR's algorithm. On the GALA corpus and on code galop was not
tuned on, the first pass never predicts at runtime. The lexer is built entirely
ahead of time.
What you keep:
- Your grammar. galop reads the same
.g4file. No rewrite. - The same results. Tokens and trees match ANTLR's on the whole GALA corpus, in both flavors.
- Your code, if you want. The
antlrflavor builds ANTLR's own parse-tree types, so existing listeners and visitors keep working. The default,native, builds galop's own compact tree, with ANTLR's accessors (ctx.Expression(),ctx.AllStatement(),ctx.IDENTIFIER(),ctx.GetGuard()), typed type switches, and a generated listener (-listener, the default) and visitor (-visitor), so porting code written against ANTLR's trees is mostly renaming; it has no dependency.
What you get: a faster parser, especially when many goroutines parse at once (see the table above). galop's first user is the GALA compiler itself. It has been GALA's default parser since GALA 0.94.0, and since GALA 0.100.0 GALA parses with galop's native parser and builds no ANTLR tree for a clean file. On a real project (gala-tui), GALA 0.100.0 compared with 0.93.2, the last release before galop:
| GALA 0.93.2 | GALA 0.100.0 | change | |
|---|---|---|---|
gala build |
10.0 s | 6.03 s | −40% |
| GALA→Go transpile | 7.91 s | 3.65 s | −54% |
| parsing | 491 ms | 32 ms | 15× faster |
gala test |
15.4 s | 9.14 s | −41% |
peak memory (gala build) |
859 MB | 178 MB | −79% |
See the roadmap for how GALA moved over.
Build from source with the GALA CLI:
git clone https://github.com/martianoff/galop
cd galop
gala build -o galop ./cmd/galopTagged releases publish binaries for Linux, macOS and Windows.
galop is used like ANTLR's antlr4 tool: the same options, the same output
layout, the same message format.
galop -o gen -package parser Expr.g4 # generate Go code into gen/
galop -depend -o gen Expr.g4 # list the files it would write
galop -check -roundtrip grammars/*.g4 # validate only; also check the formatter keeps each grammar
galop -format Expr.g4 # print the grammar in canonical form
galop -report Expr.g4 # list the decisions static lookahead cannot settlegalop 0.0.0-dev, a parser generator for ANTLR 4 grammars
usage: galop [options] grammar.g4...
-o ___ specify output directory where all output is generated
-lib ___ specify location of grammars, tokens files
-atn generate rule augmented transition network diagrams
-message-format ___ specify output style for messages in antlr, gnu, vs2005
-listener generate parse tree listener (default)
-no-listener don't generate parse tree listener
-visitor generate parse tree visitor
-no-visitor don't generate parse tree visitor (default)
-package ___ specify a package/namespace for the generated code
-depend generate file dependencies
-D<option>=value set/override a grammar-level option
-Werror treat warnings as errors
-Xexact-output-dir all output goes into -o dir regardless of paths/package
galop options:
-check validate grammars without generating anything
-roundtrip with -check, also verify that formatting keeps each grammar
-format print each grammar in canonical form
-report print the decisions static lookahead cannot settle
-Xno-brackets predict over tokens only, never reading a bracketed group as one
-version print the galop version
-help print this help
-
Targets.
-Dlanguage=Go(the default) picks the Go target, and-Dflavor=native|antlrits output style,nativeby default (see design).-Doptions override the grammar's ownoptions {}; an unknown flavor is error 508. -
Python.
-Dlanguage=Python3writes lexers, in two flavors (see design).-Dflavor=antlr(the default) writes<grammar>GalopLexer.py, a lexer for ANTLR's Python runtime (4.13.1) that stands in for ANTLR's generated lexer in front of ANTLR's parser: same tokens, same errors, about a third of the time on the GALA corpus.-Dflavor=nativewrites<grammar>_lexer.py, a module with no dependency whoselex(src)returns the same tokens as arrays, in about a sixth of ANTLR's time, and for a combined grammar<grammar>_parser.py, whoseparse_<rule>(tokens)builds ANTLR's tree with no runtime, left-recursive rules and ANTLR's runtime prediction included, several times faster than ANTLR's Python parser. A syntax error raisesParseErrorwith the first error ANTLR reports: same line, column and message. It does not read grammars with actions or predicates, and does not recover from errors yet (see the roadmap). Python 3.10 or later. -
Output layout follows ANTLR: files go next to the grammar; with
-o dirthey go todirplus the grammar's relative directory (-o gen sub/T.g4writes togen/sub/), unless-Xexact-output-diris given. -
-atnwrites each rule's network as a Graphviz file,T.rule.dot(a combined grammar's lexer rules areTLexer.RULE.dot), as ANTLR does. -
Messages use ANTLR's numbers and wording where the problem is the same one ANTLR reports, and numbers from 500 up for galop's own (such as a construct it does not support yet).
-message-formatpicks ANTLR's layouts:error(56): Expr.g4:4:33: reference to undefined rule: factor # antlr (default) grammars/Expr.g4:4:33: error: reference to undefined rule: factor [error 56] # gnu grammars/Expr.g4(4,33) : error 56 : reference to undefined rule: factor # vs2005As in ANTLR, the column is the 0-based character position, and the
antlrlayout shows only the file name. The exit code is 1 when any error was reported;-Werrormakes warnings errors. -
-checkparses, checks and compiles each grammar: syntax errors, undefined or redefined rules, lexer rules that reference parser rules, parser rules that reference fragments, undecodable literals and sets, and (a warning, as in ANTLR) tokens used but never defined. -
-formatprints a canonical form. Comments are not part of the grammar model, so they are not printed.
Grammar imports (import A, B = C;) work as in ANTLR: an imported grammar is
looked for in the working directory, then next to the importing grammar, then
in the -lib directory, and its rules are merged in (see
DESIGN.md). A token vocabulary (tokenVocab)
is not supported yet and is reported as an error.
Grammar files are processed concurrently and independently: an error in one does not stop the others, and output is reported in command-line order.
The Go target writes one of two kinds of parser, picked with -Dflavor:
native (default) |
antlr |
|
|---|---|---|
| Files | expr_lexer.go, expr_parser.go |
expr_galop_lexer.go, expr_galop_parser.go |
| Dependencies | none | ANTLR's Go runtime, and ANTLR's generated code in the same package |
| Tokens | a slice of 20-byte tokens; comments and other off-channel tokens in a side slice | antlr.CommonTokens from an antlr.TokenStream |
| Tree | galop's compact tree, with typed accessors per rule | ANTLR's own context types |
| For | new code, and speed | a drop-in for ANTLR's parser in programs written against its trees |
With the antlr flavor, a program that parses with ANTLR changes only its
constructors. NewExprGalopParser embeds ANTLR's ExprParser, so error
listeners and the rest of ANTLR's parser API work as before; its rule methods
return ANTLR's contexts and, on input with syntax errors, report every error
ANTLR reports to the error listeners and return the tree ANTLR's error
recovery builds:
lexer := parser.NewExprGalopLexer(antlr.NewInputStream(src)) // was NewExprLexer
p := parser.NewExprGalopParser(antlr.NewCommonTokenStream(lexer, 0)) // was NewExprParser
p.RemoveErrorListeners()
p.AddErrorListener(myListener) // called as ANTLR calls it, GetExpectedTokens() included
prog := p.Prog() // ANTLR's IProgContext, error-recovered on bad inputp.ParseProg() instead returns the first syntax error and no tree, and calls
no listener. The antlr flavor parses with galop's decisions and never with
ANTLR's: an error strategy, parse listeners or a prediction mode set on the
embedded parser are not used, and ATN state numbers (a listener's GetState(),
a context's invoking state) are galop's, which differ from ANTLR's.
With the native flavor, for Expr.g4 in package parser:
toks := parser.ExprLex(src) // tokens; toks.Hidden holds the comments
prog, err := parser.ParseProg(toks) // a *parser.ExprSyntaxError with line and column
for _, st := range prog.AllStat() { // ANTLR's accessors, on typed handles
if a, ok := st.AsAssign(); ok { // a labeled alternative
fmt.Println(a.ID().GetText(), a.Start().Line, a.Expr().GetText())
}
}Both flavors decide exactly as ANTLR does and give the same tokens and trees.
On input with a syntax error, both report the same first error as ANTLR
parsing that input in a fresh process, with the same message, line and column.
(ANTLR's error text can depend on what the same process parsed earlier, because
its prediction cache is shared.) The native flavor's Parse<Rule> and the
antlr flavor's Parse<Rule> method stop at that first error; the antlr
flavor's rule methods recover as ANTLR does (above).
For an editor, the native flavor's Parse<Rule>WithRecovery (and
ExprParseWithRecovery(toks, rule)) recovers as ANTLR's default error strategy
does: it returns every syntax error ANTLR reports, in order, and the
error-recovered tree, with ANTLR's error tokens and the tokens its recovery made
up (<missing ';'>). Each error also names its token and the node of the rule
being parsed when it was reported, which code that explains an error reads, the
tokens the parser expected there (Expected: what ANTLR's GetExpectedTokens()
gives an error listener, for messages such as "expecting one of ..."), and
how far ANTLR's parse had read (Read): with the lexer's ErrorAt, that places
token recognition errors among the syntax errors where ANTLR reports them. On
input without errors it is Parse<Rule> (see
design):
prog, errs := parser.ParseProgWithRecovery(toks) // errs: []parser.ExprParseError
for _, e := range errs {
fmt.Println(e.Line, e.Column, e.Msg)
}The native flavor also generates a typed view, a listener (by default) and a
visitor (with -visitor), so code written against ANTLR's trees can keep its
shape:
switch p := n.Parent().Typed().(type) { // the node as its rule's handle
case *parser.AssignNode:
...
}
parser.ExprWalk(prog.Ref(), myListener) // EnterAssign/ExitAssign, VisitTerminal, ...
v := parser.ExprAccept[int](expr.Ref(), myVisitor) // VisitX per rule and labeled alternativeTo parse text cut from a larger file, such as an expression inside a string,
start the lexer at the text's position so tokens and errors report positions in
the enclosing file. The native flavor has ExprLexAt(src, line, column). The
antlr flavor's lexer counts from its Interpreter's Line and
CharPositionInLine, as ANTLR's lexer does. An entry rule that is not anchored
to EOF stops after its match: Tree().Next (native) or the stream's next token
(antlr flavor) is where it stopped, as in ANTLR.
To move a program from ANTLR's trees to the native tree step by step, generate
the antlr flavor with -DnativePackage=<import path of the native package>. It
then also writes expr_galop_native.go, whose ExprToNative(root, stream, src)
converts any tree of ANTLR's context types to the native tree;
ExprToNativeContexts also returns the ANTLR context of each native node, for
code that holds both trees while it moves:
flowchart LR
A[ANTLR parser<br/>error-recovered tree] --> C[ExprToNative]
B[galop antlr flavor] --> C
C --> T[native tree]
N[galop native flavor] --> T
On input native parsing accepts, the converted tree is the one native parsing
builds. On input with syntax errors it is ANTLR's error-recovered tree, with
error tokens, which an editor needs while a file is being typed (see
design); the native
flavor's Parse<Rule>WithRecovery builds the same tree without ANTLR.
rules_gala provides
galop_parser, which runs galop on a .g4 file and yields the generated Go
sources for a go_library.
grammar,lexer grammar,parser grammarheadersoptions { ... },tokens { ... },channels { ... },@name { ... }and@scope::name { ... }actionsimport A, B = C;: imported grammars, merged as ANTLR merges them- parser and lexer rules,
fragmentrules, alternatives with# Label - rule and token references, quoted literals,
'a'..'z'ranges,[...]sets,.,~ ?*+and their non-greedy forms??*?+?- element labels
x=eandxs+=e - embedded actions
{...}and predicates{...}? - lexer commands:
-> skip,-> channel(HIDDEN),-> pushMode(X), ... EOFin lexer rules, matching the end of the input (LINE : '//' ~[\n]* ('\n' | EOF) ;)
Not supported yet, and reported as errors rather than ignored: rule arguments,
returns/locals, rule-level options and actions, element options other than
<assoc=left|right> on an alternative, lexer modes, the tokenVocab and
caseInsensitive options, and in the Go target, semantic predicates.
Directly left-recursive rules (e : e '+' e | INT) are rewritten into a
precedence loop as ANTLR rewrites them, which -report shows, and both flavors
generate them, error recovery and the converter included (see
design). They are checked against ANTLR on
a grammar with each shape of alternative and on Milvus's, CEL's, SigNoz's and
Grule's grammars. Mutually left-recursive rules are an error, as in
ANTLR (error 119), and so is a left-recursive rule with no other alternative
(147); -check does not report ANTLR's errors for left recursion its rewrite
cannot handle (148, 169).
See AGENTS.md for the project rules and CONTRIBUTING.md for the workflow.
gala test # unit tests
gala build -o galop ./cmd/galop # the CLI
./galop -check -roundtrip testdata/grammars/*.g4 # the grammar corpus
bazel test //... # the same suite under Bazel
bazel run //differential/cmd/perfgate # the performance gate (docs/FUZZ_AND_PERF.md)Apache 2.0, with an exception for the code galop generates: the lexers,
parsers, listeners, visitors and converters it writes from your grammar are yours to
use under any terms, with or without attribution (see the end of LICENSE).
The corpus grammars in testdata/grammars are other projects' files under their own
licenses; see their notices.