8000 The hpp files hold mappings, and must not · Issue #600 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

The hpp files hold mappings, and must not #600

Closed

Description

@Lillecarl

DONE. It opened at _cpp/eval.hpp, 417 lines of hand-written
C++ with about 160 MAPPINGS in it. Every mapping this task named is
emitted now, and derived_path.hpp - the last file that was mapping
rather than helping - is deleted.

40  errors.hpp

238 eval.hpp all helpers
12 libstore.hpp

290 code lines, down from 330

What remains is one shape rather than a file, and it is its own
task: a generated nanobind type_caster for nix::ref<T> and for a
union, which would take the last conversions the declarations name
by hand. See the closing section.

Where it comes from

Carl: "Why do we have hand crafted hpp files? Isn't our codegen good
enough? The goal is that our uberannotated Python source is the only
source of truth?"

The goal is right and the file drifted. It was 108 lines under the
mock and it is 417 now, because the libexpr swap wrote a whole
Evaluator and Bridge surface by hand rather than growing the
declaration to reach it.

Carl set the rule when he saw the number, and it is sharper than a
budget: "We shouldn't have any C++ mapping code at all, if we need
helpers to make the codegen simpler we can have those but nothing
hand-written C++ for the actual mappings."

So this is not a reduction target. A mapping in _cpp is in the
wrong file, and the count is how many are left rather than how many
are affordable.

The test is who calls it. Generated code calls a HELPER. A
MAPPING is the generated code.

I proposed a line-count baseline that would fail the build on growth,
and Carl rejected it for the right reason: a budget legitimises the
thing that should not exist. Recorded because it is the tempting
wrong answer.

The measurement

417  code lines in _cpp/eval.hpp   (784 with prose)

MAPPINGS - must go
 85    guarded accessors
 57    parse_expr / eval_expr / make_int / make_string / make_bool
 18    the type_name switch
 ~8    list_append / attrs_set bodies
---
~168

HELPERS - stay, and the generated code calls them
~249    the GC root, thread registration, EvalCore, the core's
        deleter, the staging machinery, the is_* predicates

1. Guarded accessors - 85 lines, and the biggest win

Every reader on Value has the same body:

auto * v = get();
if (v->type<true>() == nix::nThunk)
    throw std::runtime_error("value is a thunk");
if (v->type() != nix::nInt)
    throw std::runtime_error("value is not int");
return v->integer().value;

Twelve of them. The only things that differ are the ARM
(nix::nInt), the field (integer()), and sometimes a conversion
(.value, std::string(...)).

nix::Value is a tagged union whose readers are noexcept and
UNDEFINED on the wrong tag, so the guard is not optional and never
will be. That makes it exactly the kind of thing to derive: a rule
that must be applied everywhere, identically, with no judgement.

What the declaration would say:

@guard("int")
def integer(self) -> I64:
    """This value as an integer."""

@guard names a key of the @tree scalars map, which the class
already declares. The thunk check comes free - a thunk is a kind that
is not the named one - so it stops being written twelve times.

2. The type_name switch - 18 lines, and the repo already does this

type_name maps nix::ValueType to the strings @tree keys on.
decl/words.py already declares HashAlgorithm and
ContentAddressMethod as StrEnums whose members ARE the strings a Nix
parser takes, and pyenum.py emits them.

This is the same mapping pointed the other way: C++ enumerator to
Python string, rather than Python string to C++ parse. One emitter
knows how to write a table between an enum and a set of strings; it
should write both.

The declaration would name the enum and the pairs, and the switch
would be emitted. It also closes a real gap: nFloat, nPath and
nNull are arms the walk could carry as SCALARS and does not,
because adding one today means editing C++.

3. The thin producers - 57 lines, and they need via back

make_int is:

auto * v = state().allocValue();
v->mkInt(value);
return wrap(v);

The interesting half is one line. The rest is the wrap.

This is via again, and the direction matters. via was deleted
because the INBOUND use is unsafe here - nix::Value's readers are
undefined on the wrong tag, so no method may bind a pointer-to-member
through a handle. The OUTBOUND use is a different mechanism with the
same name: a produced pointer wraps in the handle before it crosses.

So the lesson from deleting via is not "handles cannot be derived".
It is that one word carried two mechanisms, and only one of them was
refuted. The outbound half should come back under its own name, and
@produced(by=...) is where it belongs - the class already says who
makes one; it could say what wraps it.

What is a HELPER, and stays

About 249 lines. Each is infrastructure the generated code calls,
rather than a statement of what a Python name means:

  • The GC root. nix::allocRootValue and the RootValue member.
    A declaration language would need a concept of "reachable from a
    foreign collector", which is one library's problem rather than a
    binding pattern.

  • Thread registration. GC_get_stack_base, the two thread-local
    flags, the register/unregister pair. libexpr exposes no API for
    this; it is the integration this repo owns, and it is where the
    6600x latch bug lived.

  • EvalCore. Its member ORDER is the fact - each object takes the
    previous by reference - and a declaration that stated the order
    would be restating C++ initialisation rules.

  • The core's deleter. Registering before teardown, once, so no
    holder has to remember.

  • The staging builders. stage, stage_attr, materialise, the
    is_* predicates, and the built_ flag that refuses to rewrite an
    evaluated value.

    These are helpers and they split cleanly from the mappings that use
    them. Evaluator::list_append is a MAPPING - it says what the
    Python name list_append does - and its body is two lines: check
    is_builder, call stage. That body should be emitted, and the
    two functions it calls should stay here. The same split applies to
    attrs_set.

Order

1 first: it is the most lines, the most mechanical, and the guard is
a correctness rule rather than a convenience - deriving it means a
thirteenth accessor cannot forget it. Then 2, which is small and
mostly reuses pyenum.py. Then 3, which needs a marker designed
rather than a body deleted.

#598 overlaps: @guard is a new marker, and designing it
before the marker table exists means designing it twice.

The numbers, remeasured (065)

The figures above are stale in two ways. _cpp/eval.hpp is
huggorm_decl/cpp/eval.hpp since the restructure, and it is 238 code
lines rather than 417 - the accessors named under MAPPINGS came down
before this was reread.

The second way matters more. The census counted cpp/<module>.hpp
for each module it emitted, so it only ever measured the two files
whose names are module names. What the whole directory holds:

238  eval.hpp          counted
 35  derived_path.hpp  counted
 37  errors.hpp        NOT counted, until 065
 20  libstore.hpp      NOT counted, until 065
---
330  total

Plus 103 in Cxx bodies - 56 in eval.py, 47 in store.py.

So the number to work down is 330, not 273, and 57 of it had never
appeared in a build log. census_cpp prints the directory total now
and names any file no module claims.

errors.hpp and libstore.hpp are the two orphans. Neither has a
declaration emitted beside it, which is why the per-module census
could not see them and is the first thing to look at: a helper with
no declaration next to it has nothing pulling it toward being
derived.

Remeasured again (after 066)

The three fronts above are CLOSED. Nothing in this section is new
work; it is a reread, because the file still said OPEN while pointing
at code that no longer exists.

cpp/eval.hpp is 238 lines and every one of them is on the HELPER
list this task wrote. The guarded accessors are gone, the type_name
switch is gone, and make_int / make_string / make_bool /
parse_expr / eval_expr are gone. What is left is the GC root and
thread registration, EvalCore and its deleter, and Bridge - the
staging builders, the is_* predicates, sorted, symbol, intern,
materialise, wrap. Generated code calls all of it.

So the "Order" section is spent. The directory total has not moved -
still 330 - because the lines that came out of eval.hpp were
replaced by lines that were never counted. That is the honest reading
of a flat number.

35  derived_path.hpp
37  errors.hpp

238 eval.hpp all helpers
20 libstore.hpp

330

Three things are left, smallest first.

errors.hpp names its Python module in a string literal - DONE

error_class imports "huggorm_bindings.errors". That module's name
is DERIVED three other ways - errors_module() from the declaration's
stem, _policy.ERROR_MODULE, and the emitted file name - and this is
a fourth copy that no reader of the other three would find.

It is the bug 065 already found one layer up, still here. Renaming
decl/errors.py makes this lookup return null, and raise_as then
falls back to a plain RuntimeError carrying the message. Every nix
error silently loses its type, and no gate says so.

The generated catch chain already passes the class name. It should
pass the module too, which makes raise_as a helper with no library
knowledge in it at all.

Done. chain() takes the module and writes
raise_as("huggorm_bindings.errors", "BadStorePath", e), from the
same errors_module() that names the emitted file and fills the
policy table. The static import cache went with it: it would have
held whichever module asked first.

Proved by renaming decl/errors.py to decl/nixfaults.py. The
bindings and the generated package both build, and the smoke test's
except NixError still catches - which it could only do if the
emitted C++ had followed the rename. The suites then fail loudly at
typecheck, naming all seven sites, because a test may name the module
it tests.

The rename also found a copy an hour old: the smoke test block added
by 066 wrote from huggorm_bindings.errors import NixError. It reads
_policy.ERROR_MODULE now. That is the argument for perturbation in
one line - the copy was written, reviewed and committed the same day,
and only breaking the gate found it.

errors.hpp is 41 code lines, up from 37: the parameter costs two
lines and the DECREF the dropped static did not need costs two more.
A number going up while a mapping goes away is the right trade, and
it is why this task has no budget.

libstore.hpp: open_store is a conversion - DONE

init_libstore is a helper and stays - it is idempotent
initialisation that libstore exposes no other way, and a declaration
points @binds at it.

open_store is one line: nix::openStore(uri), taken as a
shared_ptr rather than the ref<Store> upstream returns. CLAUDE.md
lists a conversion as a MAPPING. Whether the declaration can say
"take this return as a shared_ptr" is the question; if it can, this
file is 12 lines.

Done, and the question turned out to be the wrong one. The
declaration never had to say anything about the conversion: ref
defines an implicit operator std::shared_ptr<T>, so the call alone
is enough. What blocked it was the EMITTER - _factory wrote
nb::new_(&symbol) and only that, so a factory had to be a named C++
symbol and every class needing one line of adaptation was pushed into
cpp/.

_factory writes a lambda now when the declaration carries a body,
which is the shape free_function already had. _lambda_head is
shared by the two, so a free body and a factory body spell one lambda
the same way. decl/store.py carries
Cxx("return nix::openStore(uri);") and @needs("store-open.hh").

Proved by breaking: with the branch reverted the emitter writes
nb::new_(&) - made.binds is empty - and g++ says "missing
template arguments before '(' token".

A second perturbation refuted a claim I had written into the code.
The lambda spells its return type, and the comment said ref<Store>
would not deduce without it. Dropping the spelling and rebuilding
compiled fine: nanobind rea 8000 ches the holder through the same implicit
conversion either way. Two emitted lines change - this one and
gc_stats - and both build. The spelling stays as consistency with
_method, and the comment now says it is not a fix.

libstore.hpp is 12 code lines and holds only init_libstore, which
is a genuine helper: libstore ABORTS rather than raising when it has
not been initialised.

35  derived_path.hpp
40  errors.hpp   (+3, the module parameter and its DECREF)

238 eval.hpp all helpers
12 libstore.hpp (-8)

325

derived_path.hpp has reached its own trigger

The file states the condition itself: "WHEN THIS MOVES INTO THE
EMITTER: the second union whose C++ arm wraps a declared arm in a
one-member struct. One user is a helper; two is a pattern."

There are two - SingleDerivedPath and DerivedPath - so the
condition is met. The declaration already knows the arms; the four
as_arms / from_arms visits say the same thing by hand.

This is the largest of the three and the one that needs a marker
designed rather than a literal moved, so #598 overlaps it the
way it overlapped @guard.

Corrected, after reading derived-path.hh

"a marker per union" was my guess and it is too big. What upstream
actually holds (nix-store 2.34.8,
nix/store/derived-path.hh):

DerivedPathOpaque      { StorePath path; }

SingleDerivedPathBuilt { ref<const SingleDerivedPath> drvPath;
                         OutputName  output; }
DerivedPathBuilt       { ref<const SingleDerivedPath> drvPath;
                         OutputsSpec outputs; }

struct SingleDerivedPath : variant<DerivedPathOpaque,
                                   SingleDerivedPathBuilt>
struct DerivedPath       : variant<DerivedPathOpaque,
                                   DerivedPathBuilt>

There is no inheritance. Each union is a struct that PUBLICLY
INHERITS its own std::variant and re-exposes it through raw(),
which is why the visits say std::get_if<...>(&p.raw()) rather than
&p - they cast back to the base.

The part that shrinks the marker: SingleDerivedPath::Opaque and
DerivedPath::Opaque are BOTH DerivedPathOpaque. The same struct,
the same single member path. Only the Built arm differs between the
two unions, and only in one member - output, one string, against
outputs, an OutputsSpec.

So the fact is stated once, not once per union: the opaque arm's C++
type is a one-member struct wrapping the declared arm, through the
member path
. Four visits collapse to one declared fact.

held stays a helper either way. ref<const SingleDerivedPath> is
non-nullable by construction, so building one from a value allocates,
and that is upstream's spelling rather than a decision this repo
makes.

Worth checking separately, and probably NOT the same pattern:
OutputsSpec is a variant too - variant<All, Names> where All is
a std::monostate and Names is a std::set with its default
constructor deleted. A monostate arm is a different shape from a
wrapped-struct arm, and its two Cxx bodies should not be folded
into this marker just because both are variants.

What the marker would actually cover

The nine Cxx bodies in derived_path.py are seven now: output
and outputs were plain member reads and say @reads, which the DSL
has had all along and nineteen accessors elsewhere use.

The seven, classified - because the marker's scope is the useful
number, not the total:

THE WRAPPED-ARM PATTERN - four, and the marker derives them
  SingleDerivedPathBuilt.__init__   placement-new + held()
  SingleDerivedPathBuilt.drv_path   as_arms(*self.drvPath)
  DerivedPathBuilt.__init__         placement-new + held()
  DerivedPathBuilt.drv_path         as_arms(*self.drvPath)

OUTPUTSSPEC'S OWN VARIANT - two, a DIFFERENT shape
  OutputsSpec.all      holds_alternative<All>
  OutputsSpec.names    get_if<Names> + range copy

A DECISION - one, and it stays
  OutputsSpec.__init__  refuses `all` with names, and neither

The two drv_path bodies are IDENTICAL text, character for
character. That is the clearest statement of the problem in the file:
one fact, written twice, in two classes that differ in nothing this
line touches.

So the marker covers four bodies here plus the four visits in
cpp/derived_path.hpp - eight sites, one declared fact. held stays
a helper on both sides of the change.

OutputsSpec is the warning against widening it. Its arms are a
std::monostate and a std::set, not a struct wrapping a declared
type, so folding it in would make one marker mean two things.

And 61 Cxx bodies

Cxx(...) in a declaration is the sanctioned hatch: C++ written
where the declaration can see it, lifted out by the reader. 59 uses
now, concentrated in eval.py (15), store.py (14) and
derived_path.py (7). Not counted in the cpp/ total and not a
violation - but the hatch is where a mapping goes to hide, and the
one look at derived_path.py found two bodies that only needed a
marker the DSL already had.

Worth the same look at eval.py and store.py, which have twice as
many and have never had one.

derived_path.hpp: the fact rides on the alias - DONE

The file is gone. 35 code lines, and the emitter writes every one of
them from what the two aliases now declare.

Carl asked whether classes, decorators and multiple inheritance

were the right shape. They are not, and the reader says so.

The proposal was class SingleDerivedPath(StorePath, SingleDerivedPathBuilt) - a real object to decorate, with the arms
as bases. Three things are wrong with it, and each was measured
rather than argued:

The variance is backwards. Python inheritance is "is a". With the
arms as bases, a SingleDerivedPath IS a StorePath, and
isinstance(SingleDerivedPath(), StorePath) is True. A sum type says
the opposite: a StorePath is one of the things a SingleDerivedPath
can be. The declaration would state the relation upside down, and a
type checker would believe it.

The reader already refuses a second base, for its own reason.
read.py raises "one base. Every hierarchy this binds is single
inheritance", and Decl.base means the C++ base a bound class
derives from - LocalFSStore genuinely derives from Store. Taking
the refusal out would make one syntax carry two opposite meanings:
class LocalFSStore(Store) says "is a Store", and class DerivedPath(StorePath, DerivedPathBuilt) would say "is one of
these".

The union stops being a union. Probed in Python: the class
inherits its arms' methods (drv_path and to_string both appear on
it) and is constructible through the arm's __init__. A | B is a
type alias a checker and a reader both see; a class is not.

What it is instead: Annotated, which this DSL already documents

declare.py's own header says it: "Annotated type aliases carry
facts about a TYPE. Decorators carry facts about a METHOD or a
CLASS." A union is a type. So the alias keeps being an alias and the
C++ facts ride beside it:

SingleDerivedPath = Annotated[
    StorePath | SingleDerivedPathBuilt,
    Variant(
        "nix::SingleDerivedPath",
        raw="raw()",
        header="nix/store/derived-path.hh",
        wraps={"StorePath": Wrap("nix::DerivedPathOpaque",
                                 holds="path")},
    ),
]

Four facts, and each one is a thing only the declaration can know.
cxx is the union's own type. raw is how to reach the std::variant
inside it, because upstream's unions publicly INHERIT their variant.
header is where the type is declared - a union has no @header to
carry it, and store.cpp only PASSES a DerivedPath, so it declares
none of the arms. wraps says the one thing that is not derivable:
the opaque arm is a DerivedPathOpaque, and the StorePath Python
holds is its member path.

Every arm wraps does not name is held as itself, which is why
SingleDerivedPathBuilt says nothing. Naming every arm would make
the one that IS wrapped read like the rest.

What the emitter derives from it

nbemit.conversions writes as_arms, from_arms and held per
union, into the same namespace huggorm block as_tuple already
used. The output is the deleted header, character for character,
except that it spells nix::DerivedPathOpaque where the hand
version said nix::SingleDerivedPath::Opaque - the same type, and
the one the declaration states.

held is generated too. #600 had it staying a helper because
ref is upstream's spelling rather than a decision - but it converts
arms into a ref, and CLAUDE.md lists a conversion as a MAPPING. It
is three lines from the same fact, so keeping it by hand would have
left one hand-written line to justify a file.

_sites is new and is why there is one walk rather than two. The
includes need every type's caster and the conversions need every
union; both read the same list of places a translation unit names a
declared type.

96  errors.hpp

601 eval.hpp
48 libstore.hpp

Proved by breaking

wraps={"StorePathX": ...} - the reader refuses at
derived_path.py:146:1, naming the arms it could have meant.

Dropping header= from the DerivedPath alias - store.cpp stops
including nix/store/derived-path.hh.

holds="pathx" - g++ says "'const struct nix::DerivedPathOpaque' has
no member named 'pathx'; did you mean 'path'?".

And one perturbation REFUTED a claim in the declaration. Dropping
raw="raw()" emits &p instead of &p.raw(), and it compiles:
std::get_if deduces variant<Types...>* from the derived class,
because upstream's inheritance is public. So the field is not
load-bearing. It stays, with the comment corrected to say why - &p
leans on that inheritance being public, which is a detail of the
header rather than an API of it, and goal 1 is closeness to what Nix
publishes.

The Cxx-body audit, done for every declaration

derived_path.py was audited because the marker work went through
it, and it gave up two @reads. The same look at the other eight, by
shape rather than by file:

57 Cxx bodies in all

 3  return as_list(self.MEMBER);       <- @reads, and nothing else
 2  out-parameter, then as_list        <- a real call
 4  reach through self.get()           <- @guard, already derived
 5  mention self.config                <- not one shape; see below
 2  deref of a ref MEMBER              <- the DerivedPath pattern
 1  deref of a ref<T>                  <- query_path_info
 1  .string() on a fs::path            <- follow_links_to_store

Only the first row was restatement, and it is fixed: references,
sigs and signatures say @reads now, and the emitted C++ is
identical.

"Mention self.config" looked like five and is not one shape. Only
nixstore.get_store_dir is a member read through it; the rest call a
method on it, or mention it inside larger logic - real_path does a
dynamic_cast and raises Unsupported, which is a decision.

eval.py and store.py have the most bodies and gave up none.
Their shapes are guards and producers, which the emitter already
derives, and genuine decisions.

What the audit DID find: a fact stated in one branch of two

_method spelled the lambda's return type for a declared body and
not for a derived one. The comment justifying it argued from the
BODY - "cannot deduce" - which is true of a derived body too. So
@reads over a list[T] deduced as_list's return where the same
accessor with a Cxx line spelled it, and swapping the three
accessors to @reads made that visible: the bodies matched, the
lambda heads did not.

_returns is now read by both branches. 29 emitted lambdas gained a
return type and all of them compile.

Still open, and it is one shape, not three

*self.queryPathInfo(path), *self.drvPath twice, and the held
that builds one: four sites where a nix::ref<T> meets the boundary.
A generated nanobind type_caster for ref would take all four, and
the same caster for nix::DerivedPath would take the seven
as_arms/from_arms calls the bodies still name. That writes C++
shapes this repo has not written before, so it needs Carl's word
first.

Migrated from tasks/063-the-hpp-files-should-be-smaller.md.done.


Assisted-By: Opus 5

Activity

  1. added
    source: huggorm
    on Oct 19, 2026
  2. added theissue type on Oct 19, 2026
  3. transferred this issue fromnixidae/huggormon Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: huggorm

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0