Files
logos-cpp-sdk/cpp-generator/lidl_to_json.cpp
T
Dario LipicarandClaude Opus 5 acea0d24e2 feat(codegen): a lossless Qt type mapping, and LIDL types in getMethods (#149)
* feat(codegen): a lossless Qt type mapping — typed containers and optionals

`lidlTypeToQt` answered four different LIDL types with one Qt name. `[uint]`,
`[bstr]`, `[[uint]]` and `[any]` were all QVariantList; `{tstr: uint}` and
`{tstr: any}` were both QVariantMap; every `?T` was a bare QVariant. A Qt
consumer therefore lost, on the SAME contract, types that the std consumer next
door kept — it could not tell `?tstr` from `?uint`, and got no compile-time
check on any element.

The table is now recursive:

    [T]                     QList<qtOf(T)>          ([tstr] stays QStringList)
    {tstr: V}               QMap<QString, qtOf(V)>
    ?T                      std::optional<qtOf(T)>  (through optionalValueType,
                                                     so ??T stays two-state)
    any                     QVariant                 — KEPT, deliberately

`any` is the one row that must not widen: QVariant is the only Qt type that
holds bytes AND an exact uint64 AND arbitrary nesting at once, so every
narrower spelling would lose what it was chosen to carry. The rule is applied
at the LEAF, so anything whose element type bottoms out at `any` keeps the
QVariant-family spelling at every depth — `[any]` is QVariantList, `[[any]]`
still is, `{tstr: [any]}` is QVariantMap, `?any` is QVariant.

THE TRAP, and why this is not just a rename. A widened name must never reach
QVariant::fromValue / qvariant_cast / logos::qt::toWire as a WHOLE value.
logos-protocol's qvariantToNlohmann matches a CLOSED userType() set:
QList<qulonglong> is in none of it, so it serialises to JSON null. The decode
fails just as quietly — qvariant_cast<QList<qulonglong>> of a QVariantList
yields an EMPTY list. Neither direction warns. So every widened slot is encoded
and decoded by a generator-emitted ELEMENT LOOP, the shape the record cases
already used, and `lidlQtNeedsElementLoop` is the single predicate that decides
which slots need one.

The emitted loops take their source as a lambda PARAMETER, not a body-local
binding. They nest (`[[uint]]`), every level wants the same short names, and a
local — or a range-for over a name the loop itself declares — is then
self-referential: it compiles and reads uninitialised memory. Measured: three
round-trip tests died on SIGTRAP before the argument form.

THE STRING-KEYED EMITTER IS FROZEN, ON PURPOSE. generator_lib is keyed on flat
type NAMES (lidl_to_json flattens the contract before it gets there, because
that emitter also serves the metaobject-introspection path), so it cannot
derive the levels an element loop needs without parsing C++ type names back
into a tree. Every widened spelling is folded back to the name it produced
before (legacyQtBase), which keeps BOTH surfaces it feeds byte-for-byte
unchanged: the legacy Qt consumer, and the Qt-free lp one whose table is
DERIVED from it through mapParamTypeStd. Verified by generating a
28-method contract through both before and after: the diff is empty. The
widened types are spent in the TypeExpr-driven emitters instead
(lidl_gen_client.cpp here, lidl_gen_qt_consumer.cpp in logos-qt-sdk).

Also here, because both are consequences of the table becoming recursive:

  * lidlTypeToQt gained a record-name HOOK. A wrapper nests its record structs
    in the wrapper class, so a type written outside that scope must qualify
    them — and the emitters used to do that by matching the three shapes that
    could mention a record on the finished string. `?Point` and
    `QList<QList<Point>>` are now spellable, so the qualification happens
    during the walk, at the one place that knows a name is a record.
  * lidlTypeToLidlText — the LIDL contract spelling of a type. Unused here; the
    commit that follows puts getMethods() on it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(cdylib): getMethods publishes the LIDL contract vocabulary, not Qt names

A module's published metadata — `returnType`, `parameters[].type`, `signature`
— answered in Qt type names. Two things wrong with that, and the second is the
one that matters:

  * a cdylib module is Qt-FREE. It described itself in the types of a language
    it does not use, to readers (`lm`, logoscore's method listing, basecamp's
    module inspector) that are showing a human what the module offers.
  * it was LOSSY. `[uint]`, `[bstr]` and `[any]` are three different LIDL types
    and all three published as the single word QVariantList, so the listing
    could not be read back as a contract. That is now `[uint]`, `[bstr]`,
    `[any]`; `{tstr: uint}`; `? tstr`; and a record publishes its declared
    name.

WHY THIS IS SAFE — checked, not assumed. The historical objection is recorded
in the function this replaces: these strings are read as METATYPES, and
emitting a record's struct name here once made the host SIGSEGV. Nothing in the
current runtime does that. logos-plugin-qt's QtProviderObject dispatches on
`method.returnMetaType()` / `parameterMetaType(i)` — the QMetaObject, never
this JSON — and every remaining reader treats these fields as opaque text:
logos-module's `lm` prints them, logoscore's output.cpp prints them, basecamp's
CoreModuleManager forwards the JSON to QML, and the plain wire's json_mapping
only round-trips them. Nothing anywhere builds a QMetaObject from this
metadata.

The spelling comes from lidlTypeToLidlText, which mirrors logos-lidl's
serializeTypeExpr. It is a COPY, because that function is file-local to
logos-lidl's serializer.cpp and the public headers expose no type printer —
so instead of hoping, the pairing is ASSERTED: the test round-trips each shape
through `lidl::serialize` and reads the type text back out of the emitted
`.lidl`. When logos-lidl exports a printer, delete the copy and call it.

Not fixed by this, and not attempted: the Rust SDK's provider generator has its
own `qt_type_name` writing the same JSON, so the two languages now disagree
about how a module describes itself. That is a cross-repo change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(doctests): the generator round-trip pins the lossless Qt spellings

`cpp-sdk-generator-roundtrip.test.yaml` is a CI gate
(.github/workflows/doctests.yml), and two of its `expect_contains` were
pinned to the type names the Qt consumer produced BEFORE the lossless
mapping:

    QStringList labels(const QVariantList& ids
    QVariant nearest(const Point& p, QVariant limit

The generator now emits `QList<qulonglong>` and
`std::optional<Point>` / `std::optional<qulonglong>` for those slots, so both
assertions failed. The `nearest` step's `run` grep was pinned the same way
(`QVariant nearest`), so the line it was supposed to assert on was not even
in the output being searched.

Verified by running the spec's own steps against the generator built from
this commit: 10 run-steps, 0 failures. The `[uint]` -> QList<qulonglong> and
`?T` -> std::optional<T> lines were read out of the real
`consumer/sensor_module_api.h` and `geometry/geometry_module_api.h`, not
written from the mapping table.

Prose too, in three places that described the old table: the Flow-3 type
mapping ("other arrays -> QVariantList"), the composite-types intro
("optionals ... stay QVariantMap / QVariant"), and the composite-signature
step. They now say what the mapping actually is — one LIDL type, one C++
spelling, with `any` the single deliberate exception — and `nearest` is
called out as the one signature carrying both halves of the optional
mapping.

`doctests/outputs/cpp-sdk-generator-roundtrip.md` carries the same prose
corrections. That tree is hand-pinned and CI never diffs it, which is
exactly why it must be corrected by hand.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(generator): the consumer wrapper comes from the contract, not from getMethods

`logos-cpp-generator <plugin> --module-only` — the invocation
logos-plugin-qt's generate-module-headers.sh makes for every module's lp
wrapper — built that wrapper's whole type surface out of the plugin's
PUBLISHED `getMethods()` metadata. It now builds it out of the module's `.lidl`
contract, the file the same invocation already passes as `--events-from`.

WHY THIS IS A DEFECT AND NOT A PREFERENCE. generator_lib is keyed on flat type
NAMES, and mapParamType / mapReturnType fall back to QVariant for a name they
do not recognise (generator_lib.cpp:142 and :153). So the wrapper's types
depend on the VOCABULARY a module happens to publish its metadata in, and a
vocabulary this emitter has no row for degrades to QVariant — LogosMap on the
lp surface — with no diagnostic at any layer. It is a machine reader of a
listing that every other consumer treats as human-facing text, and it fails
silently.

It was measured, not theorised. 621772a made the cdylib backend publish the
LIDL contract vocabulary (`tstr`, `[uint]`, `result`, `? tstr`) in place of Qt
type names, because that listing is what `lm`, logoscore and basecamp show a
human and Qt names are the wrong answer for a Qt-free module. Every
`interface: "universal"` module's lp wrapper collapsed:
logos-test-modules' `checks.unit-tests-new-api` went PASS -> FAIL, and the
compiler said exactly why —

    error: no viable conversion from 'LogosMap' to 'StdLogosResult'
        StdLogosResult r = modules().test_basic_module.resultWithMap();

`result` is not a name mapReturnType knows, so it became QVariant, so it became
LogosMap. Bisected to exactly 621772a (5ffd90b passes, dd52d9d fails).

THE FIX IS TO STOP READING THAT VOCABULARY, not to learn a second one.
`int` means a 32-bit Qt int in one table and a 64-bit LIDL integer in the
other, and the reader cannot tell from the string which table it is holding —
a merged table would silently mistype every integer on every module. The
contract has no such ambiguity: it is a TypeExpr tree, and lidl_to_json is the
single place it is flattened. Taking methods from it makes this path emit the
same wrapper as `--general-only --dep <name>=<name>.lidl`, which is what
buildHeaders.nix already runs under cross-compilation and for the entire Qt
surface. Contract-first, on every platform, for every surface.

WHAT CHANGED, exactly:

  * loadEventsFromLidl -> loadContractFromLidl. It already parsed the whole
    contract and threw the methods away; it now returns them, after the same
    lidlCheckRecords + lidlInjectIdentity + noteOptionalPositionalSlots that
    main.cpp's --dep path applies. Identity is injected rather than read,
    matching the provider side (main.cpp's --backend cdylib), so the two cannot
    disagree about name() / version().
  * A sidecar that is NAMED BUT MISSING is now refused (exit 2), and an
    unreadable or malformed one is fatal (exit 4). Both used to be shrugged off
    — which shipped a wrapper with no typed events, and would now ship one with
    no typed methods, in the silently-empty shape generate-module-headers.sh
    exists to refuse.
  * The plugin is STILL LOADED. That load is the dlopen check this path
    performs (exit 3 on an SDK/ABI skew) and it is unchanged; what the plugin
    says about itself is now compared against the contract instead of believed,
    and a divergence — a stale sidecar — is reported by name on stderr. Only
    `isInvokable` entries are compared: a cdylib publishes its events into the
    same array, tagged `"type": "event"`, and both emitters already skip those.
  * A module with NO contract keeps introspection — a handcrafted Qt plugin's
    QMetaObject is still the only description of its API that exists, and Qt
    type names are the right vocabulary for it — but a listing spelled in the
    LIDL vocabulary with no contract to go with it is now REFUSED (exit 7)
    instead of silently producing the untyped wrapper. That combination is only
    reachable by hand: buildHeaders.nix always passes the flag when the sidecar
    exists, and it is the shape the developer guide used to suggest. The two
    vocabularies are not distinguishable in general, which is the whole reason
    this emitter must read only one — but they do not have to be: the words
    they share (`int`, `bool`) are all in the known table and never reach the
    fallback, so the check keys on the LIDL half Qt has no word for at all
    (`tstr`, `bstr`, `uint`, `float64`, `result`, `any`, and anything starting
    `[`, `{` or `?`). No Qt type is spelled that way, so it cannot false-fire;
    a false negative is just the old behaviour.

THE ENUMERATION, because two previous ones missed this reader. Searching for
who greps `returnType` is what missed it; the question is what the data FLOWS
INTO. Every consumer of a published getMethods array in the workspace:

  MACHINE (one, and it is this one)
    logos-cpp-sdk cpp-generator/plugin_introspect.cpp, reached only through
    logos-plugin-qt's generate-module-headers.sh / buildHeaders.nix.

  HUMAN-READABLE OR OPAQUE PASSTHROUGH (all of them)
    logos-module's `lm` (prints; --json re-emits verbatim), logoscore-cli's
    client/output.cpp (prints) and core_service_dispatch.cpp (forwards),
    logos-logoscore-tui (formats one line per method), logos-module-viewer
    (reads the QMetaObject directly, not this JSON), basecamp's
    CoreModuleManager / MainUIBackend (hands the JSON string to QML),
    logos-protocol's json_mapping.cpp and qvariant_rpc_value.cpp (round-trip
    the strings unread).

  PRODUCERS, for completeness: lidl_gen_cdylib.cpp (LIDL vocabulary),
    logos-plugin-qt's QtProviderObject (Qt names, from the QMetaObject) and
    lidl_gen_cdylib_glue.cpp (forwards the cdylib's), logos-rust-sdk's
    rustgen_provider.rs (still Qt names — the two languages disagree, as
    621772a noted), and logos-protocol's ModuleProxy, which appends derived
    name()/version() entries spelled `QString`. None of that reaches a type
    decision any more, which is the point of the change.

  Build-system paths checked and clear: `<plugin> --module-only` is invoked
    from exactly one place in the workspace (generate-module-headers.sh:60);
    LogosModule.cmake, buildPlugin.nix and mkLogosModuleTests.nix all use
    `--general-only`, which is contract-driven already; the doctests' `--lidl
    --module-only` is a different mode entirely.

VERIFIED.

`nix build path:./repos/logos-test-modules#checks.aarch64-darwin.unit-tests-new-api`
with this SDK overridden in (plus the logos-lidl overrides the branch needs at
the qt-sdk and plugin-qt nodes) — 32 passed, 0 failed. The same command against
this branch's HEAD fails to compile, as above. The build log shows the path
taken, per module:

  Detected new-API plugin (LogosProviderPlugin), using getMethods() — 43 methods
  Using the module's LIDL contract for the method surface — 41 methods
      (the plugin's published listing is a description, not a type source)

The refusal, measured by hand against a real LIDL-publishing plugin
(test_basic_module, built from this branch) because no check exercises a
hand-run invocation:

  no --events-from   -> exit 7, nothing written, the message above naming
                        8 offending slots
  with --events-from -> exit 0, 41 typed methods, 69 `std::string` in the
                        emitted lp header
  a pre-621772a build of the SAME module (Qt-name listing), no --events-from
                     -> exit 0, still generates, still typed — the refusal does
                        not fire on the vocabulary this emitter can read

nix/tests-generator-cli.nix gains the two CLI-surface cases this adds: a
`--events-from` naming a file that does not exist is refused with that
sentence, and — the control that makes it mean something — the same command
with a READABLE contract gets past the flag and fails on the plugin instead. No
plugin is needed for either: the contract is loaded before the plugin is
opened.

logos-cpp-sdk's own checks (tests, generator-cli, module-impl-abi): 334 of 334.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 18:17:44 -03:00

151 lines
6.4 KiB
C++

#include "lidl_to_json.h"
#include <QJsonObject>
#include <QStringList>
#include "experimental/lidl_emit_common.h" // lidlTypeToQt — the one Qt type mapper
// Convert a TypeExpr → Qt-typed string name (same surface the
// metaobject-introspection path produces for methods, so generator_lib
// can consume both via one code path).
//
// ONE Qt type mapper. This used to be a near-duplicate of `lidlTypeToQt`
// (experimental/lidl_emit_common.cpp) and the two disagreed: this copy had no
// `void` case, so a `-> void` method reaching it as Primitive("void") from the
// impl-header parser fell through to QVariant and generated
// `QVariant doVoid(...)`. (The .lidl parser spells the same thing
// Named("void"), which survived only by accident — mapReturnType's
// `base == "void"` early-out.) The lp/std tables are DERIVED from this name, so
// the same bug produced `LogosMap doVoid(...)` on the Qt-free surface: not a
// Qt-only defect, a front-end one. It is now a delegation, so there is one
// table to disagree with.
QString lidlTypeExprToQtTypeName(const TypeExpr& te)
{
return lidlTypeToQt(te);
}
// Report every optional slot this path still flattens into a bare type name.
//
// A record FIELD no longer does: moduleRecordsToJson below carries `optional`
// alongside the value type, and the emitter reconstitutes it (QVariant on the
// Qt surface, std::optional<T> on the Lp one). What is still flattened is every
// POSITIONAL slot — a method parameter, a return type, an event parameter.
// Those have no name to hang a flag on, so they only ever had the type-kind
// spelling and there is no spelling divergence to fix.
//
// `lidlTypeToQt` DOES now answer `?T` with std::optional<T>. This path cannot
// keep it: generator_lib is keyed on flat type NAMES and folds every widened
// spelling back (legacyQtBase), because encoding one correctly needs an element
// loop it has no tree to derive. So the loss is this emitter's, not the
// mapping's — the TypeExpr-driven Qt consumer emitters keep the value type —
// and the note says which surface is affected rather than claiming the table
// still flattens.
void noteOptionalPositionalSlots(const ModuleDecl& mod, const QString& where,
QTextStream& err)
{
QStringList optSlots;
for (const MethodDecl& md : mod.methods) {
for (const ParamDecl& pd : md.params)
if (paramIsOptional(pd))
optSlots << (qs(md.name) + "(" + qs(pd.name) + ")");
if (typeIsOptional(md.returnType))
optSlots << (qs(md.name) + "() return");
}
for (const EventDecl& ed : mod.events)
for (const ParamDecl& pd : ed.params)
if (paramIsOptional(pd))
optSlots << (qs(ed.name) + "(" + qs(pd.name) + ")");
if (optSlots.isEmpty()) return;
err << "Note: " << where << ": optional positional slot(s) ["
<< optSlots.join(", ")
<< "] are generated as untyped QVariant (LogosMap on the lp surface) by "
"THIS emitter, which is keyed on flat type names and folds "
"std::optional<T> back to QVariant. `?T` keeps its two states (an "
"invalid QVariant / a JSON null is the empty one) but loses T here. "
"The TypeExpr-driven Qt consumer emitters keep it as "
"std::optional<T>; record fields are unaffected on every surface — "
"they carry optionality through.\n";
}
// Build a getMethods()-shaped QJsonArray (the surface makeHeader/makeSource
// consume) from a parsed ModuleDecl. Every interface method is invokable.
QJsonArray moduleMethodsToJson(const ModuleDecl& mod)
{
QJsonArray arr;
for (const MethodDecl& m : mod.methods) {
QJsonObject o;
o["name"] = qs(m.name);
o["returnType"] = lidlTypeExprToQtTypeName(m.returnType);
o["isInvokable"] = true;
QJsonArray params;
for (const ParamDecl& p : m.params) {
QJsonObject po;
po["type"] = lidlTypeExprToQtTypeName(p.type);
po["name"] = qs(p.name);
params.append(po);
}
o["parameters"] = params;
arr.append(o);
}
return arr;
}
// Build the records QJsonArray ({ name, fields:[{name,type,optional}] }) from a
// parsed ModuleDecl — the contract's `type Foo { ... }` declarations, which
// generator_lib turns into structs nested in the wrapper class.
//
// OPTIONALITY SURVIVES HERE, and it is the whole reason this object has three
// keys instead of two. A field has two equivalent spellings — the flag
// (`? name: T`) and the type kind (`name: ?T`) — which logos-lidl's docs/spec.md
// binds to ONE meaning and requires to produce byte-identical code. Flattening
// `fd.type` into a name answered that question two different ways from one
// contract: the flag spelling kept T (so `? maybe: tstr` became a bare `QString`
// that cannot be empty at all, silently defaulting), the type spelling collapsed
// to QVariant. Both answers came from reading the verbatim spelling instead of
// asking.
//
// So: `type` is the value type with optionality stripped (fieldValueType), and
// `optional` is true for either spelling (fieldIsOptional). Those accessors are
// the frontend's, and are the ONLY correct source — `fd.optional` alone and
// `fd.type.kind == Optional` alone are the same bug from opposite sides.
QJsonArray moduleRecordsToJson(const ModuleDecl& mod)
{
QJsonArray arr;
for (const TypeDecl& td : mod.types) {
QJsonObject o;
o["name"] = qs(td.name);
QJsonArray fields;
for (const FieldDecl& fd : td.fields) {
QJsonObject f;
f["name"] = qs(fd.name);
f["type"] = lidlTypeExprToQtTypeName(fieldValueType(fd));
f["optional"] = fieldIsOptional(fd);
fields.append(f);
}
o["fields"] = fields;
arr.append(o);
}
return arr;
}
// Build the events QJsonArray ({ name, params:[{name,type}] }) — same shape
// loadEventsFromLidl produces — from a parsed ModuleDecl.
QJsonArray moduleEventsToJson(const ModuleDecl& mod)
{
QJsonArray arr;
for (const EventDecl& ed : mod.events) {
QJsonObject o;
o["name"] = qs(ed.name);
QJsonArray params;
for (const ParamDecl& pd : ed.params) {
QJsonObject p;
p["name"] = qs(pd.name);
p["type"] = lidlTypeExprToQtTypeName(pd.type);
params.append(p);
}
o["params"] = params;
arr.append(o);
}
return arr;
}