Skip to content
28 changes: 21 additions & 7 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,17 @@ uv run python benchmarks/bench_parse.py --digest --unordered
uv run --no-project --with sphinx python -m sphinx -W -b html doc /tmp/reynir-doc
```

Note: after changing the C++ sources (`eparser.cpp`, `ereducer.cpp`,
`eparser.h`) or `eparser_build.py`, force a rebuild of the `_eparser` CFFI
Note: after changing the C++ sources (`src/reynir/e*.cpp` and `e*.h`) or
`eparser_build.py`, force a rebuild of the `_eparser` CFFI
extension with
`uv sync --reinstall-package reynir` (the extension is compiled at install
time; see `setup.py`, which exists only for the `cffi_modules` hook — all
other metadata is in `pyproject.toml`). Extra compiler flags for
such a build (sanitizers, `-DEPARSER_ASSERT -UNDEBUG` to enable the
assertions of the core) go in `CXXFLAGS`, not `CFLAGS`, and need
`--no-cache`.
assertions of the core, `-DDEBUG -UNDEBUG` for a trace of each parse) go
in `CXXFLAGS`, not `CFLAGS`, and need `--no-cache`. `CXXFLAGS` replaces
the flags of the Python build, which has `-O3`: for a build that is to
be timed, pass those along (`sysconfig.get_config_var("CFLAGS")`).

Environment variables that switch the C++ fast paths off or check them
against the Python implementations (all results must be the same either
Expand Down Expand Up @@ -116,6 +118,18 @@ The parsing pipeline, orchestrated by the `Greynir` class in `reynir.py`
singular, nominative, feminine); terminal matching logic lives here.
`baseparser.py` holds a pure-Python reference parser. `incparser.py`
handles incremental parsing of token streams by paragraph/sentence.
The C++ module is in `src/reynir/e*.cpp` and `e*.h`, a file for each
concern (the top of `eparser.cpp` has the list): `eparser.cpp` is the
algorithm itself (`ParseRun` is one parse, with the predictor, the
completer and the scanner as methods; `Parser` is what parses share),
`egrammar` the grammar and its lookahead tables, `eforest` the parse
forest, `ematcher` native matching (`Matcher`), `ereducer` the
reducer, `ememory` the pools, and `eparser_api.cpp` every function
that Python calls, which the declarations in `eparser_build.py`
mirror. The build has no link-time optimization, so a call into
another file is never inlined: what is called for every state belongs
in `eparser.cpp` or in a header. A new `.cpp` file goes in the
`sources` list of `eparser_build.py`.
The core processes the states of an Earley column in the order in
which they are added (`Column::nextState()`), which determines the
order of families in the forest and thereby the outcome of those exact
Expand All @@ -130,15 +144,15 @@ The parsing pipeline, orchestrated by the `Greynir` class in `reynir.py`
pools that are kept between parses (`BlockPool`; section 13 of the
performance document): a block is never initialized, and code on the
hot path that obtains one must do so in a function of its own
(`addChunk()`). The buffers of the tokens that have been seen before
(`StateStore::addChunk()`). The buffers of the tokens that have been seen before
(matching cache, matching data) are handed to the core when it is called
(`ParseJob.known_buffers()`, `earleyParseEx()`); it asks for the
others through callbacks (`alloc_func()`, `meanings_func()`). See
`doc/earley-core-performance.md`; `test/test_earley_core.py` tests the
core in isolation with synthetic grammars.
The core has a lookahead filter: a state is only created if what
follows its dot can begin with the current token or derive nothing
(`Parser::viable()`; the filters and the classes of nonterminals that
(`ParseRun::viable()`; the filters and the classes of nonterminals that
it uses are calculated in `Grammar::analyze()` when a grammar is
loaded). It must not change the content of the forest, nor the token
index that a failed parse reports. Token/terminal matches and
Expand All @@ -151,7 +165,7 @@ The parsing pipeline, orchestrated by the `Greynir` class in `reynir.py`
native matchers replicate the Python ones in `binparser.py`
(`WordMatchers`, `BIN_Token.verb_matches()`): a change to the matching
logic there must be made in `evalMatch()`/`verbMatchMeaning()` in
`eparser.cpp`, or in the tables, as well.** `GREYNIR_MATCHING_PARITY=1`
`ematcher.cpp`, or in the tables, as well.** `GREYNIR_MATCHING_PARITY=1`
compares the two for every match that the parser evaluates, and
`test/test_native_matching.py` for all terminals. Native matching also
applies to parsers whose tokens are of a class derived from `BIN_Token`
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/bench_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

This program measures the parsing speed of GreynirEngine on a corpus
of sentences, and how the time divides between the C++ Earley-Scott
parser core (the earleyParseEx() function in eparser.cpp) and the rest
parser core (the earleyParseEx() function of the C++ module) and the rest
of the pipeline (tokenization, token/terminal matching callbacks,
conversion of the parse forest to Python objects, and reduction).

Expand All @@ -56,7 +56,7 @@
--digest before and after the change and compare the two outputs:

uv run python benchmarks/bench_parse.py --digest > before.txt
(change eparser.cpp; then: uv sync --reinstall-package reynir)
(change the C++ sources; then: uv sync --reinstall-package reynir)
uv run python benchmarks/bench_parse.py --digest > after.txt
diff before.txt after.txt

Expand Down
93 changes: 92 additions & 1 deletion doc/earley-core-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

Status: IMPLEMENTED (stages 1 to 5, and section 12) — 2026-11-11;
section 8: findings only (its lookahead filter is implemented in stage 3);
section 13: IMPLEMENTED (the pool of blocks) — 2026-12-01, otherwise findings
section 13: IMPLEMENTED (the pool of blocks) — 2026-12-01, otherwise findings;
section 14: IMPLEMENTED — 2026-12-01

## 0. Summary

Expand All @@ -27,6 +28,8 @@ the core spends its time after all this, and a small change that follows
from it. Section 13 is about the memory that a parse uses: the same
program could parse up to a tenth slower in one run than in the next,
depending on where its memory happened to lie, and no longer does.
Section 14 is about the division of the C++ module into files, and says
where the functions that the earlier sections name are now.

Stages 1 and 2 taken together, on the machine where stage 2 was done:

Expand Down Expand Up @@ -1464,3 +1467,91 @@ slower. Pass the flags of `sysconfig.get_config_var("CFLAGS")` along.
* **The first phase** (`reduceStart()`, 5% of a warm parse) is two
functions, `buildFamilies()` and `walk()`, with hardly any allocation;
nothing stands out.

## 14. The module in files

Status: IMPLEMENTED — 2026-12-01

### Why, and the one constraint

`eparser.cpp` had grown to 3,033 lines with six concerns in it, of which
the Earley algorithm was one, and `eparser.h` to 1,084. The aim was a
file for each concern, each with a small interface, and clarity was put
before the last percent of speed.

One thing limits how the code can be divided. The extension is built
without link-time optimization, so a call from one `.cpp` file into
another is never inlined, and section 13 shows what a single inlining
decision on the path of every state can cost (4% of the core). So the
classes that call each other for every state stay together in one file,
and the few functions of other files that are called that often are
defined in headers (`Grammar::operator[]`, `Node::addFamily()`,
`Forest::alloc()`).

### The files

| File | Lines | What is in it |
|---|---|---|
| `eparser.cpp` | 1,689 | The algorithm: `State`, `StateStore`, `Column`, `StateSet`, `HNode`, `NodeDict`, `ParseRun`, `Parser` |
| `eparser.h` | 154 | The `Parser` class; includes the other headers |
| `egrammar.h`, `egrammar.cpp` | 890 | `Nonterminal`, `Production`, `Grammar`: reading the binary file, the analysis for the lookahead filter |
| `eforest.h`, `eforest.cpp` | 436 | `Label`, `Node`, `Forest` |
| `ematcher.h`, `ematcher.cpp` | 771 | `Matcher`, and the structures that `binparser.py` fills in |
| `ereducer.h`, `ereducer.cpp` | 1,640 | The reducer, its tables (`ReducerSetup`) and what it returns |
| `ememory.h`, `ememory.cpp` | 382 | `BlockPool`, `Pool`, `AllocCounter` |
| `ebase.h` | 76 | Types and macros |
| `eparser_api.cpp` | 327 | Every function that Python calls |

Three things changed in substance, the rest is code moved as it was:

* **Native matching is a class.** The table of terminal specs, the
masks, the prefilling patterns and the parity counter were members of
`Parser`. They are now a `Matcher`, of which three things are asked:
`setTable()`, `match()` and `prefill()`. The parser core no longer
knows what a `TerminalSpec` or a `MeaningRec` is.
* **A parse is an object.** `Parser::parse()` was one function of 350
lines. `ParseRun` is one parse: its members are what the local
variables of that function were, and its methods are the steps of the
algorithm, `start()`, `predict()`, `complete()` and `scan()`. `Parser`
is left with what parses share. The working memory of a parse is
released by destructors, also when memory runs out in the middle of
it, where it used to be left behind.
* **Each module prints its own lines of the allocation report.** There
was an `AllocReporter` class that every other class declared a friend.

Where the functions that sections 1 to 13 name are now:

| Then | Now |
|---|---|
| `Parser::parse()`, the main loop | `ParseRun::run()`, with `predict()`, `complete()` and `scan()` |
| `Parser::viable()`, `canAdvance()`, `makeNode()`, `push()`, `pushNew()` | The same names in `ParseRun` |
| `operator new(size_t, StateChunk*&)`, `addChunk()`, `freeStates()` | `StateStore::alloc()`, `StateStore::addChunk()` and the destructor of `StateStore` |
| The lists `pQ` and `pQ0` of states with a matching terminal at the dot | `Column::addToScan()`, `Column::takeScan()` |
| `Parser::matchNatively()`, `Parser::prefillCache()`, `Parser::setMatchingTable()` | `Matcher::match()`, `Matcher::prefill()`, `Matcher::setTable()`, in `ematcher.cpp` |
| `evalMatch()`, `verbMatchMeaning()` | The same names, in `ematcher.cpp` |
| `Parser::setReducerTables()` | `ReducerSetup::set()`, in `ereducer.cpp` |
| `Grammar::analyze()`, `Grammar::readBinary()` | The same names, in `egrammar.cpp` |
| `earleyParseEx()` and the other functions of the interface | The same names, in `eparser_api.cpp` |

### Results

Measured as section 13 describes (four or five processes of each, the same
Python, one core), on the 1,000 news sentences:

| | First pass | Core | Warm pass | Core |
|---|---|---|---|---|
| Before | 2.62 s | 1.336 s | 1.657 s | 0.653 s |
| The files, with `Parser::parse()` as it was | 2.63 s | 1.338 s | 1.664 s | 0.654 s |
| With `ParseRun` | 2.59 s | 1.310 s | 1.640 s | 0.634 s |

Moving the code made no difference, and making the parse an object made
the core 3% faster, which was not the aim. The reason was not looked
into; the code that the compiler makes for the loop is simply different.

### Verification

* The parse forests of the 1,000 news sentences and of
`benchmarks/corpus.txt` are identical to those from before, including
the order of the families (`bench_parse.py --digest`), after each of
the eight steps.
* The checks listed at the end of section 13, all of them.
10 changes: 5 additions & 5 deletions src/reynir/binparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2612,15 +2612,15 @@ def describe_token(
# Native (C++) token/terminal matching support
#
# The functions below build a matching table that enables the C++
# Earley parser core (eparser.cpp) to decide most token/terminal match
# Earley parser core (ematcher.cpp) to decide most token/terminal match
# queries natively, without calling back into Python. Terminals whose
# matching semantics are not natively encodable (verbs, prepositions,
# proper names, ending constraints, etc.) are marked T_PYTHON and
# continue to be matched through the regular Python callback.
# The binary record layouts here mirror, byte for byte, the TerminalSpec,
# MeaningRec and TokenRec structures declared in eparser.h.
# MeaningRec and TokenRec structures declared in ematcher.h.

# Terminal spec kinds (see eparser.h)
# Terminal spec kinds (see ematcher.h)
_T_PYTHON = 0
_T_TEXT = 1
_T_TEXT_CAT = 2
Expand Down Expand Up @@ -3028,7 +3028,7 @@ def build_matching_table(grammar: "BIN_Grammar") -> MatchingTable:

def matching_masks(token_class: Type[BIN_Token] = BIN_Token) -> bytes:
"""Return the bit masks that native matching uses (a MatchMasks
structure, see eparser.h), for tokens of the given class"""
structure, see ematcher.h), for tokens of the given class"""
bit = BIN_Token.VBIT
# Variants of a verb terminal that must be found in the form of a verb
verb_variants = 0
Expand Down Expand Up @@ -3163,7 +3163,7 @@ def encode_token_matching_data(
) -> bytes:
"""Encode a token, along with its BÍN meanings, into the packed
native matching format (a TokenRec header followed by MeaningRec
entries; see eparser.h). If verb_profiles is given (a cache, shared
entries; see ematcher.h). If verb_profiles is given (a cache, shared
between the tokens of a parser), the meaning records of verbs
describe them well enough for verb terminals to be matched natively.
It must not be given if the class of the token has its own
Expand Down
76 changes: 76 additions & 0 deletions src/reynir/ebase.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*

Greynir: Natural language processing for Icelandic

C++ Earley parser module: basic definitions

Copyright © 2026 Miðeind ehf.

This software is licensed under the MIT License:

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

The types, and the few macros, that all parts of the C++ module use.

*/

#ifndef EBASE_H
#define EBASE_H

#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <assert.h>
#include <new>


// Define DEBUG, here or with -DDEBUG, for a build that writes a trace of
// what it does to stdout: of each parse, and of the reading of a grammar.
// #define DEBUG

// Assert macro. The assertions are enabled in DEBUG builds, or - without
// the trace - by defining EPARSER_ASSERT. Note that NDEBUG must not be
// defined in either case; Python's default compiler flags do define it.
#if defined(DEBUG) || defined(EPARSER_ASSERT)
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif


typedef unsigned int UINT;
typedef int INT;
typedef wchar_t WCHAR;
typedef char CHAR;
typedef unsigned char BYTE;
typedef bool BOOL;
typedef unsigned long long UINT64;


// For functions that are called from the hot path of the parser, but
// seldom: keeping them out of line keeps the hot path small
#if defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE __attribute__((noinline))
#endif


#endif // EBASE_H
Loading
Loading