diff --git a/docs/cpp-classes.md b/docs/cpp-classes.md index 5004e0d7d..e2954e1e9 100644 --- a/docs/cpp-classes.md +++ b/docs/cpp-classes.md @@ -44,6 +44,8 @@ virtual only as in C++: | Method | What it is | | --- | --- | +| `@virtual name(...): T;` | a C++ virtual method, whose slot the compiler numbers for the target (see "One binding for every target") | +| `@destructor name(): void;` | the C++ virtual destructor: one slot under MSVC, two under the Itanium ABI; it can't be called | | `@slot(N) name(...): T;` | a C++ virtual method: slot N of the vtable, counted from 0 with the base classes' slots | | `name(...): T;` overriding a base class's `@slot` method | the same slot, as in C++ (`@slot` may be repeated, with the same number) | | `@linkname("symbol") name(...): T;` | a C++ non-virtual method, called by its (mangled) symbol as `symbol(this, args...)` | @@ -61,6 +63,55 @@ reads the same. (A class whose virtual methods have bodies is the other way roun Fields declared on the class are the C++ object's fields after the vtable pointer, laid out like a tuple's. +## One binding for every target: `@virtual` + +`@slot(N)` numbers are the target's: MSVC and the Itanium ABI (g++, clang on Linux, macOS, +MinGW) lay out the same C++ class differently. With `@virtual`, the compiler numbers the slots +itself, as the target's C++ compiler does, so one `.ts` file serves every target: + +```ts +@cpp +class Shape { // class Shape { + @destructor destroy(): void; // virtual ~Shape(); + @virtual area(): s32; // virtual int area() = 0; + @virtual scale(by: s32): void; // virtual void scale(int by) = 0; + @virtual scale(by: f64): void; // virtual void scale(double by) = 0; +} // }; + +@cpp +class Circle extends Shape { // class Circle : public Shape { + @virtual radius(): s32; // virtual int radius(); + @virtual area(): s32; // int area() override; +} // }; +``` + +| | MSVC | Itanium | +| --- | --- | --- | +| a base class's slots | first | first | +| a virtual destructor | one slot (the scalar deleting destructor) | two slots (the complete and the deleting destructor) | +| overloads of one name | together, where the first is declared, in reverse declaration order | in declaration order | +| a method with the name and parameter types of a base class's virtual method | that method's slot (an override) | the same | + +Above, MSVC gives `Shape` the slots `~Shape` 0, `area` 1, `scale(double)` 2, `scale(int)` 3, and +the Itanium ABI `~Shape` 0 and 1, `area` 2, `scale(int)` 3, `scale(double)` 4. `Circle.radius` is +4 under MSVC and 5 under Itanium, and `Circle.area` keeps `Shape.area`'s slot on both. + +So a class using `@virtual` declares **every** virtual method it adds, in the C++ header's order, +the protected and private ones too (a slot left out shifts the next ones); `tsbindgen +--virtual-slots` writes it that way. The rules: + +- a class numbers its new virtual methods with `@virtual` or with `@slot(N)`, not both (an + override may still name its base class's slot with `@slot(N)`); +- the base class's slots must all be known: its own virtual methods are `@virtual`, or it says + how many slots it has with `@vtablesize(N)` on the class (for a base bound by hand with + `@slot(N)`, which may leave slots out); +- `@slot(N)` still works as before, and wins over `@virtual` on the same method: the escape for a + vtable no rule above describes. + +A `@cpp` class exported from a module carries its slots, its `@destructor` and its +`@vtablesize(N)` in its declarations, so an importing module can extend it with `@virtual` +methods of its own. + ## Rules The compiler rejects anything that would add a slot, run code of its own, or ask the object what @@ -69,9 +120,12 @@ errors and not warnings. | Not allowed | Why | | --- | --- | -| a method without a body and without `@slot`, `@linkname` or `@cppname`, overriding nothing | it's neither a slot nor a symbol: a forgotten `@slot` | -| an `abstract` method without `@slot` | it is virtual, so it needs its slot | -| `@slot` on a method of an ordinary class | an ordinary class's vtable is tslang's own | +| a method without a body and without `@virtual`, `@slot`, `@linkname` or `@cppname`, overriding nothing | it's neither a slot nor a symbol: a forgotten `@virtual` | +| an `abstract` method without `@virtual` or `@slot` | it is virtual, so it needs its slot | +| `@virtual`, `@destructor` or `@slot` on a method of an ordinary class, `@vtablesize` on one | an ordinary class's vtable is tslang's own | +| new virtual methods with both `@virtual` and `@slot(N)` in one class | `@virtual` numbers every new slot of the class | +| `@virtual` in a class extending one whose size isn't known (its slots are `@slot(N)`, without `@vtablesize(N)`) | the new slots would start at an unknown slot | +| a call of a `@destructor` method | MSVC's slot is the deleting destructor, taking flags; the Itanium ABI's first destroys without freeing | | a constructor or a field initializer, in a class none of whose virtual methods has a body | the objects and their code are C++'s (see "Implementing C++ methods") | | static members, `get`/`set` accessors, `accessor` fields | they would take vtable slots | | `implements` | an implemented interface takes a slot | @@ -106,9 +160,14 @@ counts it: clang computes for the target, and each non-virtual method's `@cppname` declaration (its `@linkname` symbol when `@cppname` can't spell it or mangles it otherwise) (README, "C++ classes"): `tsbindgen nvrhi.hpp --target x86_64-pc-windows-msvc --filter 'nvrhi::I*' -- -std=c++17`. +With `--virtual-slots` it writes `@virtual` and `@destructor` instead of this target's `@slot(N)`, +declaring the virtual methods that aren't public too: one binding for every target. A class with +a virtual method it can't declare (a variadic one, one taking a type it can't map), and every class +extending it, keeps this target's `@slot(N)`, with a comment saying why. Writing one by hand: -- **Slot numbers.** Take them from the compiler, not by counting: MSVC prints a class's vtable +- **Slot numbers.** Prefer `@virtual` (above), declaring every virtual method in the header's + order. For `@slot(N)`, take them from the compiler, not by counting: MSVC prints a class's vtable with `cl /c /Zs /d1reportSingleClassLayout file.cpp`; clang (Itanium) with `clang++ -S -emit-llvm -o /dev/null -Xclang -fdump-vtable-layouts file.cpp`, for a class whose vtable the file emits (it defines the first virtual method that isn't inline), where slot N is diff --git a/tslang/include/TsClangImporter/BindingModel.h b/tslang/include/TsClangImporter/BindingModel.h index f45aadb6c..7f57dc32b 100644 --- a/tslang/include/TsClangImporter/BindingModel.h +++ b/tslang/include/TsClangImporter/BindingModel.h @@ -100,6 +100,13 @@ struct Method TsType result; bool nonTrivialReturn = false; // returns a record with a destructor or a copy constructor std::string skipReason; // non-empty: left out, with a `// skipped:` line in its place + // a virtual method that adds a slot: printed @virtual with --virtual-slots (slot is the target's) + bool isVirtual = false; + // the virtual destructor that adds its slots, printed @destructor with --virtual-slots only + bool destructor = false; + // `protected` or `private`: a virtual method that isn't public, which only --virtual-slots + // declares (its slot shifts the next ones); empty for a public one + std::string access; }; struct Decl @@ -125,6 +132,9 @@ struct Decl std::string base; // CppClass: the key of the base class, or empty std::vector methods; // CppClass: the methods it introduces, in declaration order std::string fieldsSkipReason; // CppClass: non-empty when its fields aren't declared + // CppClass: why its slots can't be numbered with @virtual - a virtual method that adds a slot + // and can't be declared; empty when every one is in `methods` + std::string virtualSlotsReason; }; struct HeaderModel diff --git a/tslang/include/TsClangImporter/BindingPrinter.h b/tslang/include/TsClangImporter/BindingPrinter.h index ff5a53e8b..ce17b5684 100644 --- a/tslang/include/TsClangImporter/BindingPrinter.h +++ b/tslang/include/TsClangImporter/BindingPrinter.h @@ -19,6 +19,10 @@ struct PrintOptions std::string namespaceName; // --namespace: wrap in `namespace N { export ... }`, with @linkname std::string stripPrefix; // --strip-prefix: removed from the TS names (needs a namespace) std::vector headerLines; // printed first, each as a `//` comment + // --virtual-slots: a C++ class's virtual methods @virtual, its destructor @destructor, which + // tslang numbers for the target compiled for: one binding for every target. A class with a + // virtual method that can't be declared (or extending one) keeps this target's @slot(N). + bool virtualSlots = false; }; struct PrintResult diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index cfa4f70c7..92913922b 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -474,6 +474,16 @@ // @slot(N) on a method of a @cpp class: a C++ virtual method, slot N of the vtable (counted // from 0, a base class's slots included); a method without it isn't virtual (see MethodInfo::cppSlot) #define CPP_SLOT "slot" +// @virtual on a method of a @cpp class: a C++ virtual method whose slot the compiler numbers for the +// target's C++ ABI from the declaration order, as the C++ compiler does (mlirGenClassCppVirtualSlots). +// Its class declares every virtual method of its own, in the C++ header's order. +#define CPP_VIRTUAL "virtual" +// @destructor on a method of a @cpp class: the C++ virtual destructor - one slot under MSVC, two under +// the Itanium ABI. It can't be called: the two ABIs call it differently. +#define CPP_DESTRUCTOR "destructor" +// @vtablesize(N) on a @cpp class: its vtable has N slots, a base class's included, so a class extending +// it numbers its @virtual methods from N. Written into __decls for a class whose size is known. +#define CPP_VTABLE_SIZE "vtablesize" // The name of a C++ overload after the first one declared, `write#1` (see mlirGenClassCppOverloadNames) #define CPP_OVERLOAD_SEPARATOR "#" // On a call (CallIndirect, then CallInternal or Invoke): the index of the argument that is the hidden diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 58aef52ff..5a4ca6f7a 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -172,6 +172,8 @@ struct MethodInfo // @slot(N): the vtable slot of a @cpp method, -1 without @slot (a non-virtual method, or // one overriding a base class's slot by name) int cppSlot = -1; + // @destructor: the C++ virtual destructor of a @cpp class, which can't be called + bool isCppDestructor = false; // a slot of a @cpp class's vtable that no method names (ClassInfo::getVirtualTable) bool isCppSlotGap = false; // `@keeps`, `@borrows`, `@lends` (OWN_DECLARED_KEEPS_ATTR_NAME): argument indices, `this` 0, for @@ -893,6 +895,11 @@ struct ClassInfo // two @cpp methods in one slot, or an override's @slot not its base's: found by // getVirtualTable, which can't report it, and reported by its caller std::string cppSlotConflict; + // a @cpp class's vtable: its number of slots, a base class's included, when every one is known + // (its virtual methods are @virtual, or it says @vtablesize(N)), else -1; and the slot of its + // virtual destructor, its own or a base class's, -1 without one (mlirGenClassCppVirtualSlots) + int cppVTableSize = -1; + int cppDestructorSlot = -1; ProcessingStages processingAtEvaluation; ProcessingStages processing; // the module `processing` was reached in: a discovery module is thrown away with what it holds diff --git a/tslang/include/TypeScript/TargetInfo.h b/tslang/include/TypeScript/TargetInfo.h index cf939306e..3ff793c61 100644 --- a/tslang/include/TypeScript/TargetInfo.h +++ b/tslang/include/TypeScript/TargetInfo.h @@ -31,6 +31,9 @@ struct TargetInfo // MSVC C++ member functions are __thiscall on 32-bit x86 (`this` in ECX), not the plain C // convention a class method is called with, so a @cpp class can't call them. bool memberCallsUseThiscall = false; + // C++ vtables are laid out as MSVC lays them out (overloads grouped, one destructor slot), not as + // the Itanium ABI does (mlirGenClassCppVirtualSlots) + bool msvcVTableLayout = false; // MSVC returns a C++ record (struct, class) from an instance method through a hidden pointer, // passed after `this` and returned in turn (clang's MicrosoftCXXABI::classifyReturnType): the @@ -80,6 +83,7 @@ struct TargetInfo info.supportsInProcessJit = target.getArch() == host.getArch() && target.getOS() == host.getOS(); info.memberCallsUseThiscall = msvc && x86_32; + info.msvcVTableLayout = msvc; info.hiddenReturnPointerAfterThis = msvc; info.hiddenReturnPointerBeforeThis = !msvc && (target.getArch() == llvm::Triple::x86_64 || target.getArch() == llvm::Triple::aarch64); diff --git a/tslang/lib/TsClangImporter/BindingPrinter.cpp b/tslang/lib/TsClangImporter/BindingPrinter.cpp index 40b8d4a60..c27428a8e 100644 --- a/tslang/lib/TsClangImporter/BindingPrinter.cpp +++ b/tslang/lib/TsClangImporter/BindingPrinter.cpp @@ -239,6 +239,7 @@ llvm::Expected printBindings(const HeaderModel &model, const PrintO }; auto hasCppClass = false; + auto targetSlots = false; // a @cpp class printed with this target's @slot(N) for (int pass = 0; pass < groups; ++pass) { for (size_t index = 0; index < model.decls.size(); ++index) @@ -270,6 +271,30 @@ llvm::Expected printBindings(const HeaderModel &model, const PrintO break; case DeclKind::CppClass: { hasCppClass = true; + // @virtual needs every slot of the class and of its bases declared + std::string slotsReason; + for (auto *current = &decl; current && slotsReason.empty();) + { + slotsReason = current->virtualSlotsReason; + auto base = current->base; + current = nullptr; + for (auto &other : model.decls) + { + if (!base.empty() && other.key == base) + { + current = &other; + } + } + } + + auto virtualSlots = options.virtualSlots && slotsReason.empty(); + targetSlots |= !virtualSlots; + if (options.virtualSlots && !virtualSlots) + { + line("// @slot numbers for this target only: " + slotsReason); + result.warnings.push_back(decl.qualifiedName + " keeps this target's slots: " + slotsReason); + } + line("@cpp"); line(exported + "class " + tsName + (decl.base.empty() ? "" : " extends " + nameOf(decl.base)) + " { // " + decl.qualifiedName); @@ -286,6 +311,19 @@ llvm::Expected printBindings(const HeaderModel &model, const PrintO for (auto &method : decl.methods) { + // the destructor and the virtual methods that aren't public are slots, which + // only @virtual has to declare + if (!virtualSlots && (method.destructor || !method.access.empty())) + { + continue; + } + + if (method.destructor) + { + member("@destructor " + method.name + "(): void;"); + continue; + } + if (!method.skipReason.empty()) { member("// skipped: " + method.cppName + " \xE2\x80\x94 " + method.skipReason); @@ -307,7 +345,9 @@ llvm::Expected printBindings(const HeaderModel &model, const PrintO // a non-virtual method by its C++ declaration, which @cppname mangles for the // target compiled for; by this target's symbol when it can't be spelled so - auto decorator = method.slot >= 0 ? "@slot(" + std::to_string(method.slot) + ") " + auto access = method.access.empty() ? std::string() : method.access + " "; + auto decorator = virtualSlots && method.isVirtual ? "@virtual " + access + : method.slot >= 0 ? "@slot(" + std::to_string(method.slot) + ") " : method.cppDeclaration.empty() ? "@linkname(\"" + method.symbol + "\") " : "@cppname(\"" + method.cppDeclaration + "\") "; @@ -402,8 +442,11 @@ llvm::Expected printBindings(const HeaderModel &model, const PrintO if (hasCppClass) { - result.text += "// The @cpp classes are this target's C++ ABI (generate them again for another); compile with " - "-mm=gc or -mm=none.\n"; + result.text += targetSlots + ? "// The @cpp classes are this target's C++ ABI (generate them again for another); compile with " + "-mm=gc or -mm=none.\n" + : "// tslang numbers the @cpp classes' slots for the target compiled for (@virtual); their fields " + "are this target's layout. Compile with -mm=gc or -mm=none.\n"; } if (!result.text.empty()) diff --git a/tslang/lib/TsClangImporter/HeaderParser.cpp b/tslang/lib/TsClangImporter/HeaderParser.cpp index f62b53ed0..56a30f4ce 100644 --- a/tslang/lib/TsClangImporter/HeaderParser.cpp +++ b/tslang/lib/TsClangImporter/HeaderParser.cpp @@ -759,12 +759,49 @@ class Collector : public clang::RecursiveASTVisitor usedNames.insert(field.name); } + auto uniqueName = [&](const std::string &cppName) { + auto name = escapeReserved(cppName); + for (auto suffix = 2; usedNames.count(name) && !methodNames.count(name); ++suffix) + { + name = escapeReserved(cppName) + "_" + std::to_string(suffix); + } + + usedNames.insert(name); + methodNames.insert(name); + return name; + }; + for (auto *method : definition->methods()) { + // a virtual method adding a slot: --virtual-slots numbers the class's slots from them all + auto addsSlot = method->isVirtual() && method->size_overridden_methods() == 0; + if (addsSlot && llvm::isa(method)) + { + Method bound; + bound.cppName = "~" + decl.name; + bound.name = uniqueName("destructor"); + bound.isVirtual = true; + bound.destructor = true; + bound.result.name = "void"; + decl.methods.push_back(std::move(bound)); + continue; + } + + if (addsSlot && (method->isImplicit() || method->isDeleted() || + llvm::isa(method) || method->isOverloadedOperator())) + { + if (decl.virtualSlotsReason.empty()) + { + decl.virtualSlotsReason = "the virtual '" + method->getNameAsString() + "' can't be declared"; + } + + continue; + } + if (method->isImplicit() || method->isDeleted() || method->isStatic() || llvm::isa(method) || method->isOverloadedOperator() || method->getDescribedFunctionTemplate() || - method->getAccess() != clang::AS_public || + (method->getAccess() != clang::AS_public && !addsSlot) || (method->isVirtual() && method->size_overridden_methods() > 0)) { continue; @@ -774,15 +811,19 @@ class Collector : public clang::RecursiveASTVisitor // by the arguments. A field of the name makes it `_2`, `_3`, ... Method bound; bound.cppName = method->getName().str(); - bound.name = escapeReserved(bound.cppName); - for (auto suffix = 2; usedNames.count(bound.name) && !methodNames.count(bound.name); ++suffix) + bound.name = uniqueName(bound.cppName); + bound.isVirtual = addsSlot; + if (method->getAccess() != clang::AS_public) { - bound.name = escapeReserved(bound.cppName) + "_" + std::to_string(suffix); + bound.access = method->getAccess() == clang::AS_protected ? "protected" : "private"; } - usedNames.insert(bound.name); - methodNames.insert(bound.name); mapMethod(bound, method); + if (addsSlot && !bound.skipReason.empty() && decl.virtualSlotsReason.empty()) + { + decl.virtualSlotsReason = "the virtual '" + bound.cppName + "' is skipped"; + } + decl.methods.push_back(std::move(bound)); } diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index af2633b5c..dc5f3577e 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -490,6 +490,12 @@ namespace typescript { os << "@" CPP_VTABLE; newline(); + // the importer's own @virtual methods, in a class extending this one, start after it + if (classType->cppVTableSize >= 0) + { + os << "@" CPP_VTABLE_SIZE "(" << classType->cppVTableSize << ")"; + newline(); + } } // an importer calls a @final class's methods directly and may not extend it @@ -777,6 +783,12 @@ namespace typescript os.indent(4); os << "@" CPP_SLOT "(" << method.cppSlot << ")"; newline(); + if (method.isCppDestructor) + { + os.indent(4); + os << "@" CPP_DESTRUCTOR; + newline(); + } } os.indent(4); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 4550b67ed..56a476f2e 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -2812,6 +2812,15 @@ namespace mlirgen value = mlirGenCallFunction(location, calledFuncType, funcRefValue, operands, genContext); }) .Case([&](auto calledBoundFuncType) { + // MSVC's destructor slot is the deleting destructor, taking flags; the Itanium ABI's + // first one destroys without freeing: one call can't mean the same under both + if (isCppDestructorMethod(funcRefValue)) + { + emitError(location) << "a C++ destructor (@" CPP_DESTRUCTOR ") can't be called: release the object the way " + << "the C++ library does"; + return; + } + auto calledFuncType = getFunctionType(calledBoundFuncType.getInputs(), calledBoundFuncType.getResults(), calledBoundFuncType.isVarArg()); auto thisValue = builder.create(location, calledFuncType.getInput(0), funcRefValue); diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 1293cabdb..c979025db 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -229,6 +229,12 @@ namespace mlirgen // the base classes are known now, and no method has been named yet if (newClassPtr->isCppVTable) { + if (mlir::failed(mlirGenClassCppVirtualSlots(location, classDeclarationAST, newClassPtr, classGenContext))) + { + setProcessingState(newClassPtr, ProcessingStages::ErrorInStorageClass, genContext); + return {mlir::failure(), ""}; + } + mlirGenClassCppOverloadNames(classDeclarationAST, newClassPtr, classGenContext); } @@ -673,6 +679,11 @@ namespace mlirgen } cppVTableMethods.insert(funcName); + if (llvm::any_of(newClassPtr->methods, [&](auto &method) { return method.funcName == funcName && method.isCppDestructor; })) + { + cppDestructors.insert(funcName); + } + if (hasBody) { funcOp->setAttr(CPP_METHOD_ATTR_NAME, builder.getUnitAttr()); @@ -833,12 +844,21 @@ namespace mlirgen } } + if (MLIRHelper::hasDecorator(classDeclarationAST, CPP_VTABLE_SIZE)) + { + emitError(location) << "@" CPP_VTABLE_SIZE " is for a @" CPP_VTABLE " class"; + return mlir::failure(); + } + for (auto &classMember : classDeclarationAST->members) { - if (MLIRHelper::hasDecorator(classMember, CPP_SLOT)) + for (auto decorator : {CPP_SLOT, CPP_VIRTUAL, CPP_DESTRUCTOR}) { - emitError(loc(classMember)) << "@" CPP_SLOT " is for a method of a @" CPP_VTABLE " class"; - return mlir::failure(); + if (MLIRHelper::hasDecorator(classMember, decorator)) + { + emitError(loc(classMember)) << "@" << decorator << " is for a method of a @" CPP_VTABLE " class"; + return mlir::failure(); + } } } @@ -929,7 +949,7 @@ namespace mlirgen if (hasModifier(classMember, SyntaxKind::AbstractKeyword)) { error(memberLocation) << "the abstract method '" << cppOverloadedName(methodName) << "' of a @" CPP_VTABLE - << " class needs @" CPP_SLOT "(N), its vtable slot"; + << " class needs @" CPP_VIRTUAL " or @" CPP_SLOT "(N), its vtable slot"; } else if (!hasBody && !newClassPtr->isImport && !declarationMode) { @@ -941,8 +961,8 @@ namespace mlirgen if (!hasLinkName) { - error(memberLocation) << "'" << cppOverloadedName(methodName) << "' has no @" CPP_SLOT ", so it isn't virtual: give a " - << "C++ virtual method its slot, @" CPP_SLOT "(N), or a non-virtual one its " + error(memberLocation) << "'" << cppOverloadedName(methodName) << "' has no @" CPP_SLOT ", so it isn't virtual: mark a " + << "C++ virtual method @" CPP_VIRTUAL " or give it its slot, @" CPP_SLOT "(N), or a non-virtual one its " << "symbol, @" LINK_NAME "(\"...\"), or its C++ declaration, @" CPP_NAME "(\"...\")"; } } @@ -986,16 +1006,34 @@ namespace mlirgen return failed ? mlir::failure() : mlir::success(); } - // @slot(N) of a class member: N; -1 without @slot, -2 when its argument isn't a slot number + // The key of a class member in cppVirtualSlots: its node, whatever type it is seen as + static const void *cppMemberKey(Node member) + { + return member.operator->(); + } + + // @slot(N) of a class member: N; -1 without @slot, -2 when its argument isn't a slot number. A + // @virtual or @destructor method has the slot mlirGenClassCppVirtualSlots gave it (an explicit + // @slot wins), or -3 before it is given one. int MLIRGenImpl::getCppSlot(ClassElement classMember, const GenContext &genContext) { auto slot = -1; + auto numbered = false; + auto explicitSlot = false; iterateDecorators(classMember, genContext, [&](StringRef name, SmallVector args) { + if (name == CPP_VIRTUAL || name == CPP_DESTRUCTOR) + { + numbered = true; + return; + } + if (name != CPP_SLOT) { return; } + explicitSlot = true; + unsigned value; if (args.size() != 1 || args.front().getAsInteger(10, value) || value > (unsigned)std::numeric_limits::max()) { @@ -1006,8 +1044,280 @@ namespace mlirgen slot = static_cast(value); }); + if (numbered && !explicitSlot) + { + auto it = cppVirtualSlots.find(cppMemberKey(classMember)); + return it != cppVirtualSlots.end() ? it->second : -3; + } + return slot; } + // @virtual and @destructor (CPP_VIRTUAL, CPP_DESTRUCTOR): the compiler numbers a @cpp class's + // virtual methods for the target as its C++ compiler does, so one binding serves every target. + // A base class's slots come first. Of this class's methods, one with the name and parameter + // types of a base class's virtual method overrides it, in its slot; the others are new slots, + // in declaration order, except that + // - under MSVC, overloads of one name are grouped where the first of them is declared, in + // reverse declaration order, and the destructor is one slot (the scalar deleting destructor); + // - under the Itanium ABI, the destructor is two slots (the complete and the deleting one). + // The class declares all its virtual methods (a slot it leaves out shifts the next ones), so a + // class numbering its new methods with @slot(N) can't use @virtual too, and a base class's + // size must be known: its own methods are @virtual, or it says @vtablesize(N). + mlir::LogicalResult MLIRGenImpl::mlirGenClassCppVirtualSlots(mlir::Location location, ClassLikeDeclaration classDeclarationAST, + ClassInfo::TypePtr newClassPtr, const GenContext &genContext) + { + auto msvc = compileOptions.targetInfo.msvcVTableLayout; + + auto baseSize = 0; + auto baseDestructor = -1; + ClassInfo::TypePtr baseClass; + for (auto &base : newClassPtr->baseClasses) + { + baseClass = base; + baseSize = base->cppVTableSize; + baseDestructor = base->cppDestructorSlot; + } + + // the base classes' virtual methods, by C++ name: what a method here may override + struct BaseSlot + { + int slot; + mlir::ArrayRef params; + }; + + llvm::StringMap> baseSlots; + std::function collect = [&](ClassInfo::TypePtr classInfo) { + for (auto &base : classInfo->baseClasses) + { + for (auto &method : base->methods) + { + auto funcType = method.declaredFuncType ? method.declaredFuncType : method.funcType; + if (method.isStatic || method.cppSlot < 0 || method.isCppSlotGap || method.isCppDestructor || !funcType) + { + continue; + } + + baseSlots[cppOverloadedName(method.name)].push_back( + {method.cppSlot, funcType.getInputs().drop_front(funcType.getNumInputs() > 0 ? 1 : 0)}); + } + + collect(base); + } + }; + collect(newClassPtr); + + auto declaredSize = -1; + iterateDecorators(classDeclarationAST, genContext, [&](StringRef name, SmallVector args) { + unsigned value; + if (name == CPP_VTABLE_SIZE) + { + declaredSize = args.size() == 1 && !args.front().getAsInteger(10, value) && value <= (unsigned)std::numeric_limits::max() + ? static_cast(value) : -2; + } + }); + + if (declaredSize == -2) + { + emitError(location) << "@" CPP_VTABLE_SIZE " takes the number of slots, an integer from 0"; + return mlir::failure(); + } + + struct NewSlot + { + ClassElement member; + std::string name; + bool destructor; + }; + + SmallVector newSlots; + auto ownDestructor = -1; + auto slotsOfItsOwn = false; + auto failed = false; + for (auto &classMember : classDeclarationAST->members) + { + if (classMember != SyntaxKind::MethodDeclaration || hasModifier(classMember, SyntaxKind::StaticKeyword)) + { + continue; + } + + auto memberLocation = loc(classMember); + auto methodDeclaration = classMember.as(); + auto isVirtual = MLIRHelper::hasDecorator(classMember, CPP_VIRTUAL); + auto isDestructor = MLIRHelper::hasDecorator(classMember, CPP_DESTRUCTOR); + auto explicitSlot = -1; + auto hasSlot = false; + iterateDecorators(classMember, genContext, [&](StringRef name, SmallVector args) { + unsigned value; + if (name == CPP_SLOT) + { + hasSlot = true; + if (args.size() == 1 && !args.front().getAsInteger(10, value) && value <= (unsigned)std::numeric_limits::max()) + { + explicitSlot = static_cast(value); + } + } + }); + + if (isDestructor) + { + if (methodDeclaration->parameters.size() > 0) + { + emitError(memberLocation) << "a C++ destructor (@" CPP_DESTRUCTOR ") takes no parameters"; + failed = true; + continue; + } + + if (hasSlot) + { + // the destructor in a slot given by hand: an import's, or a binding for one target + ownDestructor = explicitSlot; + slotsOfItsOwn |= baseSize < 0 || explicitSlot >= baseSize; + } + else if (baseDestructor >= 0) + { + // overriding the base class's + cppVirtualSlots[cppMemberKey(classMember)] = baseDestructor; + } + else + { + newSlots.push_back({classMember, "~", true}); + } + + continue; + } + + if (hasSlot) + { + // a slot of its own, not one of a base class's + slotsOfItsOwn |= baseSize < 0 || explicitSlot >= baseSize; + continue; + } + + if (!isVirtual) + { + continue; + } + + auto name = cppOverloadedName(MLIRHelper::getName(methodDeclaration->name)).str(); + auto it = baseSlots.find(name); + if (it != baseSlots.end()) + { + // an override of the base class's method with these parameters + SmallVector params; + auto typed = true; + for (auto ¶meter : methodDeclaration->parameters) + { + auto type = parameter->type ? getType(parameter->type, genContext) : mlir::Type(); + typed &= static_cast(type); + params.push_back(type); + } + + if (!typed) + { + emitError(memberLocation) << "'" << name << "' is a virtual method of a base class too: give every parameter " + << "its type, to tell whether this one overrides it"; + failed = true; + continue; + } + + auto overridden = llvm::find_if(it->second, [&](BaseSlot &base) { return base.params == mlir::ArrayRef(params); }); + if (overridden != it->second.end()) + { + cppVirtualSlots[cppMemberKey(classMember)] = overridden->slot; + continue; + } + } + + newSlots.push_back({classMember, name, false}); + } + + if (failed) + { + return mlir::failure(); + } + + auto size = baseSize; + if (!newSlots.empty()) + { + if (baseSize < 0) + { + emitError(location) << "the @" CPP_VTABLE " class '" << newClassPtr->fullName << "' numbers its virtual methods with @" + << CPP_VIRTUAL ", but where they start isn't known: its base class '" + << (baseClass ? baseClass->fullName : StringRef()) << "' names its slots with @" CPP_SLOT + "(N). Declare the base class's virtual methods with @" CPP_VIRTUAL " too, or give it @" + CPP_VTABLE_SIZE "(N)"; + return mlir::failure(); + } + + if (slotsOfItsOwn) + { + emitError(location) << "the @" CPP_VTABLE " class '" << newClassPtr->fullName << "' gives its new virtual methods " + << "both @" CPP_VIRTUAL " and @" CPP_SLOT "(N): number them all with one or the other"; + return mlir::failure(); + } + + SmallVector ordered; + if (msvc) + { + // grouped by name where the first is declared, each group in reverse order + SmallVector names; + for (auto &newSlot : newSlots) + { + if (!llvm::is_contained(names, newSlot.name)) + { + names.push_back(newSlot.name); + } + } + + for (auto &name : names) + { + for (auto &newSlot : llvm::reverse(newSlots)) + { + if (newSlot.name == name) + { + ordered.push_back(newSlot); + } + } + } + } + else + { + ordered = newSlots; + } + + for (auto &newSlot : ordered) + { + cppVirtualSlots[cppMemberKey(newSlot.member)] = size; + if (newSlot.destructor) + { + ownDestructor = size; + } + + size += newSlot.destructor && !msvc ? 2 : 1; + } + } + else if (slotsOfItsOwn) + { + size = -1; + } + + if (declaredSize >= 0) + { + if (size >= 0 && declaredSize < size) + { + emitError(location) << "the @" CPP_VTABLE " class '" << newClassPtr->fullName << "' has " << size + << " slots, more than its @" CPP_VTABLE_SIZE "(" << declaredSize << ")"; + return mlir::failure(); + } + + size = declaredSize; + } + + newClassPtr->cppVTableSize = size; + newClassPtr->cppDestructorSlot = ownDestructor >= 0 ? ownDestructor : baseDestructor; + return mlir::success(); + } + // Whether a base class of a @cpp class has a virtual method named methodName: a method of the // class with that name overrides it, as in C++, without @slot of its own @@ -4518,6 +4828,7 @@ genContext); if (newClassPtr->isCppVTable && !classMethodMemberInfo.isConstructor && !classMethodMemberInfo.isStatic) { classMethodMemberInfo.cppSlot = std::max(getCppSlot(classMember, genContext), -1); + classMethodMemberInfo.isCppDestructor = MLIRHelper::hasDecorator(classMember, CPP_DESTRUCTOR); classMethodMemberInfo.isVirtual = isCppVirtualMethod(newClassPtr, classMember, genContext); classMethodMemberInfo.isForceVirtual = classMethodMemberInfo.isVirtual; } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index a2c827f6e..cfa0d4805 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -6546,6 +6546,21 @@ class MLIRGenImpl return false; } + bool isCppDestructorMethod(mlir::Value funcRef) + { + if (auto virtualSymbolRef = funcRef.getDefiningOp()) + { + return cppDestructors.contains(virtualSymbolRef.getIdentifier()); + } + + if (auto symbolRef = funcRef.getDefiningOp()) + { + return cppDestructors.contains(symbolRef.getIdentifier()); + } + + return false; + } + // A @cpp class's objects are C++ objects: their slot 0 is a C++ method (the destructor), // not `.instanceOf`, and the class has no RTTI, so nothing may ask one what it is - not // `instanceof`, nor boxing into `any` (unboxed by asking), nor an interface (made by asking). @@ -13734,6 +13749,9 @@ class MLIRGenImpl int getCppSlot(ClassElement classMember, const GenContext &genContext); + mlir::LogicalResult mlirGenClassCppVirtualSlots(mlir::Location location, ClassLikeDeclaration classDeclarationAST, + ClassInfo::TypePtr newClassPtr, const GenContext &genContext); + bool isCppBaseSlot(ClassInfo::TypePtr classInfo, StringRef methodName); std::string getCppMethodName(ClassElement classMember, const GenContext &genContext); @@ -14498,6 +14516,7 @@ class MLIRGenImpl dllName }); methodInfos.back().cppSlot = cppSlot; + methodInfos.back().isCppDestructor = isCppDestructor; } else { @@ -14506,6 +14525,7 @@ class MLIRGenImpl if (newClassPtr->isCppVTable) { methodInfos[methodIndex].cppSlot = cppSlot; + methodInfos[methodIndex].isCppDestructor = isCppDestructor; methodInfos[methodIndex].isVirtual = isAbstract || isVirtual; } if (!dllName.empty()) @@ -14672,6 +14692,7 @@ class MLIRGenImpl mlir_ts::AccessLevel accessLevel; // @slot(N) of a method of a @cpp class (MethodInfo::cppSlot) int cppSlot = -1; + bool isCppDestructor = false; mlir_ts::FuncOp funcOp; }; @@ -17450,6 +17471,10 @@ class MLIRGenImpl llvm::StringSet<> cppVTableHiddenReturnsBeforeThis; // the methods of @cpp classes (by function name), C++ methods llvm::StringSet<> cppVTableMethods; + // the @destructor methods of @cpp classes, by function name: a call of one is an error + llvm::StringSet<> cppDestructors; + // the slot mlirGenClassCppVirtualSlots gave a @virtual or @destructor method, by its declaration + llvm::DenseMap cppVirtualSlots; // the methods of @cpp classes without a body: a slot one names in a class implementing C++ // methods is null, as a pure virtual method's llvm::StringSet<> cppMethodsWithoutBody; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 4a39faf3b..da15e98e2 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4007,11 +4007,15 @@ set(cppvtable_errors "field_initializer|a field of a @cpp class can't have an initializer" "slot_old_name|@cppvtable is now @cpp, and a virtual method needs @slot\\(N\\)" "slot_missing|'second' has no @slot, so it isn't virtual" - "slot_abstract|the abstract method 'first' of a @cpp class needs @slot\\(N\\), its vtable slot" + "slot_abstract|the abstract method 'first' of a @cpp class needs @virtual or @slot\\(N\\), its vtable slot" "slot_conflict|@slot: 'second' and 'first' are both in slot 1" "slot_override|@slot: 'first' overrides slot 0 of a base class, not slot 2" "slot_argument|@slot takes the slot number, an integer from 0" "slot_plain_class|@slot is for a method of a @cpp class" + "virtual_destructor_call|a C\\+\\+ destructor \\(@destructor\\) can't be called" + "virtual_mixed_slot|the @cpp class 'Mixed' gives its new virtual methods both @virtual and @slot\\(N\\)" + "virtual_base_unknown|the @cpp class 'Extended' numbers its virtual methods with @virtual, but where they start isn't known" + "virtual_plain_class|@virtual is for a method of a @cpp class" "overload_no_match|no overload of 'write' takes these arguments \\(string\\). it has:" "overload_ambiguous|the call of 'write' is ambiguous: its arguments \\(s32, s32\\) fit more than one of:" "overload_override|'write' is overloaded in a base class: an override names the slot it overrides, @slot\\(N\\)" @@ -4179,8 +4183,59 @@ if (CMAKE_SIZEOF_VOID_P EQUAL 8 AND (MSVC OR (NOT WIN32 AND CMAKE_SYSTEM_PROCESS set_tests_properties(test-${cppvtable_mm}-verify-ownership-cppvtable-abi PROPERTIES FAIL_REGULAR_EXPRESSION "error:|warning:|Stack dump|Assertion failed") endforeach() + # One binding for both ABIs: tslang numbers the @virtual slots as the host's C++ compiler did + # (cppvtable/virtual_slots.ts) + foreach(cppvtable_mm none rc own) + add_test(NAME test-jit-cppvtable-virtual-slots-${cppvtable_mm} + COMMAND $ --emit=jit --no-default-lib -mm=${cppvtable_mm} + --shared-libs=$ + --shared-libs=$ + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_slots.ts") + set_tests_properties(test-jit-cppvtable-virtual-slots-${cppvtable_mm} + PROPERTIES PASS_REGULAR_EXPRESSION "done\." + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Segmentation|Assertion failed") + endforeach() endif() +# @virtual slots, numbered for each target whatever the host (the slots MSVC and clang give +# abi_host.cpp's VirtualDerived): k(int) is grouped before k() under MSVC, last under the Itanium ABI +add_test(NAME test-compile-cppvtable-virtual-slots-msvc + COMMAND $ --emit=mlir --no-default-lib -mm=none -mtriple=x86_64-pc-windows-msvc + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_slots.ts" -o -) +set_tests_properties(test-compile-cppvtable-virtual-slots-msvc + PROPERTIES PASS_REGULAR_EXPRESSION "VirtualDerived.k#1\", index = 7 : i32" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +add_test(NAME test-compile-cppvtable-virtual-slots-itanium + COMMAND $ --emit=mlir --no-default-lib -mm=none -mtriple=x86_64-unknown-linux-gnu + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_slots.ts" -o -) +set_tests_properties(test-compile-cppvtable-virtual-slots-itanium + PROPERTIES PASS_REGULAR_EXPRESSION "VirtualDerived.k#1\", index = 11 : i32" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +# ...the destructor: one slot under MSVC (MSVC's over(int) in slot 2), two under Itanium (over(int, int) in 3) +add_test(NAME test-compile-cppvtable-virtual-destructor-msvc + COMMAND $ --emit=mlir --no-default-lib -mm=none -mtriple=x86_64-pc-windows-msvc + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_slots.ts" -o -) +set_tests_properties(test-compile-cppvtable-virtual-destructor-msvc + PROPERTIES PASS_REGULAR_EXPRESSION "VirtualBase.over#2\", index = 2 : i32" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +add_test(NAME test-compile-cppvtable-virtual-destructor-itanium + COMMAND $ --emit=mlir --no-default-lib -mm=none -mtriple=x86_64-unknown-linux-gnu + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_slots.ts" -o -) +set_tests_properties(test-compile-cppvtable-virtual-destructor-itanium + PROPERTIES PASS_REGULAR_EXPRESSION "VirtualBase.over, index = 3 : i32" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +# @vtablesize(N): a base class naming some slots by hand says where its slots end +add_test(NAME test-compile-cppvtable-virtual-base-size + COMMAND $ --emit=mlir --no-default-lib -mm=none + "${PROJECT_SOURCE_DIR}/test/tester/cppvtable/virtual_base_size.ts" -o -) +set_tests_properties(test-compile-cppvtable-virtual-base-size + PROPERTIES PASS_REGULAR_EXPRESSION "Extended.more, index = 6 : i32" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +# A @cpp class extending one another module exported: its size and destructor come through __decls +foreach(virtual_mm gc own) + tslang_add_test(NAME test-compile-shared-export-import-virtual-slots-${virtual_mm} COMMAND test-runner -shared -mm=${virtual_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_virtual_slots.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_virtual_slots.ts") +endforeach() + # MSVC member functions are __thiscall on 32-bit x86, which a class method call isn't. add_test(NAME test-compile-cppvtable-thiscall-target COMMAND $ --emit=obj --no-default-lib -mm=none -mtriple=i686-pc-windows-msvc diff --git a/tslang/test/tester/cppvtable/abi_host.cpp b/tslang/test/tester/cppvtable/abi_host.cpp index 4a869a6de..f505807e3 100644 --- a/tslang/test/tester/cppvtable/abi_host.cpp +++ b/tslang/test/tester/cppvtable/abi_host.cpp @@ -163,3 +163,43 @@ ABI_EXPORT int abi_is_storage(void *p, int index) { return p == &storage[index] ? 1 : 0; } + +// A hierarchy whose slots tslang numbers itself, for the target (virtual_slots.ts, @virtual): a +// destructor, which is one slot under MSVC and two under the Itanium ABI, and overloads, which MSVC +// groups where the first of them is declared, in reverse order. Every method says which it is. +struct VirtualBase +{ + virtual int f() { return 1; } + virtual ~VirtualBase() {} + virtual int over(int a, int b) { return 100 + a + b; } + virtual int g() { return 2; } + virtual int over(double x) { return 200; } + virtual int over(int x) { return 300 + x; } + virtual int h() { return 3; } +}; + +struct VirtualDerived : VirtualBase +{ + virtual int k() { return 4; } + int over(double x) override { return 201; } + virtual int over(short x) { return 400 + x; } + virtual int m() { return 5; } + virtual int k(int x) { return 500 + x; } + ~VirtualDerived() override {} + int g() override { return 20; } +}; + +ABI_EXPORT VirtualDerived *virtual_derived() +{ + return new VirtualDerived(); +} + +ABI_EXPORT VirtualBase *virtual_base() +{ + return new VirtualBase(); +} + +ABI_EXPORT void virtual_delete(VirtualBase *object) +{ + delete object; +} diff --git a/tslang/test/tester/cppvtable/virtual_base_size.ts b/tslang/test/tester/cppvtable/virtual_base_size.ts new file mode 100644 index 000000000..c6d1ce126 --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_base_size.ts @@ -0,0 +1,18 @@ +// ...unless it says how many slots it has, @vtablesize(N): the derived class's @virtual methods +// start there. +@cpp +@vtablesize(6) +class Partial { + @slot(3) known(): s32; +} + +@cpp +class Extended extends Partial { + @virtual more(): s32; +} + +declare function make_extended(): Extended; + +function main() { + print(make_extended().more()); +} diff --git a/tslang/test/tester/cppvtable/virtual_base_unknown.ts b/tslang/test/tester/cppvtable/virtual_base_unknown.ts new file mode 100644 index 000000000..e8d3d567f --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_base_unknown.ts @@ -0,0 +1,14 @@ +// @virtual numbers a class's methods after its base class's slots, so the base class's size has to +// be known: a base naming only some of its slots with @slot(N) can't say where they end. +@cpp +class Partial { + @slot(3) known(): s32; +} + +@cpp +class Extended extends Partial { + @virtual more(): s32; +} + +function main() { +} diff --git a/tslang/test/tester/cppvtable/virtual_destructor_call.ts b/tslang/test/tester/cppvtable/virtual_destructor_call.ts new file mode 100644 index 000000000..f14ea0122 --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_destructor_call.ts @@ -0,0 +1,14 @@ +// A C++ destructor's slot is called differently under MSVC (the deleting one, taking flags) and the +// Itanium ABI (the complete one, freeing nothing): a call of it is an error. +@cpp +class Resource { + @virtual size(): s32; + @destructor destroy(): void; +} + +declare function make_resource(): Resource; + +function main() { + const resource = make_resource(); + resource.destroy(); +} diff --git a/tslang/test/tester/cppvtable/virtual_mixed_slot.ts b/tslang/test/tester/cppvtable/virtual_mixed_slot.ts new file mode 100644 index 000000000..85a8386c3 --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_mixed_slot.ts @@ -0,0 +1,10 @@ +// A class numbers its new virtual methods with @virtual or with @slot(N), not both: a @slot among +// @virtual methods would shift or collide with them. +@cpp +class Mixed { + @virtual first(): s32; + @slot(5) second(): s32; +} + +function main() { +} diff --git a/tslang/test/tester/cppvtable/virtual_plain_class.ts b/tslang/test/tester/cppvtable/virtual_plain_class.ts new file mode 100644 index 000000000..bd3c86a6e --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_plain_class.ts @@ -0,0 +1,7 @@ +// @virtual is for a method of a @cpp class: an ordinary class's vtable is tslang's own. +class Plain { + @virtual method(): number { return 1; } +} + +function main() { +} diff --git a/tslang/test/tester/cppvtable/virtual_slots.ts b/tslang/test/tester/cppvtable/virtual_slots.ts new file mode 100644 index 000000000..ee54e4c65 --- /dev/null +++ b/tslang/test/tester/cppvtable/virtual_slots.ts @@ -0,0 +1,55 @@ +// One binding for every target: the slots of @virtual methods are numbered by tslang as the +// target's C++ compiler numbers them (abi_host.cpp's VirtualBase, VirtualDerived) - MSVC with one +// destructor slot and overloads grouped in reverse order, the Itanium ABI with two destructor slots +// and the declaration order. Before @virtual, this needed a binding per ABI with its @slot numbers. + +@cpp +class VirtualBase { + @virtual f(): s32; + @destructor destroy(): void; + @virtual over(a: s32, b: s32): s32; + @virtual g(): s32; + @virtual over(x: f64): s32; + @virtual over(x: s32): s32; + @virtual h(): s32; +} + +@cpp +class VirtualDerived extends VirtualBase { + @virtual k(): s32; + @virtual over(x: f64): s32; // overrides the base class's, in its slot + @virtual over(x: s16): s32; // a new overload + @virtual m(): s32; + @virtual k(x: s32): s32; + @destructor destroy(): void; // overrides the base class's + @virtual g(): s32; +} + +declare function virtual_derived(): VirtualDerived; +declare function virtual_base(): VirtualBase; +declare function virtual_delete(object: VirtualBase): void; + +function main() { + const base = virtual_base(); + assert(base.f() == 1 && base.g() == 2 && base.h() == 3, "the base class's methods"); + assert(base.over(3, 4) == 107, "over(int, int)"); + const half: f64 = 0.5; + assert(base.over(half) == 200, "over(double)"); + assert(base.over(7) == 307, "over(int)"); + virtual_delete(base); + + const derived = virtual_derived(); + assert(derived.f() == 1 && derived.h() == 3, "inherited"); + assert(derived.g() == 20, "an override"); + assert(derived.k() == 4 && derived.k(6) == 506, "k and its overload, MSVC grouping them"); + assert(derived.m() == 5, "after the overloads"); + assert(derived.over(half) == 201, "an overload overridden"); + assert(derived.over(9) == 409, "a new overload"); + assert(derived.over(7) == 307 && derived.over(1, 2) == 103, "the base class's overloads"); + + const asBase: VirtualBase = derived; + assert(asBase.g() == 20 && asBase.over(half) == 201, "through the base class"); + virtual_delete(derived); + + print("done."); +} diff --git a/tslang/test/tester/tests/export_virtual_slots.ts b/tslang/test/tester/tests/export_virtual_slots.ts new file mode 100644 index 000000000..d07802d16 --- /dev/null +++ b/tslang/test/tester/tests/export_virtual_slots.ts @@ -0,0 +1,9 @@ +// A @cpp class whose slots tslang numbers (@virtual), exported: the importer +// (import_virtual_slots.ts) reads its size (@vtablesize) and its destructor from __decls, and numbers +// the @virtual methods of a class extending it after them. +@cpp +export class Shape { + @virtual area(): s32; + @destructor destroy(): void; + @virtual scale(x: s32): s32; +} diff --git a/tslang/test/tester/tests/import_virtual_slots.ts b/tslang/test/tester/tests/import_virtual_slots.ts new file mode 100644 index 000000000..3cd639105 --- /dev/null +++ b/tslang/test/tester/tests/import_virtual_slots.ts @@ -0,0 +1,19 @@ +// A @cpp class extending one another module exported (export_virtual_slots.ts): its @virtual methods +// start after the imported class's slots, whose number __decls carries, and its @destructor +// overrides the imported one. +import './export_virtual_slots' + +@cpp +class Circle extends Shape { + @virtual radius(): s32; + @virtual area(): s32; + @destructor destroy(): void; +} + +function radiusOf(circle: Circle) { + return circle.radius() + circle.area(); +} + +function main() { + print("done."); +} diff --git a/tslang/tsbindgen/tsbindgen.cpp b/tslang/tsbindgen/tsbindgen.cpp index 6487b0aa9..4684ae152 100644 --- a/tslang/tsbindgen/tsbindgen.cpp +++ b/tslang/tsbindgen/tsbindgen.cpp @@ -36,6 +36,10 @@ cl::opt stripPrefix("strip-prefix", cl::desc("Remove

from the T cl::value_desc("P"), cl::cat(category)); cl::opt resourceDir("resource-dir", cl::desc("clang's resource directory"), cl::value_desc("dir"), cl::cat(category)); +cl::opt virtualSlots("virtual-slots", + cl::desc("Number a C++ class's virtual methods with @virtual, as tslang does for the target " + "compiled for, instead of this target's @slot(N): one binding for every target"), + cl::cat(category)); cl::opt outputFile("o", cl::desc("Output file (default: stdout)"), cl::value_desc("out.ts"), cl::init("-"), cl::cat(category)); @@ -216,6 +220,7 @@ int main(int argc, char **argv) options.filters = filters; options.namespaceName = namespaceName; options.stripPrefix = stripPrefix; + options.virtualSlots = virtualSlots; options.headerLines = {"Generated by tsbindgen " + version() + " (clang " CLANG_VERSION_STRING "); do not edit.", commandLine}; // `import` would not do: it loads a same-named .dll/.so as a tslang library if there is one, diff --git a/tslang/unittests/TsClangImporter/CppClassTest.cpp b/tslang/unittests/TsClangImporter/CppClassTest.cpp index 99de61669..505c2d044 100644 --- a/tslang/unittests/TsClangImporter/CppClassTest.cpp +++ b/tslang/unittests/TsClangImporter/CppClassTest.cpp @@ -286,3 +286,43 @@ TEST(CppClass, FilterByQualifiedName) auto out = generate(shapes, options, windowsTarget, {}, "c++").text; EXPECT_THAT(out, AllOf(HasSubstr("class Shape "), HasSubstr("class Circle extends Shape "))); } + +// --virtual-slots: the virtual methods @virtual, the destructor @destructor, the virtual methods +// that aren't public declared too (each is a slot), in declaration order - which tslang numbers for +// the target it compiles for, so the binding is the same text for every target +TEST(CppClass, VirtualSlotsAreOneBindingForEveryTarget) +{ + tsbindgen::PrintOptions options; + options.virtualSlots = true; + auto windows = generate(shapes, options, windowsTarget, {}, "c++"); + auto itanium = generate(shapes, options, linuxTarget, {}, "c++"); + EXPECT_THAT(windows.text, HasSubstr("@cpp\nclass Shape { // geo::Shape\n" + " @destructor destructor(): void;\n" + " @virtual area(): s32;\n" + " @virtual scale(by: s32): void;\n" + " @virtual scale(by: f32): void;\n" + " @virtual scale(by: f64): void;\n" + " @virtual protected hidden(): void;\n" + " @virtual last(): s32;\n" + "}\n")); + EXPECT_THAT(windows.text, HasSubstr("@cpp\nclass Circle extends Shape { // geo::Circle\n" + " @virtual contains(other: Shape): boolean;\n" + "}\n")); + EXPECT_EQ(windows.text, itanium.text); +} + +// ...but a class with a virtual method it can't declare, and a class extending it, keep this +// target's @slot(N): a slot left out would shift the next ones +TEST(CppClass, VirtualSlotsKeepTheTargetsSlotsWithASkippedVirtual) +{ + tsbindgen::PrintOptions options; + options.virtualSlots = true; + auto header = "class Log { public: virtual ~Log(); virtual void write(const char *format, ...); virtual int size(); };\n" + "class FileLog : public Log { public: virtual int fd(); };\n"; + auto out = generate(header, options, linuxTarget, {}, "c++"); + EXPECT_THAT(out.text, HasSubstr("// @slot numbers for this target only: the virtual 'write' is skipped\n@cpp\nclass Log")); + EXPECT_THAT(out.text, HasSubstr(" @slot(3) size(): s32;\n")); + EXPECT_THAT(out.text, HasSubstr(" @slot(4) fd(): s32;\n")); + EXPECT_THAT(out.text, Not(HasSubstr("@virtual"))); + EXPECT_THAT(out.warnings, Contains("Log keeps this target's slots: the virtual 'write' is skipped")); +}