Files
logos-cpp-sdk/cpp-generator/main.cpp
T
Dario LipicarandClaude Opus 5 3d322bd315 fix(codegen): LIDL int/uint are 64-bit in the Qt spelling too (#113)
* fix(codegen): LIDL int/uint are 64-bit in the Qt spelling too

lidlTypeToQt mapped BOTH `int` and `uint` to plain `int`. Everywhere else in the
stack a LIDL int/uint is 64-bit — int64_t/uint64_t in C++ impls, i64/u64 in the
Rust SDK — so the Qt spelling broke the one-type-per-LIDL-type rule and lost
data: a Qt consumer reading a `uint` return got a SIGNED 32-bit value, so
anything above 2^31 came back wrong and anything above 2^63 was never
expressible.

int -> qlonglong, uint -> qulonglong, and returnConversion() gains the matching
accessors (toLongLong / toULongLong instead of toInt).

qlonglong/qulonglong rather than qint64/quint64 so the generated introspection
JSON uses the same names Qt's own metaobject normalisation produces — otherwise
a cdylib module's generated `signature` and a legacy module's
QMetaObject-derived one would disagree for the same LIDL type. Nothing looks
these strings up: the only QMetaType::fromName call in the stack is for
"LogosResult".

This changes two generated surfaces: the Qt consumer wrapper signatures and the
introspection JSON. Passing an int argument still converts implicitly, so
callers keep compiling; code that assigns a wrapper's return into an `int`
narrows and may warn, which is the bug being surfaced rather than a regression.

Tests: 168/168, with the type-mapping and client-emitter expectations updated to
the 64-bit spelling.

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

* feat(records): typed C++ structs for Qt consumers

Completes the Qt half of the type mapping this branch started. A `type Foo { … }`
in a contract now generates a real struct in the client header, so a consumer
writes `Status s = client.makeStatus();` instead of digging fields out of a
QVariantMap. One LIDL type, one type per language.

  lidlTypeToQt   - Named -> the record's struct (was QVariant)
                 - [Record] -> QList<Record>, {tstr: Record} -> QMap<QString,
                   Record>. QVariantList CANNOT hold a record without
                   Q_DECLARE_METATYPE, and a typed list is the point.
  client emitter - struct + inline ToVariant/FromVariant per record, emitted
                   before the class; conversions come after all structs so
                   records may reference each other. Recursive, so a field may
                   itself be [Status] or {tstr: bstr}.
                 - records pass by const&, decode on return, and convert at the
                   call site (sync and async)

bstr fields are QByteArray on purpose: logos-protocol's QVariant<->JSON
conversion already materialises the canonical {"_bytes": base64url} form as a
QByteArray and back, so the record conversions stay pure field mapping and binary
survives at any depth with no record-specific bytes handling.

Verified by COMPILING and RUNNING the generated code, not just asserting on text
— the string tests would not have caught either bug this found: [Record] first
mapped to QVariantList (appending a Status to it does not compile) and the decode
lambdas shadowed their accumulator. Extracted the emitted record block for a
contract with a nested record and a bytes field, compiled it against Qt6Core, and
round-tripped Batch -> QVariant -> Batch asserting items[0].port, the QByteArray
blob and the label all survive. Exit 0.

The LidlTypeToQt.NamedType expectation flips from "QVariant" to the struct name,
which is the behaviour change.

Tests: 169/169.

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

* fix(codegen): teach the lp/std consumer wrappers the 64-bit spellings

Caught while checking whether the SDKs are ready for the `any` migration, and it
is a regression THIS BRANCH would otherwise have shipped.

legacy/generator_lib.cpp generates the lp/std consumer wrappers a universal
module uses to call its dependencies. It matches type names against an
allow-list and falls back to QVariant for anything else:

    static const QSet<QString> known = {
        "void","bool","int","double","float","QString", … };
    if (known.contains(base)) return base;
    return QString("QVariant");

Once lidlTypeToQt reports `qlonglong`/`qulonglong`, every LIDL int/uint method
misses that list — so a typed `int` parameter would have silently become an
opaque QVariant in those wrappers. Worse than the truncation this branch set out
to fix, and invisible until someone read the generated header.

Adds the two spellings to both allow-lists, plus the conversions they imply:
QVariant->Qt (toLongLong / toULongLong), the std spellings (int64_t / uint64_t),
the QVariant->std return path, the Qt-style return, and the default-value case.
The existing `int` entries stay for legacy Qt plugins, whose QMetaObject still
reports `int` for a 32-bit parameter.

Tests: 171/171, with the allow-list pinned in both mapping test files —
including that an unknown spelling still falls back to QVariant, so the fallback
itself is not what regressed.

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

* feat(records): typed structs for C++ dependency wrappers

Closes the second record gap. The wrapper every C++ module actually gets for
its dependencies comes from the LEGACY generator (`--dep <name>=<lidl>`), not
the client-stub backend the previous commit taught about records — and there a
contract's `type Status { ... }` reached the consumer as an untyped bag:
QVariant on the Qt surface, LogosMap on the std/lp one. Worse than
inconvenient for a `bstr` field: the caller received the canonical
`{"_bytes": "..."}` envelope and had to know to unwrap it, while Rust and the
stub backend handed back real bytes.

Now, on all three api styles:

    struct Status { uint64_t port{}; std::vector<uint8_t> blob{}; };
    Status getStatus(logos::CallError* err = nullptr);
    std::string describeStatus(const Status& s, ...);
    std::vector<Status> listStatuses(...);

The struct is NESTED in the wrapper class (`InfoModule::Status`) because a
module consuming two deps that each declare a `Status` includes both wrappers
into one translation unit. Conversions are file-local statics in the generated
.cpp, so a Qt-free module's own TUs still never see QVariant or nlohmann.
Records reach parameters, returns, event callbacks, `[Record]` and
`{tstr: Record}` — at any depth, with bytes tagged throughout.

Same commit, the legacy path's half of the 64-bit fix: `lidlTypeExprToQtTypeName`
mapped BOTH int and uint to `int` ("wire-as-int for now"), so a `uint` method on
a dep reached a Qt consumer as a signed 32-bit value and a std/lp consumer as a
signed int64_t. Now qlonglong/qulonglong, matching the spelling the other half
of this PR gave the stub backend. `lpFromJsonExpr` grew the uint64_t branch it
needed — without it a mistyped payload THREW out of nlohmann's implicit
conversion instead of defaulting like every other scalar.

Verified by generating a contract with a record, a record-of-records, a `uint`
above 2^32 and a high-byte `bstr`, then COMPILING the output for qt/std/lp and
round-tripping the emitted conversions:
  - `{"_bytes":"gAH_"}` at every depth, decoding back to the same bytes
  - 4294967296 intact through both directions
  - garbage/missing fields default rather than throw
That compile is what caught the one real bug here: the container decode lambdas
declared `__m`/`__j`, shadowing the record decoder's own locals, so a
map-of-records field read from its own uninitialized local — it compiled with
nothing but a -Wuninitialized warning. Locals are `__acc`/`__src` now, pinned
by a test.

Also: 8 generator tests (one asserting an empty record set leaves every byte
of the output as it was), 179 total green; logos-test-modules builds and tests
green against this generator.

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

* fix(records): async record returns decoded a default-constructed struct

Two correctness holes in the record work, both silent, found while scoping the
cdylib provider side.

1. The async consumer overload emitted `qvariant_cast<Status>(v)` while the sync
   one emitted `StatusFromVariant(_result)`. The wire delivers a QVariantMap and
   no Q_DECLARE_METATYPE is emitted for the struct, so the cast does not fail —
   it returns a DEFAULT-CONSTRUCTED Status and the caller sees empty fields with
   no diagnostic. The sync path being correct is what makes it bad: the same
   call is right or wrong depending only on which overload the caller reached
   for. Async now decodes field by field through the same conversion.

   (The legacy dependency-wrapper generator already did this correctly — this
   was the experimental client-stub backend only.)

2. A record whose ONLY field is a tstr named `_bytes` is wire-identical to a
   canonical tagged byte string: `isTaggedBytes()` is checked before
   `is_object()` in both logos_codec.h and logos_json_convert.cpp, so such a
   record decodes as bytes and the struct silently disappears. The ambiguity is
   inherent to the tagged form — the codec's own comment says not to name a map
   key `_bytes` — but the generator can refuse to emit the one shape guaranteed
   to misdecode instead of leaving it to be found at runtime. Both front doors
   (the .lidl client-stub path and the --dep/--interface path) now reject it
   with a message naming the type and the fix.

   A second field disambiguates it (isTaggedBytes requires exactly one key), so
   that shape still generates — verified, not assumed.

181 tests, +2.

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

* feat(cdylib): records, [bstr], typed maps and nested composites on the C++ provider

The C++ cdylib backend could express scalars, `[scalar]`, `any` and an untyped
map. Everything else it rejected BY NAME — `[bstr]`, `[[int]]`, `{tstr: int}`,
and records, which the impl-header parser could not even declare because it
skipped `struct` outright. That is why the ext contract had to be Rust-only.

Four changes, in the order they matter:

  typeSupported()  recurses instead of whitelisting element names, which admits
                   [bstr], [[int]], [Record] and [{tstr: T}] in one rule; a
                   declared record is admitted; a map now REQUIRES a tstr key
                   (it used to `return true` for any map and then silently
                   flatten {int: tstr} to an untyped LogosMap, losing the key
                   type).
  lidlTypeToStdCdylib()  became total. Its `lidlTypeToStd` fallback answers
                   QVariantList / QVariantMap — Qt names in a Qt-FREE
                   translation unit — and only failed to appear because the
                   gate rejected everything that reached it. Widening the gate
                   made that fallback a live leak, so composites now recurse and
                   never reach it.
  <name>_types.h   new: the generated codec, recursive, with a FULL
                   specialization for std::vector<uint8_t> that wins over the
                   generic vector rule — which is what keeps a bstr tagged at
                   any depth instead of becoming a plain array of numbers. One
                   Codec specialization per declared record, field by field,
                   with the field path in the error.
  impl_header_parser  learned `struct` (two passes, because a record field may
                   name another record and the type mapper only answers Named()
                   for an already-registered name — one pass silently typed
                   `Blob inner;` as `any`), std::map<std::string, T>, and
                   recursion into vector elements so std::vector<Blob> is
                   [Blob] rather than falling through to `any`.

Records are only names the contract DECLARES: `void` is not a LIDL builtin, so
`-> void` arrives as Named("void"), and treating every Named as a record is the
exact trap that made the Rust generator emit `-> Void`.

Two things the interface JSON got wrong, both found by running it:

  - it spelled a record `Blob` and a `[Record]` `QList<Blob>`. Those are the
    CONSUMER's names, correct in a generated wrapper where the struct exists —
    but this JSON is the module's getMethods(), read by the host to marshal a
    QVariant, and there is no metatype called `Blob`. The host SIGSEGV'd on the
    first call to any record method. A record IS a variant map at that boundary;
    lidlTypeToQtWire() says so.
  - the types header emitted the structs. Header-first, the author owns them and
    the contract was derived from those very declarations, so it was a
    redefinition. It emits forward declarations and the codec.

Also: `jsonReturn` is set by the front end for any map return, which no longer
implies the C++ type IS nlohmann::json now that a typed map is
std::map<std::string, T> — checking the flag before the spelling emitted
`result.dump()` on a std::map. The spelling decides.

Scalars keep their nlohmann accessor verbatim rather than routing through the
codec: `.get<int64_t>()` TRUNCATES a float instead of throwing, and the
conformance matrix pins that leniency (hostile/int/fractional expects 3 from
3.7). Changing it would silently move behaviour something depends on.

The pinned-rejection test for [bstr] is INVERTED rather than deleted — the cell
it pinned still matters, only its answer changed — plus new tests for the
non-tstr map key rejection and for declared-vs-undeclared records. 183 tests.
Every existing module still builds; test_fullapi_cpp is unchanged.

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

* fix(records): only structs the API mentions become contract types

Teaching the impl-header parser to read `struct` (previous commit) published
EVERY struct in a header as a contract `type`. Two production modules already
carry private helpers:

  openmetrics-module      struct ModuleSource   (namespace scope, internal)
  logos-package-manager   struct PendingAction  (PRIVATE, inside the class)

Both were being published — a module's interface changing as a side effect of
an internal refactor, which is not something deriving a contract from a header
may do. PendingAction was published WRONG as well: its fields carry trailing
`// comments`, the field regex requires a line ending in ';', and the
unmatched fields were silently dropped. A record with a partial field list is
worse than no record, because it looks like a contract.

A struct now earns its place by appearing in a method or event signature —
transitively, since a published record's own fields may name others. Verified
on the real headers: package-manager and openmetrics publish zero types again,
while the ext provider keeps both Blob and Wrapper (Wrapper is reachable only
through Blob's use in a signature). Trailing comments are stripped before the
field match, so no field is dropped.

Two tests over a fixture carrying both an internal namespace-scope struct and a
private in-class one; 185 tests. test-modules and openmetrics both rebuild.

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

* docs(doctests): the generator round-trip now shows 64-bit ints and typed records

The two failing assertions in cpp-sdk-generator-roundtrip were documentation
asserting the OLD behaviour, and both changes are the point of this branch:

  int record(int id, …)          ->  qlonglong record(qulonglong id, …)
  QVariant translate(QVariant p) ->  Point translate(const Point& p, …)

`record`'s `id` is a `uint64_t` in the impl header, so the old signature was
handing a caller a SIGNED 32-bit value for a `uint` — the doc showed the bug.

The surrounding prose was wrong too, not just the expectations, so both blocks
are rewritten rather than patched:

  * Flow 3 now states the mapping as int->qlonglong / uint->qulonglong and says
    why (LIDL int/uint are int64_t/uint64_t in every other binding), pointing at
    `record` as the worked example.
  * The composite section claimed "records and optionals surface as QVariant".
    Records now generate a struct, `[Point]` a QList<Point> and `{tstr: Point}`
    a QMap<QString, Point>; maps of `any`, optionals and bare `any` still cross
    untyped and stay QVariant/QVariantMap — a record has a declared shape, those
    do not. The new text draws that line explicitly.

Expectations added for `struct Point` and `Point bounds(const QList<Point>&…)`
so the record path is pinned in the doc, not just described.

Verified the way CI runs it — `--release-for logos-cpp-sdk=feat/qt-64bit-numerics`,
which is what makes `{release}` resolve to this branch instead of master:
10 passed, 0 failed. (A plain local run builds master and is not
representative — that is why it still showed the old signatures.)

outputs/ regenerated; the diff also picks up unrelated pre-existing drift where
the committed Markdown had fallen behind the spec.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 17:24:49 -03:00

337 lines
15 KiB
C++

#include "legacy/legacy_main.h"
#include "experimental/lidl_gen_client.h"
#include "experimental/lidl_gen_cdylib.h"
#include "experimental/lidl_compat.h"
#include "experimental/impl_header_parser.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
int main(int argc, char* argv[])
{
// Check for --lidl / --from-header / --header-to-lidl mode before
// initializing QCoreApplication, since legacy_main creates its own.
bool hasLidl = false;
bool hasFromHeader = false;
bool hasHeaderToLidl = false;
for (int i = 1; i < argc; ++i) {
QString arg = QString::fromUtf8(argv[i]);
if (arg == "--lidl") hasLidl = true;
if (arg == "--from-header") hasFromHeader = true;
if (arg == "--header-to-lidl") hasHeaderToLidl = true;
}
// --header-to-lidl: the C++ frontend of the source -> LIDL -> bindings
// pipeline. Parse an impl header and emit ONLY its LIDL contract (no Qt
// glue / dispatch), so a module can publish a cheap `lidl` artifact that
// consumers (any language) turn into bindings without building the module.
if (hasHeaderToLidl) {
QCoreApplication app(argc, argv);
QTextStream err(stderr);
QTextStream out(stdout);
const QStringList args = app.arguments();
// Strip a leading '@' from path arguments — some build drivers pass
// `@/abs/path`. Matches the legacy_main path handling.
auto stripAt = [](QString p) { if (p.startsWith('@')) p.remove(0, 1); return p; };
const int idx = args.indexOf("--header-to-lidl");
if (idx + 1 >= args.size()) {
err << "Error: --header-to-lidl requires a path to the impl header\n";
return 1;
}
const QString headerPath = stripAt(args.at(idx + 1));
const int implClassIdx = args.indexOf("--impl-class");
if (implClassIdx == -1 || implClassIdx + 1 >= args.size()) {
err << "Error: --header-to-lidl requires --impl-class <ClassName>\n";
return 1;
}
const QString implClass = args.at(implClassIdx + 1);
const int metadataIdx = args.indexOf("--metadata");
if (metadataIdx == -1 || metadataIdx + 1 >= args.size()) {
err << "Error: --header-to-lidl requires --metadata <metadata.json>\n";
return 1;
}
const QString metadataPath = stripAt(args.at(metadataIdx + 1));
ImplParseResult pr = parseImplHeader(headerPath, implClass, metadataPath, err);
if (pr.hasError()) {
err << "Error parsing impl header: " << pr.error << "\n";
return 4;
}
const ModuleDecl& mod = pr.module;
// Output path: explicit -o/--output <file>, else <output-dir>/<name>.lidl,
// else <name>.lidl in the CWD.
QString outPath;
const int oIdx = args.indexOf("-o");
const int outputIdx = args.indexOf("--output");
const int outDirIdx = args.indexOf("--output-dir");
if (oIdx != -1 && oIdx + 1 < args.size()) {
outPath = stripAt(args.at(oIdx + 1));
} else if (outputIdx != -1 && outputIdx + 1 < args.size()) {
outPath = stripAt(args.at(outputIdx + 1));
} else if (outDirIdx != -1 && outDirIdx + 1 < args.size()) {
const QString d = stripAt(args.at(outDirIdx + 1));
QDir().mkpath(d);
outPath = QDir(d).filePath(qs(mod.name) + ".lidl");
} else {
outPath = qs(mod.name) + ".lidl";
}
QFile f(outPath);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
err << "Failed to write LIDL: " << outPath << "\n";
return 5;
}
f.write(lidlSerialize(mod).toUtf8());
f.close();
out << "Generated LIDL: " << outPath << " (" << mod.methods.size()
<< " methods, " << mod.events.size() << " events)\n";
out.flush();
return 0;
}
if (hasLidl || hasFromHeader) {
QCoreApplication app(argc, argv);
QTextStream err(stderr);
QTextStream out(stdout);
const QStringList args = app.arguments();
QString outputDir;
const int outDirIdx = args.indexOf("--output-dir");
if (outDirIdx != -1 && outDirIdx + 1 < args.size()) {
outputDir = args.at(outDirIdx + 1);
}
// --from-header mode: parse C++ impl header directly (no .lidl needed)
if (hasFromHeader) {
const int fromHeaderIdx = args.indexOf("--from-header");
if (fromHeaderIdx + 1 >= args.size()) {
err << "Error: --from-header requires a path to the impl header\n";
return 1;
}
QString headerPath = args.at(fromHeaderIdx + 1);
const int implClassIdx = args.indexOf("--impl-class");
if (implClassIdx == -1 || implClassIdx + 1 >= args.size()) {
err << "Error: --from-header requires --impl-class <ClassName>\n";
return 1;
}
QString implClass = args.at(implClassIdx + 1);
const int metadataIdx = args.indexOf("--metadata");
if (metadataIdx == -1 || metadataIdx + 1 >= args.size()) {
err << "Error: --from-header requires --metadata <metadata.json>\n";
return 1;
}
QString metadataPath = args.at(metadataIdx + 1);
// --impl-header: the include path for generated code (defaults to header filename)
QString implHeader;
const int implHeaderIdx = args.indexOf("--impl-header");
if (implHeaderIdx != -1 && implHeaderIdx + 1 < args.size()) {
implHeader = args.at(implHeaderIdx + 1);
} else {
implHeader = QFileInfo(headerPath).fileName();
}
const int backendIdx = args.indexOf("--backend");
if (backendIdx == -1 || backendIdx + 1 >= args.size()) {
err << "Error: --from-header requires --backend <qt>\n";
return 1;
}
QString backend = args.at(backendIdx + 1);
// Parse the impl header
ImplParseResult pr = parseImplHeader(headerPath, implClass, metadataPath, err);
if (pr.hasError()) {
err << "Error parsing impl header: " << pr.error << "\n";
return 4;
}
const ModuleDecl& mod = pr.module;
QString genDirPath = outputDir.isEmpty()
? QDir::current().filePath("generated")
: outputDir;
QDir().mkpath(genDirPath);
if (backend == "cdylib") {
// Cdylib authoring: the common module-impl C ABI exports +
// the uniform Qt-plugin glue (language-agnostic, forwards to
// the C symbols). See logos_module_impl.h in logos-protocol.
QString cdErr;
if (!lidlCdylibSupported(mod, &cdErr)) {
err << "Error: module not cdylib-eligible: " << cdErr << "\n";
return 10;
}
struct Out { QString file; QString content; };
QList<Out> outs;
// Always emitted, records or not: the exports TU and the events
// sidecar both reference the generated codec, and a module with
// no `type` decls still has containers to encode.
outs.append({qs(mod.name) + "_types.h", lidlMakeTypesHeaderCdylib(mod)});
outs.append({qs(mod.name) + "_module_impl.cpp",
lidlMakeModuleImplExports(mod, implClass, implHeader)});
if (!mod.events.empty())
outs.append({qs(mod.name) + "_events_cdylib.cpp",
lidlMakeEventsSourceCdylib(mod, implClass, implHeader)});
outs.append({qs(mod.name) + ".lidl", lidlSerialize(mod)});
for (const Out& o : outs) {
const QString abs = QDir(genDirPath).filePath(o.file);
QFile f(abs);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
err << "Failed to write: " << abs << "\n";
return 11;
}
f.write(o.content.toUtf8());
out << "Generated: " << abs << "\n";
}
out.flush();
return 0;
}
if (backend == "qt") {
err << "Error: Qt glue generation moved to logos-qt-generator "
"(logos-qt-sdk). Use it for --backend qt; this tool "
"keeps the Qt-free outputs (--header-to-lidl emits the "
".lidl sidecar).\n";
return 6;
}
err << "Error: --from-header supports --backend cdylib (Qt glue: logos-qt-generator)\n";
return 1;
}
// --lidl mode
const int lidlIdx = args.indexOf("--lidl");
if (lidlIdx + 1 >= args.size()) {
err << "Usage: " << QFileInfo(app.applicationFilePath()).fileName()
<< " --lidl /path/to/module.lidl [--output-dir /path] [--module-only]\n"
<< " " << QFileInfo(app.applicationFilePath()).fileName()
<< " --lidl /path/to/module.lidl --backend qt --impl-class Class --impl-header header.h [--output-dir /path]\n"
<< " " << QFileInfo(app.applicationFilePath()).fileName()
<< " --lidl /path/to/module.lidl --backend cdylib [--output-dir /path] (glue-only: C exports come from the module's own language backend)\n"
<< " " << QFileInfo(app.applicationFilePath()).fileName()
<< " --from-header src/impl.h --backend qt --impl-class Class --metadata metadata.json [--output-dir /path]\n";
return 1;
}
QString lidlPath = args.at(lidlIdx + 1);
// Provider glue mode: --backend qt --impl-class X --impl-header Y
const int backendIdx = args.indexOf("--backend");
if (backendIdx != -1) {
if (backendIdx + 1 >= args.size()) {
err << "Error: --backend requires an argument (e.g., qt)\n";
return 1;
}
QString backend = args.at(backendIdx + 1);
const int implClassIdx = args.indexOf("--impl-class");
const int implHeaderIdx = args.indexOf("--impl-header");
// Cdylib-from-LIDL (contract-first):
// - with no --impl-class: GLUE-ONLY — the C exports come from
// the module's own language backend (e.g. the Rust SDK's
// lidl-gen --provider); the glue only knows the C symbols.
// - with --impl-class/--impl-header: the FULL set — the C-ABI
// export wrapper around the named (hand-written, Qt-free)
// C++ impl class, plus the same uniform glue. The contract
// stays the .lidl; the author just implements the class.
if (backend == "cdylib") {
QFile f(lidlPath);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
err << "Error: cannot read " << lidlPath << "\n";
return 1;
}
LidlParseResult pr = lidlParse(QString::fromUtf8(f.readAll()));
if (pr.hasError()) {
err << "Error parsing " << lidlPath << ": " << pr.error
<< " (line " << pr.errorLine << ")\n";
return 4;
}
const ModuleDecl& mod = pr.module;
QString cdErr;
if (!lidlCdylibSupported(mod, &cdErr)) {
err << "Error: module not cdylib-eligible: " << cdErr << "\n";
return 10;
}
QString genDirPath = outputDir.isEmpty()
? QDir::current().filePath("generated")
: outputDir;
QDir().mkpath(genDirPath);
struct Out { QString file; QString content; };
QList<Out> outs;
if (implClassIdx != -1) {
if (implClassIdx + 1 >= args.size()) {
err << "Error: --impl-class requires a class name\n";
return 1;
}
const QString implClass = args.at(implClassIdx + 1);
QString implHeader;
if (implHeaderIdx != -1 && implHeaderIdx + 1 < args.size())
implHeader = args.at(implHeaderIdx + 1);
else
implHeader = qs(mod.name) + "_impl.h";
outs.append({qs(mod.name) + "_types.h", lidlMakeTypesHeaderCdylib(mod)});
outs.append({qs(mod.name) + "_module_impl.cpp",
lidlMakeModuleImplExports(mod, implClass, implHeader)});
if (!mod.events.empty())
outs.append({qs(mod.name) + "_events_cdylib.cpp",
lidlMakeEventsSourceCdylib(mod, implClass, implHeader)});
} else {
err << "Error: the uniform cdylib Qt glue is generated by "
"logos-qt-generator (logos-qt-sdk); this tool emits "
"the Qt-free C-ABI export wrapper, which requires "
"--impl-class.\n";
return 12;
}
for (const Out& o : outs) {
const QString abs = QDir(genDirPath).filePath(o.file);
QFile of(abs);
if (!of.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
err << "Failed to write: " << abs << "\n";
return 11;
}
of.write(o.content.toUtf8());
out << "Generated: " << abs << "\n";
}
out.flush();
return 0;
}
if (implClassIdx == -1 || implClassIdx + 1 >= args.size()) {
err << "Error: --backend " << backend << " requires --impl-class <ClassName>\n";
return 1;
}
if (implHeaderIdx == -1 || implHeaderIdx + 1 >= args.size()) {
err << "Error: --backend " << backend << " requires --impl-header <header.h>\n";
return 1;
}
QString implClass = args.at(implClassIdx + 1);
QString implHeader = args.at(implHeaderIdx + 1);
if (backend == "qt") {
err << "Error: Qt glue generation moved to logos-qt-generator "
"(logos-qt-sdk).\n";
return 6;
}
err << "Error: unsupported backend '" << backend << "' (supported: cdylib)\n";
return 1;
}
// Client stub mode (default)
bool moduleOnly = args.contains("--module-only");
return lidlGenerateClientStubs(lidlPath, outputDir, moduleOnly, out, err);
}
return legacy_main(argc, argv);
}