Larkita
Larkita is a light-weight version of the Python parser generator Lark. It differs from Lark in three ways:
- It generates a canonical LR(1) parser (not Earley or CYK). On request, it merges states with the same core; for an LALR(1) grammar and the basic lexer, the result is the LALR(1) parser.
- The parser returns the abstract syntax tree as a nested tuple, not as a tree of objects. How the tuple is built follows from the grammar itself; you never have to write tree-building code.
- Every time a parser is generated, Larkita writes an output file with all the LR(1) states, every item annotated with its lookahead tokens. This makes conflicts easy to debug.
Grammars are written in Lark's EBNF notation, with a few additions for building the abstract syntax tree. Unlike in Lark, every rule ends with a semicolon. The precedence and associativity of operators can be declared as in bison.
Installation
Larkita needs Python 3.12 or newer and has no dependencies. Install it with
pip install larkita
The source code is on GitHub at https://github.com/karlstroetmann/Larkita. To install the latest version from there, run
pip install git+https://github.com/karlstroetmann/Larkita.git
If the optional package interegular is installed, Larkita checks whether the
regular expressions of different terminals can match the same text. It reports
such collisions via larkita.logger, which is silent by default; call
larkita.logger.setLevel(logging.WARNING) to see them.
Quick start
from larkita import Larkita
grammar = r'''
stmnt: IDENTIFIER ":=" expr ";"
| expr ";"
;
expr: expr "+" product
| expr "-" product
| product
;
product: product "*" factor
| product "/" factor
| factor
;
factor: "(" expr ")" %ignore "(", ")"
| NUMBER
| IDENTIFIER
;
%import common.CNAME -> IDENTIFIER;
%import common.NUMBER;
%import common.WS;
%ignore WS;
'''
parser = Larkita(grammar)
print(parser.parse('x := (a + 3) * b;'))
prints
((':=', ';'), ('IDENTIFIER', 'x'), ('*', ('+', ('IDENTIFIER', 'a'), ('NUMBER', '3')), ('IDENTIFIER', 'b')))
and writes the description of the automaton to grammar.out. To read the
grammar from a file, use
parser = Larkita.open('new-syntax/expr.g') # writes new-syntax/expr.out
The start symbol is the first rule of the grammar (here stmnt).
Tutorial
The tutorial
tutorial/larkita-tutorial.pdf
explains how to write grammars for Larkita, how the abstract syntax trees are
built, how to process them with match, and how to deal with syntax errors and
conflicts. Its grammars and programs are in the directory tutorial/examples of
the repository; running make in the directory tutorial runs them and rebuilds
the PDF.
How the abstract syntax tree is built
Consider an alternative a: X1 X2 ... Xn. The literal tokens written in double
quotes form the head of the tuple; all other symbols become its children:
(head, ast(child_1), ..., ast(child_k))
| Grammar | Abstract syntax tree |
|---|---|
expr: expr "+" product; |
("+", ast(expr), ast(product)) |
stmnt: expr ";"; |
(";", ast(expr)) |
stmnt: IDENTIFIER ":=" expr ";"; |
((":=", ";"), ("IDENTIFIER", name), ast(expr)) |
atom: IDENTIFIER; |
("IDENTIFIER", name) |
expr: product; |
ast(product) |
factor: "(" expr ")" %ignore "(", ")"; |
ast(expr) |
atom: IDENTIFIER "(" args ")" -> "call"; |
("call", ("IDENTIFIER", name), ast(args)) |
args: expr ("," expr)*; |
(",", ast(expr_1), ..., ast(expr_n)) |
set: "{" expr ("," expr)* "}"; |
(("{", ",", "}"), ast(expr_1), ..., ast(expr_n)) |
program: statement*; |
("program", ast(statement_1), ..., ast(statement_n)) |
stmnt: "return" [expr] ";"; |
(("return", ";"),) or (("return", ";"), ast(expr)) |
expr: expr ("+" | "-") product; |
("+", ast(expr), ast(product)) or ("-", ast(expr), ast(product)) |
expr: product (("+" | "-") product)*; |
("expr", ast(product_1), "-", ast(product_2), ...) |
In detail:
- Head. The head consists of all literals of the alternative that are not
ignored, in the order in which they are written, one entry per occurrence. If
there is exactly one literal, the head is that string; otherwise it is a tuple
of strings. The head is fixed by the grammar, not by the input:
f(a)with the rule forargsabove yields(",", ast(a)), even though no comma was read. Literals inside repetitions, optional parts and groups belong to the head, too, except for the literals of inner alternatives inside repetitions and optional parts. - Inner alternatives like
("+" | "-")abbreviate several alternatives:expr: expr ("+" | "-") product;meansexpr: expr "+" product | expr "-" product;, so the literal that has been read is the head. Inside a repetition or an optional part, and in an alternative with an alias, the head cannot depend on the input. There, the literal that has been read becomes a child of the tuple, as a plain string:1 - 2 + 3yields("expr", ast(1), "-", ast(2), "+", ast(3))with the ruleexpr: product (("+" | "-") product)*;. - Named tokens become
(NAME, text), e.g.("NUMBER", "42"). The text is not converted. Inline regular expressions/.../are treated like named tokens. - Pass-through. If an alternative has no head and consists of exactly one
symbol (with no
*,+,?,[...]or|), it returns the abstract syntax tree of that symbol unchanged. Inner alternatives are expanded first, soa: (b | "-" b);passes the abstract syntax tree ofbthrough. - The name of the variable as head. If an alternative has no head and is not a
pass-through, the name of the variable that is defined by the rule is used as head,
e.g.
("program", ...). An empty alternative of the rule forayields("a",). - Repetitions and groups are flattened into the tuple of the alternative.
- Missing optional parts are left out; there is no
Noneplaceholder. - Aliases replace the whole head:
-> "call"and-> callare equivalent.
Ignoring literals
%ignore has three forms:
%ignore WS; // the lexer skips the terminal WS
%ignore WS, COMMENT; // the lexer skips the terminals WS and COMMENT
factor: "(" expr ")" %ignore "(", ")";
// "(" and ")" are left out of the head of this alternative
%ignore: "(", ")", "{", "}"; // these literals are left out of the heads of all rules
With %ignore: "(", ")";, the rule
statement: "while" "(" expr ")" statement; yields
("while", ast(expr), ast(statement)).
Grammar syntax
Larkita reads Lark grammars, except that every statement ends with a semicolon:
-
Every rule, every definition of a terminal, and every statement that starts with
%(like%importand%ignore) ends with;. Line breaks are white space, so a rule may span several lines and several rules may share a line. A rule with several alternatives is usually written with one alternative per line and the semicolon on a line of its own:expr: expr "+" product | expr "-" product | product ; -
Syntactical variables have lowercase names, terminals have uppercase names.
-
|separates alternatives,( ... )groups,[ ... ]and?mark optional parts,*and+repeat, and~ nor~ n..mrepeat a fixed number of times. -
String literals are written as
"..."(appendifor case-insensitive matching), regular expressions as/.../flags. -
Terminals are defined with
NAME: ...;NAME.p: ...gives a terminal the priorityp, andrule.p: ...gives a rule the priorityp(used to resolve reduce/reduce conflicts). -
%import common.NUMBERimports terminals from Lark's standard library (larkita/grammars/common.lark), and%import .file.ruleimports from a grammar file next to the current one.-> NAMErenames an import. Several imports are separated by commas:%import common.CNAME -> ID, common.INT, common.WS;. -
%left,%right,%nonassoc,%precedenceand%precdeclare the precedence of operators as in bison (see Operator precedence). -
%declare,%extendand%overridework as in Lark. -
//starts a comment.
Not supported (compared with Lark): statements that end at a line break, the
rule modifiers ?rule and !rule, templates, post-lexers (such as Lark's
Indenter), lexer callbacks, and transformers. Rules and terminals whose names start with _ are not inlined
or filtered. Instead of a post-lexer, a scanner of your own can be used (see
Using another scanner).
The output file
If the grammar is read from a file, the output file has the same name with the
extension .out (expr.g produces expr.out). Otherwise it is grammar.out in
the current directory. The parameter out_file sets another path, and
out_file=False writes no output file.
The file contains
- the rules after the EBNF operators have been expanded, each followed by the
abstract syntax tree that a reduction produces, e.g.
(3) expr → expr "+" product ⇒ ("+", ast(expr), ast(product)); - the precedence declarations and the precedences of the rules, if the grammar declares any;
- a list of all conflicts and how they were resolved;
- all states. Each state lists its items with their lookahead tokens (closure
items are marked with
+), followed by its actions and gotos:
State 2
(1) stmnt → IDENTIFIER • ":=" expr ";": $END
(11) factor → IDENTIFIER •: "*", "+", "-", "/", ";"
":=" shift and go to state 8
"*" reduce using rule (11) factor → IDENTIFIER
"+" reduce using rule (11) factor → IDENTIFIER
"-" reduce using rule (11) factor → IDENTIFIER
"/" reduce using rule (11) factor → IDENTIFIER
";" reduce using rule (11) factor → IDENTIFIER
Conflicts
- Shift/reduce conflicts are resolved by precedence declarations, as in bison
(see below). All other shift/reduce conflicts are resolved in favour of shift
(so the dangling
elsebelongs to the innermostif), and Larkita issues aConflictWarning. - Reduce/reduce conflicts are resolved in favour of the rule with the highest
priority. If no rule has a higher priority than the others,
Larkitaraises aGrammarError; the output file is written anyway.
Operator precedence
Ambiguous grammars for expressions are made unambiguous by declaring the precedence and associativity of the operators, as in bison:
%nonassoc "<" "==";
%left "+" "-";
%left "*" "/";
%precedence UMINUS;
%right "^";
expr: expr ("<" | "==" | "+" | "-" | "*" | "/" | "^") expr
| "-" expr %prec UMINUS -> "neg"
| "(" expr ")" %ignore "(", ")"
| NUMBER
;
- Every declaration lists literals and terminals (commas between them are optional). Its symbols have the same precedence, which is higher than the precedence of the symbols declared above.
- A rule has the precedence of its last terminal.
%prec NAMEafter an alternative (in front of an alias or%ignore) gives it the precedence ofNAMEinstead;NAMEmay be a name likeUMINUSthat is not a terminal. - If the parser could shift a token or reduce with a rule, and both have a
precedence, the higher precedence wins. If they have the same precedence,
%leftreduces,%rightshifts, and%nonassocmakes the token a syntax error, so1 < 2 < 3is rejected.%precedencedeclares no associativity, so such a conflict is not resolved by the precedence. - Conflicts that are resolved by precedence cause no warning. The output file
lists them with the reason, written as in bison, e.g.
resolved as reduce (%left "+")orresolved as shift ("+" < "*"). - Precedence declarations in imported grammars are ignored.
Merging states
Canonical LR(1) automata can be large. With merge_states=True, Larkita merges
states with the same core (i.e. the same items without lookaheads), as long as
this is safe:
- Merging must not introduce a new conflict, neither in the merged states nor in their successors.
- With the contextual lexer, merging must not change how the input is split into
tokens. For example, if a keyword like
"else"is only acceptable in one of two states, merging them could make the lexer readelseas a keyword where the other state reads an identifier.
The resulting parser accepts the same strings, builds the same abstract syntax
trees, and detects syntax errors at the same tokens as the canonical parser,
although it may perform a few more reductions before it reports an error. With
lexer='basic', the lexer does not depend on the state of the parser, so for an
LALR(1) grammar the result is the LALR(1) automaton. The output file then
describes the merged states and explains why the remaining states with the same
core have been kept apart.
API
Larkita(grammar, *, start=None, lexer='contextual', import_paths=(),
source_path=None, out_file=None, regex=False, g_regex_flags=0,
merge_states=False)
grammar: the grammar as a string or an open file.start: the start symbol; defaults to the first rule.lexer:'contextual'(only matches the terminals that the parser can accept in its current state) or'basic'.import_paths: additional directories to search for imported grammars.source_path: the file name of the grammar, used for relative imports and to name the output file.out_file: the path of the output file, orFalseif no output file is to be written.regex: use theregexmodule instead ofre.g_regex_flags: flags applied to all terminals.merge_states: merge states with the same core, as long as this is safe (see above).
Larkita.open(filename, rel_to=None, **options) reads the grammar from a file.
parser.parse(text) returns the abstract syntax tree. It raises
UnexpectedCharacters if the lexer cannot match the input, and UnexpectedToken
if the parser receives a token it cannot accept (at the end of the input, the
token has the type $END). All exceptions derive from LarkitaError.
parser.lex(text) runs only the scanner and returns an iterator over the tokens.
Every token t provides t.type, t.value, t.line, and t.column; ignored
tokens are skipped.
parser.parse_tokens(tokens) parses tokens that come from another scanner and
returns the abstract syntax tree (see below). It raises UnexpectedToken like
parse.
parser.literals maps every string literal of the grammar to the name of its
terminal, e.g. {"while": "WHILE", ":=": "__ANON_0"}.
After construction, parser.conflicts, parser.rules, parser.terminals,
parser.parse_table and parser.out_file describe the generated parser
(parser.out_file is None if no output file has been written).
Using another scanner
If the tokens of a language cannot be described by regular expressions (e.g. if
the indentation of a line matters), they can be produced by a scanner of your own
and parsed with parse_tokens. The scanner creates every token as
Token(type, value, line=..., column=...), where type is the name of a terminal;
for the string literals of the grammar, parser.literals gives these names.
Terminals that the grammar does not define are declared with %declare. The value
of a token can be any object, and the abstract syntax tree contains it unchanged:
import re
from larkita import Larkita, Token
parser = Larkita('''
expr: expr "+" product | product;
product: product "*" factor | factor;
factor: "(" expr ")" %ignore "(", ")"
| NUMBER
;
%declare NUMBER;
''', out_file=False)
def scan(text):
for m in re.finditer(r'(\d+)|\S', text):
if m.group(1):
kind, value = 'NUMBER', int(m.group(1)) # numbers become integers
else:
value = m.group()
kind = parser.literals.get(value, value)
yield Token(kind, value, line=1, column=m.start() + 1)
print(parser.parse_tokens(scan('2 * (3 + 4)')))
prints ('*', ('NUMBER', 2), ('+', ('NUMBER', 3), ('NUMBER', 4))). A scanner can
also change the tokens that parser.lex(text) returns, e.g. insert tokens that mark
where the indentation of a line increases or decreases.
Highlighting grammars
Larkita registers two lexers for Pygments: larkita for
grammars and python-larkita for Python code whose raw strings r"""...""" are
grammars. They need Pygments, e.g. pip install larkita[pygments]:
pygmentize -l larkita grammar.g
In Jupyter, IPython.display.Code(text, language='larkita') displays a grammar
with syntax highlighting.
Examples and tests
The directory new-syntax of the repository contains two example grammars:
expr.g (arithmetic expressions) and interpreter.g (a small imperative language
with sets).
In a clone of the repository, run the tests with
python3 -m tests
License
MIT. Larkita is derived from Lark by
Erez Shinan; see LICENSE.
Metadata
Release files for larkita 0.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| larkita-0.8.0.tar.gz | 76.9 kB | With provenance | Details for larkita-0.8.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| larkita-0.8.0-py3-none-any.whl | Python 3 | none | any | Details for larkita-0.8.0-py3-none-any.whl |
Total release size: 144.6 kB
Release files / larkita-0.8.0.tar.gz
| Download URL | larkita-0.8.0.tar.gz |
|---|---|
| Size | 76.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
79e4b51b6360fe94b615e24bc6223a429999e815e20c580e09014d1ef830b696
|
|
BLAKE2b-256 checksum How to use checksums |
da53103206d73276527542337b15087941611539c5b7d7ffbd16a739a749e68a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / larkita-0.8.0-py3-none-any.whl
| Download URL | larkita-0.8.0-py3-none-any.whl |
|---|---|
| Size | 67.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c49292e4e0e2e39f25b9ee0b4c0b26eb21ad5eb2eecdff10a1036d94847f6cae
|
|
BLAKE2b-256 checksum How to use checksums |
d804bf7f27f6b49b04bc8696259565f2bb471f2c05fcab305817cd368cb5864f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for larkita 0.8.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for larkita-0.8.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.