diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 3330aa82f..f4fd4604b 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -24,9 +24,14 @@ Regression test `tslang/test/tester/tests/00tslang_issue_28.ts`. so `_beginthreadex(..., entry, arg, ...)` shifted `arg` and every argument after the callback): a function declared `@cdecl` takes each function-typed parameter as a C function pointer. A function or an arrow that captures nothing passes; a capturing arrow or a bound method passed straight to it is a -compile error ("a closure or a bound method can't be used as a plain function pointer"). Not checked -yet: a closure already stored in a variable of function type, passed on to a `@cdecl` parameter, still -loses its captures at run time. Regression tests `tslang/test/tester/tests/00tslang_issue_29.ts`, +compile error ("a closure or a bound method can't be used as a plain function pointer"). A function +value (a `const` of function type, a callback parameter) passed on to a `@cdecl` parameter is checked at +run time: a closure throws that error there, instead of the C function running it without its captures +later (an `atexit` handler crashed at exit). A function named directly skips the check. Also, a +capturing arrow can now be assigned to a function type whose leading parameters are `Opaque` +(`(a: Opaque, b: Opaque) => s32`, a C comparator). The type match took a leading `Opaque` for a receiver +and refused it; the parameters are now first matched as they are. Regression tests +`00tslang_issue_29_function_value.ts` and `00tslang_issue_29_comparator.ts`, and `tslang/test/tester/tests/00tslang_issue_29.ts`, `00tslang_issue_29_thread.ts` (Windows), `00tslang_issue_29_pthread.ts` (Linux) and `cdecl_closure_error.ts`. 30 (a generic's body, compiled where it is first instantiated, resolved a name to a local of the @@ -183,37 +188,43 @@ Still open from 48: - Whole-program facts: a method that no module of the program overrides is still taken as overridable when its class is exported. `--own-facts` reads the facts of the modules a module imports, not of the ones that import it, so the base's module can't know its subclasses. `@final` is the way to say it. -- `@final` on an accessor (`get`/`set`) is accepted but changes nothing at the call site yet. -- The other errors seen in powder_sandbox's own build are item 49. The one in `levels.ts`, `'x' is +- `@final` on an accessor (`get`/`set`) works now, as on a method: a direct call, an error for an + override ("accessor 'x' overrides the @final accessor of 'Base'"), and the declaration printer writes + it. +- The other errors seen in powder_sandbox's own build were item 49 (fixed). The one in `levels.ts`, `'x' is moved inside a loop but was made outside it` (the same `box` array kept by several `LevelStroke`s), is the game's to fix. -### 49. `-mm=own`: a nullable fresh local stored into a field, and a field moved into another - -Reduced on 2026-11-14 by the powder_sandbox session from the errors left in its own build. All three -fail on alpha127 and on the branch with the 47/48 fixes (`tslang -mm=own --emit=obj r1.ts`): +Item 49, three `-mm=own` errors powder_sandbox reduced on 2026-11-14 from what was left in its build, +is fixed. Before the fix, `startA`, `startB` and `moveAside` below were refused: ```ts class Level { name: string = "a"; } export class App { level: Level | null = null; + other: Level | null = null; read(n: string): Level | null { return n == "" ? null : new Level(); } - // 6:58 "moved here on some paths only" + "takes a second reference" startA(n: string) { const l = this.read(n); if (l) { this.level = l; } } - // 8:49 "takes a second reference": unconditional store of a nullable fresh local startB(n: string) { const l = this.read(n); this.level = l; } - other: Level | null = null; - // 11:19 "borrows a field and cannot be stored": moving one field into another (a swap works) moveAside() { this.other = this.level; this.level = null; } } -function main() { const a = new App(); a.startA("x"); a.startB("x"); a.moveAside(); print(a.other != null); } ``` -- `startA`: the store moves `l` on the path where it is not null. On the other path `l` is null and - holds nothing to release, so moving it on some paths only should be fine. -- `startB` compiles when `App` is `@final`, so the second reference likely comes from the call to - `this.read` going through the vtable. -- `moveAside`: a field read stored into another field, with the source cleared right after, is a move - of the field's value, as `[a, b] = [b, a]` already is. - -Worked around in powder_sandbox with the exchange `[l, this.level] = [this.level, l]`. +- `startA` ("moved here on some paths only"): a value moved on some ways only is fine when, on every + other way to its release, a branch tested it empty (`if (l)`, `if (!l) return;`, `l !== null`). There + it holds nothing, so the release frees nothing and goes (`emptyWhereNotMoved`). `if (l && n == "y")` + is still an error. +- `startB` ("takes a second reference"): `this.read(n)` goes through the vtable, since another module + may override `read`. The result of such a call is the caller's when no method of the family says it + borrows (`@lends`, `@borrows`, `@record`, a `this` result) and each one defined here returns its own. + An override in another module may not say it borrows when the method it overrides does not. Under + own that is an error now: "method 'read' returns a borrow ..., but the method of 'Base' it overrides + does not". +- `moveAside` ("borrows a field and cannot be stored"): a field read stored into another place and the + source field refilled right after is a move, as the exchange `[a, this.f] = [this.f, a]` (spec 77) + already was. Between the store and the refill there may be only reads, constants and rc's counts of + `null`. A call in between is still an error. + +Regression tests `tslang/test/tester/tests/00tslang_issue_49.ts` (every model), +`own/own_err_moved_when_tested_other.ts`, `own_err_field_moved_call_between.ts` and +`own_err_override_lends.ts`. powder_sandbox's exchange workaround still works. diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index 6390d1b56..7eebd2d28 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -1455,8 +1455,19 @@ class MLIRTypeHelper } MatchResult TestFunctionTypesMatchWithObjectMethods(mlir::Location location, mlir_ts::FunctionType inFuncType, mlir_ts::FunctionType resFuncType, - unsigned startParamIn = 0, unsigned startParamRes = 0) + unsigned startParamIn = 0, unsigned startParamRes = 0, bool asGiven = false) { + // The parameters as they are first: a leading `Opaque` may be a real one, not a receiver - + // `(a: Opaque, b: Opaque) => s32`, a C comparator, given a closure over a variable + if (!asGiven) + { + auto plain = TestFunctionTypesMatchWithObjectMethods(location, inFuncType, resFuncType, startParamIn, startParamRes, true); + if (plain.result == MatchResultType::Match) + { + return plain; + } + } + LLVM_DEBUG(llvm::dbgs() << "\n!!" << "@ TestFunctionTypesMatchWithObjectMethods:" << inFuncType << " -> " << resFuncType << "\n";); @@ -1466,25 +1477,25 @@ class MLIRTypeHelper // 1 we need to skip opaque and objects // TODO: we need to refactor func types the way that we can understand if this is func with "captured var", bound to object etc - if (startParamIn <= 0 && inFuncType.getNumInputs() > 0 && + if (!asGiven && startParamIn <= 0 && inFuncType.getNumInputs() > 0 && (isa(inFuncType.getInput(0)) || isa(inFuncType.getInput(0)))) { startParamIn = 1; } - if (startParamIn <= 1 && inFuncType.getNumInputs() > 1 && + if (!asGiven && startParamIn <= 1 && inFuncType.getNumInputs() > 1 && (isa(inFuncType.getInput(1)) || isa(inFuncType.getInput(1)))) { startParamIn = 2; } - if (startParamRes <= 0 && resFuncType.getNumInputs() > 0 && + if (!asGiven && startParamRes <= 0 && resFuncType.getNumInputs() > 0 && (isa(resFuncType.getInput(0)) || isa(resFuncType.getInput(0)))) { startParamRes = 1; } - if (startParamRes <= 1 && resFuncType.getNumInputs() > 1 && + if (!asGiven && startParamRes <= 1 && resFuncType.getNumInputs() > 1 && (isa(resFuncType.getInput(1)) || isa(resFuncType.getInput(1)))) { startParamRes = 2; diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 2c1b5f5d1..e60cab6c2 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -724,6 +724,15 @@ namespace typescript if (filterName(accessor.name)) continue; + // no override (TSLANG 48) + if (method.isFinal && !method.isStatic && + ((accessor.get && accessor.get.name == method.funcName) || (accessor.set && accessor.set.name == method.funcName))) + { + os.indent(4); + os << "@" FINAL_DECORATOR; + newline(); + } + if (accessor.get && accessor.get.name == method.funcName) { printAccessorGet(accessor); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 56a476f2e..5f580eca7 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -769,6 +769,13 @@ namespace mlirgen auto getMethodInfo = findMethodInfo(getFunc); auto setMethodInfo = findMethodInfo(setFunc); + // @final accessors (TSLANG 48): no subclass overrides them, so the ones this class has run + if ((getMethodInfo || setMethodInfo) && (!getMethodInfo || getMethodInfo->isFinal) && + (!setMethodInfo || setMethodInfo->isFinal)) + { + finalReceiver = true; + } + // a @final receiver's accessor is the one this class has, called directly when the class // is defined in this module, as a method is (ClassMethodAccess) auto direct = finalReceiver && !classInfo->isDeclaration && !classInfo->isImport && diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index dea46c2d5..67ba61a2e 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -409,6 +409,54 @@ namespace mlirgen }); } + mlir::LogicalResult MLIRGenImpl::checkNotClosureAtRunTime(mlir::Location location, mlir::Value value, const GenContext &genContext) + { + // a function by name, made a function value: nothing to test + for (auto current = value; current;) + { + auto *def = current.getDefiningOp(); + if (!def) + { + break; + } + + if (auto castOp = dyn_cast(def)) + { + if (castOp.getIn().getDefiningOp() && isa(castOp.getIn().getType())) + { + return mlir::success(); + } + + current = castOp.getIn(); + continue; + } + + break; + } + + auto thisVal = builder.create(location, getOpaqueType(), value); + auto isBound = builder.create(location, getBooleanType(), thisVal); + auto ifOp = builder.create(location, isBound, false); + mlir::OpBuilder::InsertionGuard guard(builder); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto message = builder.create( + location, getStringType(), + getStringAttr("a closure or a bound method can't be used as a plain function pointer: the pointer carries " + "no captured variables and no 'this'")); + builder.create(location, message); + + MLIRRTTIHelperVC rtti(builder, theModule, compileOptions); + setCatchCopyThunkBuilder(rtti); + if (!rtti.setRTTIForType(location, message.getType(), + [&](StringRef classFullName) { return getClassInfoByFullName(classFullName); })) + { + emitError(location, "Not supported type in throw"); + return mlir::failure(); + } + + return mlir::success(); + } + ValueOrLogicalResult MLIRGenImpl::castFieldsToClass(mlir::Location location, mlir::Value value, ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, mlir_ts::ClassType classType, const GenContext &genContext, bool errorAsWarning) diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index c979025db..fa57483f3 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4918,6 +4918,11 @@ genContext); classMethodMemberInfo.setFuncOp(funcOp); if (classMethodMemberInfo.registerClassMethodMember(loc(funcLikeDeclaration), orderWeight, accessLevel)) { + if (mlir::failed(checkOverrideResultFacts(loc(funcLikeDeclaration), newClassPtr, classMethodMemberInfo))) + { + return mlir::failure(); + } + // C++ methods: not a constructor, nor `.new` (static) if (!classMethodMemberInfo.isConstructor && !classMethodMemberInfo.isStatic && mlir::failed(mlirGenClassCppVTableHiddenReturn(loc(funcLikeDeclaration), newClassPtr, funcOp, @@ -5483,5 +5488,66 @@ genContext); return instance; } + mlir::LogicalResult MLIRGenImpl::checkOverrideResultFacts(mlir::Location location, ClassInfo::TypePtr classInfo, + ClassMethodMemberInfo &member) + { + if (compileOptions.memoryModel != MemoryModelOwn || member.isStatic || member.isConstructor) + { + return mlir::success(); + } + + auto index = classInfo->getMethodIndex(member.methodName); + if (index < 0) + { + return mlir::success(); + } + + auto saysBorrow = [](const MethodInfo &method) { + return method.ownLendsMask != 0 || !method.ownBorrows.empty() || method.ownRecord || method.ownReturnsThis; + }; + + auto &method = classInfo->methods[index]; + if (!saysBorrow(method)) + { + return mlir::success(); + } + + // the nearest base that has the method + std::function overridden = [&](ClassInfo::TypePtr of) -> ClassInfo::TypePtr { + for (auto &baseClass : of->baseClasses) + { + if (baseClass->getMethodIndex(member.methodName) >= 0) + { + return baseClass; + } + + if (auto found = overridden(baseClass)) + { + return found; + } + } + + return nullptr; + }; + + auto baseClass = overridden(classInfo); + if (!baseClass) + { + return mlir::success(); + } + + auto &baseMethod = baseClass->methods[baseClass->getMethodIndex(member.methodName)]; + if (baseMethod.isStatic || saysBorrow(baseMethod)) + { + return mlir::success(); + } + + emitError(location) << "method '" << member.methodName << "' returns a borrow ('@lends', '@borrows', '@record' or " + << "the result type 'this'), but the method of '" << baseClass->name + << "' it overrides does not: under -mm=own a call through '" << baseClass->name + << "' takes the result for its own"; + return mlir::failure(); + } + } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 28b3c4947..ce1bce53c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -11133,6 +11133,15 @@ class MLIRGenImpl return mlir::failure(); } + // A function value (`const f: () => void = ...`, a callback parameter) may be a closure + // at run time: its bound value is checked, and a closure is an error there instead of + // a C function that reads its captures through garbage (TSLANG_ISSUES 29) + if (isa(value.getType()) && isa(argTypeDestFuncType) && + mlir::failed(checkNotClosureAtRunTime(location, value, genContext))) + { + return mlir::failure(); + } + CAST_A(castValue, location, argTypeDestFuncType, value, genContext); if (auto castOp = castValue.getDefiningOp(); @@ -14491,6 +14500,19 @@ class MLIRGenImpl mlir::LogicalResult mlirGenClassVirtualTableDefinition(mlir::Location location, ClassInfo::TypePtr newClassPtr, const GenContext &genContext); + struct ClassMethodMemberInfo; + + // TSLANG_ISSUES 29: a function value given as a C function pointer must not hold a closure's + // captures or a bound `this`: unless it is a function named directly (seen through its views + // and the `const`s that hold it), a run-time test throws when it does. + mlir::LogicalResult checkNotClosureAtRunTime(mlir::Location location, mlir::Value value, const GenContext &genContext); + + // -mm=own (TSLANG 49): a caller through the base takes the result of a method it cannot resolve for + // its own when no method of the family says the result borrows. So an override may not say so + // (`@lends`, `@borrows`, `@record`, a result of type `this`) when the method it overrides does not. + mlir::LogicalResult checkOverrideResultFacts(mlir::Location location, ClassInfo::TypePtr classInfo, + ClassMethodMemberInfo &member); + struct ClassMethodMemberInfo { ClassMethodMemberInfo(ClassInfo::TypePtr newClassPtr, ClassElement classMember) : newClassPtr(newClassPtr), classMember(classMember) @@ -14569,8 +14591,9 @@ class MLIRGenImpl { if (auto finalOwner = finalMethodOwner(newClassPtr, methodName)) { - emitError(location) << "method '" << methodName << "' overrides the @" FINAL_DECORATOR " method of '" - << finalOwner->name << "'"; + auto isAccessor = classMember == SyntaxKind::GetAccessor || classMember == SyntaxKind::SetAccessor; + emitError(location) << (isAccessor ? "accessor '" : "method '") << getName() << "' overrides the @" FINAL_DECORATOR + << (isAccessor ? " accessor of '" : " method of '") << finalOwner->name << "'"; return false; } } diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 2dbcde646..300487f7d 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1297,6 +1297,62 @@ inline bool mayWriteField(mlir::Operation *op, mlir_ts::PropertyRefOp field, mli return writes; } +// Does every way from `definition`, where `value` is made, to `release` that does not run `move`'s +// block leave a branch on which `value` was tested empty (testedEmpty): `if (l) { this.f = l; }`? On +// those ways the value holds no block, and its release there frees nothing (TSLANG 49). A way back to +// the definition's block makes a new value; it ends there. +inline bool emptyWhereNotMoved(mlir::Value value, mlir::Operation *definition, mlir::Operation *move, mlir::Operation *release) +{ + auto *start = definition ? definition->getBlock() : nullptr; + if (!start || !move || start == release->getBlock() || start->getParent() != release->getBlock()->getParent() || + start->getParent() != move->getBlock()->getParent()) + { + return false; + } + + auto root = rootOf(value); + llvm::SmallPtrSet seen{start}; + llvm::SmallVector work{start}; + while (!work.empty()) + { + auto *block = work.pop_back_val(); + auto *terminator = block->getTerminator(); + auto condBrOp = mlir::dyn_cast_or_null(terminator); + for (unsigned index = 0; terminator && index < terminator->getNumSuccessors(); ++index) + { + auto *successor = terminator->getSuccessor(index); + if (condBrOp && condBrOp.getTrueDest() != condBrOp.getFalseDest()) + { + mlir::Value condition = condBrOp.getCondition(); + if (auto castOp = condition.getDefiningOp()) + { + condition = castOp->getOperand(0); + } + + auto tested = testedEmpty(condition, successor == condBrOp.getTrueDest()); + if (tested && rootOf(tested) == root) + { + continue; // empty from here on + } + } + + if (successor == release->getBlock()) + { + return false; + } + + if (successor == move->getBlock() || successor == start || !seen.insert(successor).second) + { + continue; + } + + work.push_back(successor); + } + } + + return true; +} + // Is this release of a field's old value a fill (TSLANG 47): the field was tested empty on the way // here, and nothing that may write it ran since? The test reads the field itself, or a `let` or // `const` declared from it that nothing assigns before the test (`let r = this.cached; if (!r) {...}`), diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index f6e0c4448..730b83176 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -1003,7 +1003,9 @@ namespace own_inference continue; } - if (!dominance->properlyDominates(acquire, release)) + // moved on some ways only: on the others it must be empty (TSLANG 49) + if (!dominance->properlyDominates(acquire, release) && + !emptyWhereNotMoved(value, definition, acquire, release)) { reportMovedOnSomePaths(taker, release, name); return false; diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 0369d0ac3..489360adb 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -1364,6 +1364,13 @@ namespace own_inference continue; } + // the release of what the taker's place held, right before the store into it (TSLANG 49) + if (auto releaseSlotOp = mlir::dyn_cast(op); + releaseSlotOp && !intoLocal && releaseSlotOp.getSlot() == storeOp.getReference() && op->getNextNode() == taker) + { + continue; + } + if (auto releaseSlotOp = mlir::dyn_cast(op)) { // a local's own release (the taker's assignment), never of the place's object @@ -1397,6 +1404,41 @@ namespace own_inference return false; } + // ...or refilled right after the taker (TSLANG 49): `this.other = this.level; this.level = null;` + // moves the field into another. The same field of the same object, its release right before + // the store that refills it, with only reads, constants and views between - nothing that could + // free or read what both places hold until then. + if (!refillRelease && retained) + { + auto field = place.getDefiningOp(); + for (auto *op = field ? taker->getNextNode() : nullptr; op; op = op->getNextNode()) + { + if (auto releaseSlotOp = mlir::dyn_cast(op)) + { + auto refillField = releaseSlotOp.getSlot().getDefiningOp(); + auto refillStore = mlir::dyn_cast_or_null(op->getNextNode()); + if (refillField && sameField(refillField, field) && refillStore && + refillStore.getReference() == releaseSlotOp.getSlot()) + { + refillRelease = op; + } + + break; + } + + // rc's retain of the refill's value, when that holds no block (`null`) + auto retainsNothing = mlir::isa(op) && holdsNoBlock(op->getOperand(0)); + // ...and that value, `null` cast to the field's union + auto castsNothing = mlir::isa(op) && holdsNoBlock(op->getResult(0)); + if (!mlir::isa(op) && + !isView(op) && !retainsNothing && !castsNothing) + { + break; + } + } + } + if (!refillRelease) { return false; diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 73dfeba84..12ce9eb4e 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -257,10 +257,27 @@ namespace own_signature callee = getMethodOp.getBoundFunc(); } - auto refOp = callee ? callee.getDefiningOp() : mlir_ts::ThisVirtualSymbolRefOp(); + // a method's slot, or an accessor's + auto *refDef = callee ? callee.getDefiningOp() : nullptr; + auto methodRef = mlir::dyn_cast_or_null(refDef); + auto accessorRef = mlir::dyn_cast_or_null(refDef); + auto *refOp = methodRef ? methodRef.getOperation() : accessorRef ? accessorRef.getOperation() : nullptr; + auto identifier = methodRef ? methodRef.getIdentifierAttr() : accessorRef ? accessorRef.getIdentifierAttr() + : mlir::FlatSymbolRefAttr(); + int64_t slotIndex = methodRef ? static_cast(methodRef.getIndex()) + : accessorRef ? static_cast(accessorRef.getIndex()) : -1; if (refOp && !refOp->hasAttr(FINAL_RECEIVER_ATTR_NAME)) { - call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, refOp.getIdentifierAttr()); + call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, identifier); + + // ...whose result is the caller's when no method of the family says it borrows: an + // override in another module may not say so either (checkOverrideResultFacts), and + // one that returns a borrow without saying it is an error there (TSLANG 49) + if (call.op->getNumResults() == 1 && !isRecordResult(call.op) && + familyResultsFresh(slotIndex, identifier.getAttr())) + { + call.op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } } continue; @@ -1650,6 +1667,22 @@ namespace own_signature computeDropsRound(true); } + bool OwnershipSignaturePass::familyResultsFresh(int64_t index, mlir::StringAttr identifier) + { + for (auto member : familyOf(index, identifier)) + { + auto funcOp = functions.lookup(member.getValue()); + if (!funcOp || funcOp->hasAttr(OWN_DECLARED_LENDS_ATTR_NAME) || funcOp->hasAttr(OWN_DECLARED_BORROWS_ATTR_NAME) || + funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME) || funcOp->hasAttr(OWN_IMPLIED_LENDS_ATTR_NAME) || + (!funcOp.isDeclaration() && !returnsFresh(funcOp))) + { + return false; + } + } + + return true; + } + bool OwnershipSignaturePass::isFill(mlir_ts::ReleaseSlotOp releaseSlotOp) { return releaseSlotOp->hasAttr(OWN_FILL_ATTR_NAME); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index c94854f9a..1172dfc79 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -626,6 +626,11 @@ class OwnershipSignaturePass : public mlir::PassWrapper callOf; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 4a9eb095e..d37c10372 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1903,8 +1903,9 @@ endforeach() # TSLANG_ISSUES 46: a function returning its union parameter, given a new object, freed it twice # TSLANG_ISSUES 47: a lazily cached field returned through a local; a fill of an empty field frees nothing # TSLANG_ISSUES 48: a @final method of an exported class is called directly, by its own facts +# TSLANG_ISSUES 49: a nullable local moved when not null, a virtual call's own result, a field moved into another foreach(issues_mm gc rc none own) - foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48) + foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -1921,6 +1922,10 @@ add_test(NAME test-compile-final-method-override-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_override_error.ts") set_tests_properties(test-compile-final-method-override-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' overrides the @final method of 'Base'" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-final-accessor-override-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_accessor_override_error.ts") +set_tests_properties(test-compile-final-accessor-override-error PROPERTIES PASS_REGULAR_EXPRESSION "accessor 'factor' overrides the @final accessor of 'Base'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") add_test(NAME test-compile-final-method-abstract-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_abstract_error.ts") set_tests_properties(test-compile-final-method-abstract-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' cannot be both abstract and @final" @@ -1948,6 +1953,10 @@ endif() foreach(issues_mm gc rc none own) tslang_add_test(NAME test-jit-00-tslang-issue-29-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") tslang_add_test(NAME test-compile-00-tslang-issue-29-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") + tslang_add_test(NAME test-jit-00-tslang-issue-29-function-value-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_function_value.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-29-function-value-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_function_value.ts") + tslang_add_test(NAME test-jit-00-tslang-issue-29-comparator-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_comparator.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-29-comparator-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_comparator.ts") tslang_add_test(NAME test-jit-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") tslang_add_test(NAME test-compile-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") endforeach() @@ -5435,7 +5444,10 @@ set(own_error_cases "own_err_fill_after_call|:21:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_in_loop|:23:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_other_field|:20:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" - "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten") + "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten" + "own_err_moved_when_tested_other|:13:13: error: '[^']*' is moved here on some paths only" + "own_err_field_moved_call_between|:12:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_field_moved_call_between.ts b/tslang/test/tester/own/own_err_field_moved_call_between.ts new file mode 100644 index 000000000..3fe1fa178 --- /dev/null +++ b/tslang/test/tester/own/own_err_field_moved_call_between.ts @@ -0,0 +1,18 @@ +// TSLANG_ISSUES 49: one field moved into another and the source cleared - but a call in between may +// free or read what both fields hold, so the move is refused. +class Level { + name: string = "a"; +} + +class App { + level: Level | null = new Level(); + other: Level | null = null; + side() { this.other = null; } + moveAside() { + this.other = this.level; + this.side(); + this.level = null; + } +} + +function main() { const a = new App(); a.moveAside(); print(a.other != null); } diff --git a/tslang/test/tester/own/own_err_moved_when_tested_other.ts b/tslang/test/tester/own/own_err_moved_when_tested_other.ts new file mode 100644 index 000000000..ab70c9726 --- /dev/null +++ b/tslang/test/tester/own/own_err_moved_when_tested_other.ts @@ -0,0 +1,18 @@ +// TSLANG_ISSUES 49: a fresh local moved into a field on some ways only is fine when on the others it +// was tested empty - not here, where `n == "y"` may be false while `l` holds an object. +class Level { + name: string = "a"; +} + +class App { + level: Level | null = null; + read(n: string): Level | null { return n == "" ? null : new Level(); } + start(n: string) { + const l = this.read(n); + if (l && n == "y") { + this.level = l; + } + } +} + +function main() { const a = new App(); a.start("x"); print(a.level != null); } diff --git a/tslang/test/tester/own/own_err_override_lends.ts b/tslang/test/tester/own/own_err_override_lends.ts new file mode 100644 index 000000000..ac32165d8 --- /dev/null +++ b/tslang/test/tester/own/own_err_override_lends.ts @@ -0,0 +1,16 @@ +// TSLANG_ISSUES 49: a caller through `Base` takes `read`'s result for its own, since `Base.read` does not +// say it borrows; so an override may not say it does. +class Level { + name: string = "a"; +} + +export class Base { + keep: Level = new Level(); + read(): Level { return new Level(); } +} + +export class Der extends Base { + @lends("this") read(): Level { return this.keep; } +} + +function main() { print(new Der().read().name); } diff --git a/tslang/test/tester/tests/00tslang_issue_29_comparator.ts b/tslang/test/tester/tests/00tslang_issue_29_comparator.ts new file mode 100644 index 000000000..d94b3f97a --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_comparator.ts @@ -0,0 +1,21 @@ +// TSLANG_ISSUES 29: a C comparator given as a function value. A capturing arrow assigned to a type whose +// parameters are `Opaque` (`(a: Opaque, b: Opaque) => s32`) was refused: the leading `Opaque` was taken +// for a receiver. It is a closure now, callable directly; given to qsort through a variable or a +// parameter, a plain function sorts and a closure throws (it has captures the C pointer can't carry). +@cdecl declare function qsort(base: Opaque, count: index, size: index, compare: (a: Opaque, b: Opaque) => s32): void; +type Cmp = (a: Opaque, b: Opaque) => s32; +function byValue(a: Opaque, b: Opaque): s32 { return Deref(>a) - Deref(>b); } +function sortWith(items: s32[], compare: Cmp): boolean { + try { qsort(Ref(items[0]), items.length, 4, compare); } catch (e) { return false; } + return true; +} +function main() { + const items: s32[] = [3, 1, 2]; + const viaPlain: Cmp = byValue; + assert(sortWith(items, viaPlain) && items[0] == 1 && items[1] == 2 && items[2] == 3, "a plain function"); + const offset = 0; + const capturing: Cmp = (a: Opaque, b: Opaque) => (byValue(b, a) + offset); + assert(capturing(Ref(items[0]), Ref(items[1])) > 0, "a closure called directly"); + assert(!sortWith(items, capturing), "a closure as a C comparator throws"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_29_function_value.ts b/tslang/test/tester/tests/00tslang_issue_29_function_value.ts new file mode 100644 index 000000000..757c477c0 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_function_value.ts @@ -0,0 +1,32 @@ +// TSLANG_ISSUES 29: a function value - a `const` of function type, a callback parameter - given to a +// @cdecl function's callback parameter. A plain function passes as a C function pointer; a closure, +// whose captures the pointer can't carry, throws there instead of running later with none. +@cdecl declare function atexit(fn: () => void): s32; + +function plain() { + print("plain at exit"); +} + +function register(f: () => void) { + atexit(f); +} + +function main() { + let n = 42; + const viaPlain: () => void = plain; + atexit(viaPlain); + register(plain); + + let caught = false; + try { + const viaClosure: () => void = () => { + print("closure sees", n); + }; + register(viaClosure); + } catch (e) { + caught = true; + } + + assert(caught, "a closure as a C function pointer throws"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_48.ts b/tslang/test/tester/tests/00tslang_issue_48.ts index 8a06a85d4..036bcfe96 100644 --- a/tslang/test/tester/tests/00tslang_issue_48.ts +++ b/tslang/test/tester/tests/00tslang_issue_48.ts @@ -15,6 +15,11 @@ export class Base { return this.scale; } + // a @final getter, as a @final method + @final get doubled(): number { + return this.scale * 2; + } + // a method that is not final, overridden below: still called through the vtable bonus(): number { return 0; @@ -25,7 +30,8 @@ export class App extends Base { total(): number { const item = this.items[1]; const f = this.factor(); - return item.n * f + this.bonus(); + const d = this.doubled; + return item.n * f + this.bonus() + d - 4; } bonus(): number { diff --git a/tslang/test/tester/tests/00tslang_issue_49.ts b/tslang/test/tester/tests/00tslang_issue_49.ts new file mode 100644 index 000000000..77ad82169 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_49.ts @@ -0,0 +1,62 @@ +// TSLANG_ISSUES 49 (-mm=own), reduced by powder_sandbox: +// - startA: a nullable fresh local moved into a field when it is not null. On the other way it is +// null and holds nothing, so its release there frees nothing. +// - startB: the result of a method of an exported class, called through its vtable, is the caller's +// when no method of its family says it borrows (an override may not say it either). +// - moveAside: one field moved into another, the source cleared right after. + +class Level { + name: string = "a"; +} + +export class App { + level: Level | null = null; + other: Level | null = null; + + read(n: string): Level | null { + return n == "" ? null : new Level(); + } + + startA(n: string) { + const l = this.read(n); + if (l) { + this.level = l; + } + } + + startA2(n: string) { + const l = this.read(n); + if (!l) { + return; + } + + this.level = l; + } + + startB(n: string) { + const l = this.read(n); + this.level = l; + } + + moveAside() { + this.other = this.level; + this.level = null; + } +} + +function main() { + const a = new App(); + a.startA(""); + assert(a.level == null); + a.startA("x"); + assert(a.level != null); + a.startA2(""); + a.startA2("y"); + a.startB("x"); + a.moveAside(); + print(a.level != null, a.other != null); + assert(a.level == null && a.other != null && a.other.name == "a"); + a.startB(""); + assert(a.level == null); + print("done."); +} diff --git a/tslang/test/tester/tests/final_accessor_override_error.ts b/tslang/test/tester/tests/final_accessor_override_error.ts new file mode 100644 index 000000000..2127a28ea --- /dev/null +++ b/tslang/test/tester/tests/final_accessor_override_error.ts @@ -0,0 +1,10 @@ +// TSLANG_ISSUES 48: a @final accessor cannot be overridden +class Base { + @final get factor(): number { return 1; } +} + +class App extends Base { + get factor(): number { return 2; } +} + +function main() { print(new App().factor); } diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index e9054ae94..ebe14774a 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -76,9 +76,10 @@ set(not_compilable_alone cdecl_closure_error.ts # an error by design (test-compile-computed-name-failed-error) computed_name_failed_error.ts - # errors by design (test-compile-final-method-override-error, -abstract-error) + # errors by design (test-compile-final-method-override-error, -abstract-error, final-accessor-override-error) final_method_override_error.ts final_method_abstract_error.ts + final_accessor_override_error.ts # an error by design (test-compile-generic-self-recursion-untyped-error) generic_self_recursion_untyped_error.ts) diff --git a/tslang/test/wasm/wasm_skips.txt b/tslang/test/wasm/wasm_skips.txt index 32b30e1a1..0d10e9777 100644 --- a/tslang/test/wasm/wasm_skips.txt +++ b/tslang/test/wasm/wasm_skips.txt @@ -6,6 +6,7 @@ internals.ts # inline_asm with x86 instructions 00any_to_opaque_narrow.ts wasm32 # stores a u64 in an Opaque: a pointer is 4 bytes on wasm32 00tslang_issue_29_pthread.ts # starts threads through pthread_create: the host starts them only through Thread.spawn 00tslang_issue_29_thread.ts # starts threads through _beginthreadex: the host starts them only through Thread.spawn +00tslang_issue_29_function_value.ts # registers C exit handlers through atexit, which the host may not provide 00stdcall_winapi.ts # calls the Windows API (GetCurrentProcessId): the host has none of it 00cppvtable_hidden_return.ts # a @cpp class returning a struct needs the MSVC or a 64-bit Itanium ABI (excluded on i686 too) fetch.ts # (default library) fetch(): the host has no network, so the request throws