Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 33 additions & 22 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
21 changes: 16 additions & 5 deletions tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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";);

Expand All @@ -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<mlir_ts::OpaqueType>(inFuncType.getInput(0)) || isa<mlir_ts::ObjectType>(inFuncType.getInput(0))))
{
startParamIn = 1;
}

if (startParamIn <= 1 && inFuncType.getNumInputs() > 1 &&
if (!asGiven && startParamIn <= 1 && inFuncType.getNumInputs() > 1 &&
(isa<mlir_ts::OpaqueType>(inFuncType.getInput(1)) || isa<mlir_ts::ObjectType>(inFuncType.getInput(1))))
{
startParamIn = 2;
}

if (startParamRes <= 0 && resFuncType.getNumInputs() > 0 &&
if (!asGiven && startParamRes <= 0 && resFuncType.getNumInputs() > 0 &&
(isa<mlir_ts::OpaqueType>(resFuncType.getInput(0)) || isa<mlir_ts::ObjectType>(resFuncType.getInput(0))))
{
startParamRes = 1;
}

if (startParamRes <= 1 && resFuncType.getNumInputs() > 1 &&
if (!asGiven && startParamRes <= 1 && resFuncType.getNumInputs() > 1 &&
(isa<mlir_ts::OpaqueType>(resFuncType.getInput(1)) || isa<mlir_ts::ObjectType>(resFuncType.getInput(1))))
{
startParamRes = 2;
Expand Down
9 changes: 9 additions & 0 deletions tslang/lib/TypeScript/DeclarationPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
7 changes: 7 additions & 0 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand Down
48 changes: 48 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::CastOp>(def))
{
if (castOp.getIn().getDefiningOp<mlir_ts::SymbolRefOp>() && isa<mlir_ts::FunctionType>(castOp.getIn().getType()))
{
return mlir::success();
}

current = castOp.getIn();
continue;
}

break;
}

auto thisVal = builder.create<mlir_ts::GetThisOp>(location, getOpaqueType(), value);
auto isBound = builder.create<mlir_ts::CastOp>(location, getBooleanType(), thisVal);
auto ifOp = builder.create<mlir_ts::IfOp>(location, isBound, false);
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
auto message = builder.create<mlir_ts::ConstantOp>(
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<mlir_ts::ThrowOp>(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)
Expand Down
66 changes: 66 additions & 0 deletions tslang/lib/TypeScript/MLIRGenClasses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<ClassInfo::TypePtr(ClassInfo::TypePtr)> 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
27 changes: 25 additions & 2 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::HybridFunctionType>(value.getType()) && isa<mlir_ts::FunctionType>(argTypeDestFuncType) &&
mlir::failed(checkNotClosureAtRunTime(location, value, genContext)))
{
return mlir::failure();
}

CAST_A(castValue, location, argTypeDestFuncType, value, genContext);

if (auto castOp = castValue.getDefiningOp<mlir_ts::CastOp>();
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}
}
Expand Down
Loading
Loading