mirror of
https://github.com/logos-co/logos-cpp-sdk.git
synced 2026-08-31 17:51:07 +00:00
* 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>
548 lines
21 KiB
C++
548 lines
21 KiB
C++
#include <gtest/gtest.h>
|
|
#include <QTemporaryDir>
|
|
#include <algorithm>
|
|
#include "impl_header_parser.h"
|
|
#include <QCoreApplication>
|
|
#include <QDir>
|
|
#include <QFile>
|
|
#include <QTextStream>
|
|
|
|
// Helper: find the fixtures directory.
|
|
// 1. FIXTURES_DIR env var — set by CI to point to installed fixtures
|
|
// 2. FIXTURES_DIR compile define — set by CMake, works during ctest in nix sandbox
|
|
// 3. ../fixtures relative to binary — nix install layout ($out/bin/ + $out/fixtures/)
|
|
static QString fixturesDir()
|
|
{
|
|
// Environment variable takes priority (set by CI or user)
|
|
QByteArray envDir = qgetenv("FIXTURES_DIR");
|
|
if (!envDir.isEmpty() && QDir(envDir).exists())
|
|
return QString::fromUtf8(envDir);
|
|
|
|
#ifdef FIXTURES_DIR
|
|
if (QDir(FIXTURES_DIR).exists())
|
|
return QString(FIXTURES_DIR);
|
|
#endif
|
|
|
|
// Installed layout: $out/bin/experimental_tests + $out/fixtures/
|
|
QString binDir = QCoreApplication::applicationDirPath();
|
|
if (!binDir.isEmpty()) {
|
|
QString installed = QDir::cleanPath(binDir + "/../fixtures");
|
|
if (QDir(installed).exists())
|
|
return installed;
|
|
}
|
|
return QDir::currentPath() + "/fixtures";
|
|
}
|
|
|
|
class ImplHeaderParserTest : public ::testing::Test {
|
|
protected:
|
|
QString errOutput;
|
|
QTextStream err{&errOutput};
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Basic parsing
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, ParsesSampleImpl)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/sample_impl.h",
|
|
"SampleModuleImpl",
|
|
fixturesDir() + "/sample_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
// Metadata from JSON
|
|
EXPECT_EQ(r.module.name, "sample_module");
|
|
EXPECT_EQ(r.module.version, "1.2.3");
|
|
EXPECT_EQ(r.module.description, "A sample module for testing");
|
|
EXPECT_EQ(r.module.category, "testing");
|
|
ASSERT_EQ(r.module.depends.size(), 2);
|
|
EXPECT_EQ(r.module.depends[0], "dep_a");
|
|
|
|
// Methods — should find all public methods, skip ctor/dtor/private
|
|
EXPECT_GE(r.module.methods.size(), 10);
|
|
}
|
|
|
|
TEST_F(ImplHeaderParserTest, MethodTypes)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/sample_impl.h",
|
|
"SampleModuleImpl",
|
|
fixturesDir() + "/sample_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
// Find specific methods and check their types
|
|
auto findMethod = [&](const std::string& name) -> const MethodDecl* {
|
|
for (const auto& m : r.module.methods)
|
|
if (m.name == name) return &m;
|
|
return nullptr;
|
|
};
|
|
|
|
// std::string greet(const std::string& name) → tstr
|
|
auto greet = findMethod("greet");
|
|
ASSERT_NE(greet, nullptr);
|
|
EXPECT_EQ(greet->returnType.name, "tstr");
|
|
ASSERT_EQ(greet->params.size(), 1);
|
|
EXPECT_EQ(greet->params[0].name, "name");
|
|
EXPECT_EQ(greet->params[0].type.name, "tstr");
|
|
|
|
// bool isValid(const std::string& input) → bool
|
|
auto isValid = findMethod("isValid");
|
|
ASSERT_NE(isValid, nullptr);
|
|
EXPECT_EQ(isValid->returnType.name, "bool");
|
|
|
|
// int64_t getCount() → int
|
|
auto getCount = findMethod("getCount");
|
|
ASSERT_NE(getCount, nullptr);
|
|
EXPECT_EQ(getCount->returnType.name, "int");
|
|
EXPECT_TRUE(getCount->params.empty());
|
|
|
|
// uint64_t getSize() → uint
|
|
auto getSize = findMethod("getSize");
|
|
ASSERT_NE(getSize, nullptr);
|
|
EXPECT_EQ(getSize->returnType.name, "uint");
|
|
|
|
// double getScore() → float64
|
|
auto getScore = findMethod("getScore");
|
|
ASSERT_NE(getScore, nullptr);
|
|
EXPECT_EQ(getScore->returnType.name, "float64");
|
|
|
|
// void doNothing() → void
|
|
auto doNothing = findMethod("doNothing");
|
|
ASSERT_NE(doNothing, nullptr);
|
|
EXPECT_EQ(doNothing->returnType.name, "void");
|
|
|
|
// std::vector<std::string> getNames() → [tstr]
|
|
auto getNames = findMethod("getNames");
|
|
ASSERT_NE(getNames, nullptr);
|
|
EXPECT_EQ(getNames->returnType.kind, TypeExpr::Array);
|
|
EXPECT_EQ(getNames->returnType.elements[0].name, "tstr");
|
|
|
|
// std::vector<uint8_t> getData() → bstr
|
|
auto getData = findMethod("getData");
|
|
ASSERT_NE(getData, nullptr);
|
|
EXPECT_EQ(getData->returnType.name, "bstr");
|
|
|
|
// std::vector<int64_t> getIds() → [int]
|
|
auto getIds = findMethod("getIds");
|
|
ASSERT_NE(getIds, nullptr);
|
|
EXPECT_EQ(getIds->returnType.kind, TypeExpr::Array);
|
|
EXPECT_EQ(getIds->returnType.elements[0].name, "int");
|
|
|
|
// std::string combine(const std::string& a, const std::string& b, int64_t count)
|
|
auto combine = findMethod("combine");
|
|
ASSERT_NE(combine, nullptr);
|
|
EXPECT_EQ(combine->returnType.name, "tstr");
|
|
ASSERT_EQ(combine->params.size(), 3);
|
|
EXPECT_EQ(combine->params[0].name, "a");
|
|
EXPECT_EQ(combine->params[1].name, "b");
|
|
EXPECT_EQ(combine->params[2].name, "count");
|
|
EXPECT_EQ(combine->params[2].type.name, "int");
|
|
}
|
|
|
|
TEST_F(ImplHeaderParserTest, SkipsPrivateMethods)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/sample_impl.h",
|
|
"SampleModuleImpl",
|
|
fixturesDir() + "/sample_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
for (const auto& m : r.module.methods) {
|
|
EXPECT_NE(m.name, "internalHelper") << "Private method should not be parsed";
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Empty class
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, EmptyClass)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/empty_class_impl.h",
|
|
"EmptyClassImpl",
|
|
fixturesDir() + "/empty_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
EXPECT_TRUE(r.module.methods.empty());
|
|
// Should have a warning in err output
|
|
EXPECT_TRUE(errOutput.contains("Warning"));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Complex class with access specifier changes
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, ComplexAccessSpecifiers)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/complex_impl.h",
|
|
"ComplexModuleImpl",
|
|
fixturesDir() + "/empty_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
auto findMethod = [&](const std::string& name) -> const MethodDecl* {
|
|
for (const auto& m : r.module.methods)
|
|
if (m.name == name) return &m;
|
|
return nullptr;
|
|
};
|
|
|
|
// First public section
|
|
EXPECT_NE(findMethod("firstMethod"), nullptr);
|
|
// Second public section (after protected)
|
|
EXPECT_NE(findMethod("secondMethod"), nullptr);
|
|
EXPECT_NE(findMethod("thirdMethod"), nullptr);
|
|
// Protected method should be skipped
|
|
EXPECT_EQ(findMethod("protectedHelper"), nullptr);
|
|
// Private method should be skipped
|
|
EXPECT_EQ(findMethod("privateHelper"), nullptr);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Error cases
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// A struct in an impl header becomes a contract `type` — but ONLY if the API
|
|
// mentions it. A header routinely declares private helpers, and publishing
|
|
// those would change the module's interface as a side effect of an internal
|
|
// refactor. Verified against two real modules: openmetrics' `ModuleSource` and
|
|
// the package manager's in-class `PendingAction` were both being published.
|
|
TEST_F(ImplHeaderParserTest, OnlyApiReferencedStructsBecomeRecords)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/records_impl.h",
|
|
"RecordsImpl",
|
|
fixturesDir() + "/records_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
std::vector<std::string> names;
|
|
for (const auto& t : r.module.types) names.push_back(t.name);
|
|
std::sort(names.begin(), names.end());
|
|
|
|
// Blob is named directly; Wrapper too. Internal and Helper are not.
|
|
ASSERT_EQ(names.size(), 2u) << "published: " << [&]{
|
|
std::string j; for (const auto& n : names) j += n + " "; return j; }();
|
|
EXPECT_EQ(names[0], "Blob");
|
|
EXPECT_EQ(names[1], "Wrapper");
|
|
|
|
// A field with a trailing comment must NOT be silently dropped: a record
|
|
// published with a partial field list looks like a contract and is not one.
|
|
for (const auto& t : r.module.types) {
|
|
if (t.name != "Blob") continue;
|
|
ASSERT_EQ(t.fields.size(), 3u);
|
|
EXPECT_EQ(t.fields[2].name, "payload");
|
|
EXPECT_EQ(t.fields[2].type.name, "bstr");
|
|
}
|
|
}
|
|
|
|
// The closure is transitive: a record reaches the contract because something
|
|
// the API names refers to it, however indirectly.
|
|
TEST_F(ImplHeaderParserTest, RecordsReachableOnlyThroughAnotherRecordAreKept)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/records_impl.h",
|
|
"RecordsImpl",
|
|
fixturesDir() + "/records_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
// Wrapper's own fields name Blob; both survive even though a signature
|
|
// could have named only one of them.
|
|
bool sawWrapper = false;
|
|
for (const auto& t : r.module.types) {
|
|
if (t.name != "Wrapper") continue;
|
|
sawWrapper = true;
|
|
ASSERT_EQ(t.fields.size(), 2u);
|
|
EXPECT_EQ(t.fields[0].type.name, "Blob");
|
|
EXPECT_EQ(t.fields[1].type.elements.at(0).name, "Blob");
|
|
}
|
|
EXPECT_TRUE(sawWrapper);
|
|
}
|
|
|
|
TEST_F(ImplHeaderParserTest, MissingHeaderFile)
|
|
{
|
|
auto r = parseImplHeader(
|
|
"/nonexistent/path.h",
|
|
"Foo",
|
|
fixturesDir() + "/sample_metadata.json",
|
|
err);
|
|
EXPECT_TRUE(r.hasError());
|
|
EXPECT_TRUE(r.error.contains("Failed to open header"));
|
|
}
|
|
|
|
TEST_F(ImplHeaderParserTest, MissingMetadataFile)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/sample_impl.h",
|
|
"SampleModuleImpl",
|
|
"/nonexistent/metadata.json",
|
|
err);
|
|
EXPECT_TRUE(r.hasError());
|
|
EXPECT_TRUE(r.error.contains("Failed to open metadata"));
|
|
}
|
|
|
|
TEST_F(ImplHeaderParserTest, WrongClassName)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/sample_impl.h",
|
|
"NonExistentClass",
|
|
fixturesDir() + "/sample_metadata.json",
|
|
err);
|
|
// Not an error per se, but should find zero methods and warn
|
|
ASSERT_FALSE(r.hasError());
|
|
EXPECT_TRUE(r.module.methods.empty());
|
|
EXPECT_TRUE(errOutput.contains("Warning"));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// LogosMap / LogosList, Qt collections, metadata events, emitEvent detection
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, UniversalTypesAndMetadataEvents)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/universal_impl.h",
|
|
"UniversalImpl",
|
|
fixturesDir() + "/universal_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
EXPECT_EQ(r.module.name, "universal_mod");
|
|
EXPECT_EQ(r.module.version, "2.0.0");
|
|
|
|
ASSERT_EQ(r.module.events.size(), 1);
|
|
EXPECT_EQ(r.module.events[0].name, "onReady");
|
|
// Optional per-event description carried from metadata.json events[].
|
|
EXPECT_EQ(r.module.events[0].description, "Fired once the module is ready.");
|
|
ASSERT_EQ(r.module.events[0].params.size(), 1);
|
|
EXPECT_EQ(r.module.events[0].params[0].name, "info");
|
|
EXPECT_EQ(r.module.events[0].params[0].type.name, "tstr");
|
|
|
|
auto findMethod = [&](const std::string& name) -> const MethodDecl* {
|
|
for (const auto& m : r.module.methods)
|
|
if (m.name == name) return &m;
|
|
return nullptr;
|
|
};
|
|
|
|
// The fixture declares a `std::function<…> emitEvent` member. The old
|
|
// legacy hook treated it specially; now such members are simply skipped
|
|
// and never mistaken for a callable method.
|
|
EXPECT_EQ(findMethod("emitEvent"), nullptr);
|
|
|
|
auto fetchMap = findMethod("fetchMap");
|
|
ASSERT_NE(fetchMap, nullptr);
|
|
EXPECT_EQ(fetchMap->returnType.kind, TypeExpr::Map);
|
|
EXPECT_TRUE(fetchMap->jsonReturn);
|
|
|
|
auto fetchList = findMethod("fetchList");
|
|
ASSERT_NE(fetchList, nullptr);
|
|
EXPECT_EQ(fetchList->returnType.kind, TypeExpr::Array);
|
|
EXPECT_EQ(fetchList->returnType.elements[0].name, "any");
|
|
EXPECT_TRUE(fetchList->jsonReturn);
|
|
|
|
auto asVariantMap = findMethod("asVariantMap");
|
|
ASSERT_NE(asVariantMap, nullptr);
|
|
EXPECT_EQ(asVariantMap->returnType.kind, TypeExpr::Map);
|
|
EXPECT_FALSE(asVariantMap->jsonReturn);
|
|
|
|
auto listNames = findMethod("listNames");
|
|
ASSERT_NE(listNames, nullptr);
|
|
EXPECT_EQ(listNames->returnType.kind, TypeExpr::Array);
|
|
EXPECT_EQ(listNames->returnType.elements[0].name, "tstr");
|
|
EXPECT_FALSE(listNames->jsonReturn);
|
|
|
|
auto anyList = findMethod("anyList");
|
|
ASSERT_NE(anyList, nullptr);
|
|
EXPECT_EQ(anyList->returnType.kind, TypeExpr::Array);
|
|
EXPECT_EQ(anyList->returnType.elements[0].name, "any");
|
|
EXPECT_FALSE(anyList->jsonReturn);
|
|
|
|
auto fetchResult = findMethod("fetchResult");
|
|
ASSERT_NE(fetchResult, nullptr);
|
|
EXPECT_EQ(fetchResult->returnType.kind, TypeExpr::Primitive);
|
|
EXPECT_EQ(fetchResult->returnType.name, "result");
|
|
EXPECT_FALSE(fetchResult->jsonReturn);
|
|
EXPECT_TRUE(fetchResult->resultReturn);
|
|
|
|
auto fetchResultNodiscard = findMethod("fetchResultNodiscard");
|
|
ASSERT_NE(fetchResultNodiscard, nullptr);
|
|
EXPECT_EQ(fetchResultNodiscard->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultNodiscard->resultReturn);
|
|
|
|
auto fetchResultStatic = findMethod("fetchResultStatic");
|
|
ASSERT_NE(fetchResultStatic, nullptr);
|
|
EXPECT_EQ(fetchResultStatic->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultStatic->resultReturn);
|
|
|
|
auto fetchResultNodiscardStatic = findMethod("fetchResultNodiscardStatic");
|
|
ASSERT_NE(fetchResultNodiscardStatic, nullptr);
|
|
EXPECT_EQ(fetchResultNodiscardStatic->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultNodiscardStatic->resultReturn);
|
|
|
|
auto fetchResultStaticNodiscard = findMethod("fetchResultStaticNodiscard");
|
|
ASSERT_NE(fetchResultStaticNodiscard, nullptr);
|
|
EXPECT_EQ(fetchResultStaticNodiscard->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultStaticNodiscard->resultReturn);
|
|
|
|
auto fetchResultMultiAttr = findMethod("fetchResultMultiAttr");
|
|
ASSERT_NE(fetchResultMultiAttr, nullptr);
|
|
EXPECT_EQ(fetchResultMultiAttr->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultMultiAttr->resultReturn);
|
|
|
|
auto fetchResultInlineStatic = findMethod("fetchResultInlineStatic");
|
|
ASSERT_NE(fetchResultInlineStatic, nullptr);
|
|
EXPECT_EQ(fetchResultInlineStatic->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultInlineStatic->resultReturn);
|
|
|
|
auto fetchResultConsteval = findMethod("fetchResultConsteval");
|
|
ASSERT_NE(fetchResultConsteval, nullptr);
|
|
EXPECT_EQ(fetchResultConsteval->returnType.name, "result");
|
|
EXPECT_TRUE(fetchResultConsteval->resultReturn);
|
|
|
|
for (const auto& m : r.module.methods) {
|
|
EXPECT_NE(m.name, "void") << "Keyword should not appear as method name";
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Event doc comments: `///` above a `logos_events:` declaration becomes the
|
|
// event's description (same capture rules as methods: doc-comments only,
|
|
// adjacent-only, multi-line joined with \n).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, EventDocCommentsFromHeader)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/documented_events_impl.h",
|
|
"DocumentedEventsImpl",
|
|
fixturesDir() + "/documented_events_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
ASSERT_EQ(r.module.events.size(), 3);
|
|
|
|
// Multi-line `///` doc comment: the two lines are joined with a newline.
|
|
EXPECT_EQ(r.module.events[0].name, "userLoggedIn");
|
|
EXPECT_EQ(r.module.events[0].description,
|
|
"Fired once the user has authenticated.\n"
|
|
"Carries the freshly issued session token.");
|
|
ASSERT_EQ(r.module.events[0].params.size(), 2);
|
|
EXPECT_EQ(r.module.events[0].params[0].name, "userId");
|
|
EXPECT_EQ(r.module.events[0].params[1].name, "token");
|
|
|
|
// A plain `//` comment is not a doc comment → no description captured.
|
|
EXPECT_EQ(r.module.events[1].name, "heartbeat");
|
|
EXPECT_TRUE(r.module.events[1].description.empty());
|
|
|
|
// Single-line `///` doc comment.
|
|
EXPECT_EQ(r.module.events[2].name, "shutdown");
|
|
EXPECT_EQ(r.module.events[2].description, "Single-line documented event.");
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Issue #76: a section specifier and a declaration on the *same* physical
|
|
// line (`logos_events : void foo();`, as clang-format / prettier produce)
|
|
// must be parsed identically to the newline-separated form. The code after
|
|
// the colon must not be discarded.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
TEST_F(ImplHeaderParserTest, SameLineSectionSpecifiers)
|
|
{
|
|
auto r = parseImplHeader(
|
|
fixturesDir() + "/same_line_events_impl.h",
|
|
"SameLineEventsImpl",
|
|
fixturesDir() + "/same_line_events_metadata.json",
|
|
err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
auto findEvent = [&](const std::string& name) -> const EventDecl* {
|
|
for (const auto& e : r.module.events)
|
|
if (e.name == name) return &e;
|
|
return nullptr;
|
|
};
|
|
auto findMethod = [&](const std::string& name) -> const MethodDecl* {
|
|
for (const auto& m : r.module.methods)
|
|
if (m.name == name) return &m;
|
|
return nullptr;
|
|
};
|
|
|
|
// The exact prettier form from the issue:
|
|
// logos_events : void versionReady(const std::string &version);
|
|
// Previously the prototype after the colon was discarded entirely.
|
|
const EventDecl* versionReady = findEvent("versionReady");
|
|
ASSERT_NE(versionReady, nullptr)
|
|
<< "Same-line `logos_events :` prototype must still be parsed";
|
|
ASSERT_EQ(versionReady->params.size(), 1);
|
|
EXPECT_EQ(versionReady->params[0].name, "version");
|
|
EXPECT_EQ(versionReady->params[0].type.name, "tstr");
|
|
// The `///` doc comment above the collapsed line must attach: in the
|
|
// same-line form there is nowhere else for it to go, so documentation
|
|
// must not be formatting-dependent either.
|
|
EXPECT_EQ(versionReady->description, "Fired once the latest version is known.");
|
|
|
|
// An event declared after the section is already open, also same-line.
|
|
const EventDecl* downloadProgress = findEvent("downloadProgress");
|
|
ASSERT_NE(downloadProgress, nullptr);
|
|
ASSERT_EQ(downloadProgress->params.size(), 2);
|
|
EXPECT_EQ(downloadProgress->params[0].name, "id");
|
|
EXPECT_EQ(downloadProgress->params[0].type.name, "tstr");
|
|
EXPECT_EQ(downloadProgress->params[1].name, "percent");
|
|
EXPECT_EQ(downloadProgress->params[1].type.name, "int");
|
|
|
|
// The newline-separated form keeps working alongside the collapsed form.
|
|
EXPECT_NE(findEvent("shutdown"), nullptr);
|
|
|
|
// Exactly the three events above — no phantom or dropped entries.
|
|
EXPECT_EQ(r.module.events.size(), 3);
|
|
|
|
// The symmetric case: `public : <decl>` on one line must surface the
|
|
// method too (the access specifier no longer swallows the declaration).
|
|
const MethodDecl* greet = findMethod("greet");
|
|
ASSERT_NE(greet, nullptr)
|
|
<< "Same-line `public:` declaration must still be parsed";
|
|
EXPECT_EQ(greet->returnType.name, "tstr");
|
|
ASSERT_EQ(greet->params.size(), 1);
|
|
EXPECT_EQ(greet->params[0].name, "name");
|
|
EXPECT_EQ(greet->params[0].type.name, "tstr");
|
|
|
|
// The same-line events must land in events[], never leak into methods[].
|
|
EXPECT_EQ(findMethod("versionReady"), nullptr);
|
|
EXPECT_EQ(findMethod("downloadProgress"), nullptr);
|
|
}
|
|
|
|
|
|
TEST_F(ImplHeaderParserTest, ParsesMultiLineSignature)
|
|
{
|
|
QTemporaryDir dir;
|
|
ASSERT_TRUE(dir.isValid());
|
|
const QString hp = dir.filePath("ml_impl.h");
|
|
{
|
|
QFile f(hp);
|
|
ASSERT_TRUE(f.open(QIODevice::WriteOnly | QIODevice::Text));
|
|
f.write(
|
|
"#pragma once\n"
|
|
"#include <string>\n"
|
|
"class MlImpl {\n"
|
|
"public:\n"
|
|
" std::string single(const std::string& a);\n"
|
|
" std::string wrapped(const std::string& first,\n"
|
|
" const std::string& second);\n"
|
|
"};\n");
|
|
}
|
|
auto r = parseImplHeader(hp, "MlImpl",
|
|
fixturesDir() + "/sample_metadata.json", err);
|
|
ASSERT_FALSE(r.hasError()) << r.error.toStdString();
|
|
|
|
QStringList names;
|
|
for (const auto& m : r.module.methods) names << QString::fromStdString(m.name);
|
|
EXPECT_TRUE(names.contains("single"));
|
|
EXPECT_TRUE(names.contains("wrapped"))
|
|
<< "got: " << names.join(",").toStdString();
|
|
}
|