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
125 changes: 13 additions & 112 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,115 +47,16 @@ tslang now checks the runtime's `TypeScriptAsyncRuntime.lib` before linking a li
older than the compiler. `-v` is an alias for `--verbose`, which prints the linker's command line, so
the linker's "use -v" hint works.

Items 31-33 are `-mm=own` limits found in the default library (TypeScriptCompilerDefaultLib), not in
native_ts_graphics. There the tests `thread_spawn.ts` and `atomics_wait.ts` are marked `// not own`
because of them. Each repro was compiled with `--emit=exe` (the JIT's default-library DLL didn't
link against this build) and runs under `-mm=gc` with the output shown.

### 31. `-mm=own`: two closures can't capture the same array

tslang (commit 94b8bdb2, built with uncommitted local changes). Found 2026-11-08.

A closure passed to `Thread.spawn` moves what it captures, so a second closure capturing the same
`Int32Array` is a use after move. Threads can't share memory under `-mm=own`, which is what
`Atomics` is for. A single capture is fine: in the third repro the main thread still reads the
array after the thread captured it. The error names `'this value'`, not `counter`, and points at the
second arrow function rather than at `counter` inside it.

Repro (`share_two.ts`):
```ts
// -mm=own: two threads that capture the same Int32Array
function main() {
const counter = new Int32Array([0]);
const a = Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; });
const b = Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; });
a.join();
b.join();
print(Atomics.load(counter, 0));
}
```

`-mm=gc` prints `2`. `-mm=own`:
```
share_two.ts:5:28: error: 'this value' is used here after its value was moved
const b = Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; });
^
share_two.ts:4:28: note: value moved here
const a = Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; });
^
```

The same in a loop (`share_loop.ts`), the usual way to start workers, gives a different error:
```ts
// -mm=own: threads spawned in a loop, each capturing the same Int32Array
function main() {
const counter = new Int32Array([0]);
const workers: ThreadHandle<int>[] = [];
for (let t = 0; t < 4; t++) {
workers.push(Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; }));
}

for (const w of workers) w.join();
print(Atomics.load(counter, 0));
}
```

`-mm=gc` prints `4`. `-mm=own`:
```
share_loop.ts:6:35: error: 'this value' is moved inside a loop but was made outside it; only a borrow could do that, and -mm=own cannot prove one yet
workers.push(Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; }));
^
```

One capture compiles and runs under both models, printing `1` (`share_after.ts`):
```ts
// -mm=own: the main thread uses the Int32Array after a thread captured it
function main() {
const counter = new Int32Array([0]);
const a = Thread.spawn((): int => { Atomics.add(counter, 0, 1); return 0; });
a.join();
print(Atomics.load(counter, 0));
}
```

Expected: a way to share one array between threads under `-mm=own`, such as `Shared<T>` captured by
each closure, or a capture that borrows when the closure can't outlive the array.

### 32. `-mm=own`: the error for a move in a loop doesn't say what was moved

tslang (commit 94b8bdb2, built with uncommitted local changes). Found 2026-11-08.

Both errors in 31 call the captured variable `'this value'`. In a program with several captures,
nothing says which one is moved. The error should name `counter` and point at its use inside the
arrow function.

### 33. `-mm=own`: a thread can't return an object, and the error points into the default library

tslang (commit 94b8bdb2, built with uncommitted local changes). Found 2026-11-08.

`Thread.spawn` keeps the function's result in a field of `ThreadStart<R>` for `join()` to return.
When `R` is a class, storing it is rejected. The error is reported in the default library's
`lib.generics.ts` (`this.result = result;` in `ThreadStart.run`) with no line in the user's program,
so nothing points at the `Thread.spawn` call that caused it. A string or a number works.

Repro (`return_object.ts`):
```ts
// -mm=own: a thread whose function returns an object
class Box {
constructor(public value: int) {}
}

function main() {
const t = Thread.spawn((): Box => new Box(42));
print(t.join().value);
}
```

`-mm=gc` prints `42`. `-mm=own`:
```
.\__build\defaultlib\generics/lib.generics.ts:857:13: error: 'this value' takes a second reference; -mm=own cannot prove a move or a borrow here yet
```

`const result = this.fn(); this.result = result;` moves a value the function just returned, which
the field should be able to take. Expected: the move is accepted. Failing that, the error should
also name the instantiating call in the user's file.
Items 31-33, `-mm=own` limits found in the default library on 2026-11-08, are fixed too, and
`thread_spawn.ts` and `atomics_wait.ts` there now run under every model. 31 (two closures couldn't
capture the same array): a closure that escapes owns what it captures, so that stays an error for a
plain object, and `Shared<T>` is the way to share one. A `const` `Shared<T>` is now captured by copy, so
any number of closures hold a counted handle each, in a loop too; under `-mm=own` a handle's count is
always atomic, since handles are what threads share. 32 (the error said `'this value'` and pointed at
the arrow): the error about a captured variable now names it, with or without `--di`, points at its
first use in the closure, and says to use a `const Shared<T>`. 33 (`this.result = this.fn()` was refused
when `R` is a class): the result of a call through a callback is the caller's when every function that
can reach the call is defined in the module and none returns a borrow of its argument. A callback that
gives back its argument or what it captured is still refused. Regression tests
`tslang/test/tester/tests/00tslang_issues_31_33.ts` and `tslang/test/tester/own/own_err_capture_*.ts`,
`own_err_callback_result_*.ts`.
Original file line number Diff line number Diff line change
Expand Up @@ -5611,3 +5611,33 @@ Array<Item> whether called or not.
The default library marks the functions above in `__Array` and in Array<T>; Array<T>'s push, unshift
and splice move elements as §72 says, and splice removes by swapping each to the end and popping it.

## 74. What threads need: a callback's result, and a handle in several closures, 2026-11-08

`Thread.spawn` keeps its function in a field and the function's result in another, and threads that
share memory capture it (TSLANG_ISSUES 31-33).

**A callback's result.** A call through a function value had no fresh result, so `this.result =
this.fn()` was a second reference. Where the signature pass has resolved the call to a closed callback
family (`Callees::viaCallback`), it knows every function that can be called: each returns its result
retained as any function does, and one that returns a borrow of a parameter says so in its facts. So
when every member is defined here and no member's facts have `borrows` or `record`, the call is
`__own_fresh_result`. A body that returns what it does not own (a capture, a global that can be
assigned) is refused where it is written, whichever way it is called.

**A handle in several closures.** A `const` Shared<T> has a slot (identity storage), which made it a
read-write variable, captured through its cell, and a cell has one owner. Nothing assigns a `const`,
so it is now captured by copy (`setCaptureByValue`): each box holds a counted handle of its own, and
the box's release gives it back. A `let` Shared<T> keeps its cell.

A box that borrows what it holds (a closure that does not escape, over a parameter's copy or beside a
cell) gives nothing back, so the retain made for a handle in it is erased too, although other handle
retains stay (spec 23.2), and a handle read from a local is then bounded like any other borrowed copy.

**Counts.** Under own only handles are counted, and they are what threads share, so their counts are
always atomic (`CompileOptions::atomicRefCounts`). `Shared.share` stays erased: there is nothing to mark.

**Names.** A captured variable's name is the box field's (`fieldName` of the fill's `ts.PropertyRef`),
which needs no `--di`. MLIRGen records where a closure first uses each capture
(`PassResult::outerVariableUses`) and puts it on the closure (`__capture_uses`, under own only); the
errors about a capture point there. The fill and its retain keep the arrow's location, so debug info
never holds a location from another function's scope.
5 changes: 3 additions & 2 deletions tslang/include/TypeScript/DataStructs.h
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,13 @@ struct CompileOptions
}

// --atomic-rc: every reference count change is an atomic read-modify-write, so objects may
// be shared between threads under `rc`. Only `rc` keeps counts; `own` never counts at all.
// be shared between threads under `rc`. `own` counts only Shared<T> handles, which exist to be
// shared, so it always counts them atomically; `Shared.share` has nothing to mark there.
bool atomicRC = false;

bool atomicRefCounts() const
{
return isRefCounted() && atomicRC;
return (isRefCounted() && atomicRC) || memoryModel == MemoryModelOwn;
}

// Whether the ownership operations are live and lower to code - retains and releases under
Expand Down
4 changes: 4 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@
// closure is built and the difference is known.
#define OWNS_CAPTURE_ATTR_NAME "__owns_capture"

// On such a closure, under -mm=own: a dictionary from each captured variable's name to where the
// closure's body first uses it, which is where an error about the capture points.
#define CAPTURE_USES_ATTR_NAME "__capture_uses"

// On a `ts.CreateBoundFunction` that binds a method to an object: the object's type, which the
// lowering casts `this` away from. Under rc the bound value counts the object through that type's
// tag at CLOSURE_TYPE_INDEX, as an interface over it does.
Expand Down
2 changes: 2 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ struct PassResult
// a generator's next(): its {value, done} is Iterator<T>'s, so a finished one's undefined value is not in T
bool iteratorResult = false;
llvm::StringMap<ts::VariableDeclarationDOM::TypePtr> outerVariables;
// where the function first uses each of them, for the errors about the capture
llvm::StringMap<mlir::LocationAttr> outerVariableUses;
SmallVector<mlir_ts::FieldInfo> extraFieldsInThisContext;
};

Expand Down
2 changes: 2 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h
Original file line number Diff line number Diff line change
Expand Up @@ -1338,6 +1338,8 @@ struct NamespaceInfo

llvm::StringMap<llvm::StringMap<ts::VariableDeclarationDOM::TypePtr>> captureVarsMap;

llvm::StringMap<llvm::StringMap<mlir::LocationAttr>> captureUsesMap;

llvm::StringMap<llvm::SmallVector<mlir::typescript::FieldInfo>> localVarsInThisContextMap;

llvm::StringMap<std::pair<mlir::Type, TypeNode>> typeAliasMap;
Expand Down
15 changes: 15 additions & 0 deletions tslang/lib/TypeScript/MLIRGenFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,7 @@ namespace mlirgen
}

getCaptureVarsMap().insert({name, passResult->outerVariables});
getCaptureUsesMap().insert({name, passResult->outerVariableUses});
funcProto->setHasCapturedVars(true);

LLVM_DEBUG(llvm::dbgs() << "\n!! has captured vars, name: " << name << "\n";);
Expand Down Expand Up @@ -2601,6 +2602,20 @@ namespace mlirgen
// dropped - `apply(v => v.x + base.x, v)` - is released at the end of the block that
// made it (§9.30), which is what gives the box back.
boundFuncVal->setAttr(OWNS_CAPTURE_ATTR_NAME, builder.getUnitAttr());
if (compileOptions.memoryModel == MemoryModelOwn)
{
if (auto captureUses = getCaptureUsesMap().find(name); captureUses != getCaptureUsesMap().end())
{
SmallVector<mlir::NamedAttribute> uses;
for (auto &use : captureUses->getValue())
{
uses.push_back(builder.getNamedAttr(use.getKey(), use.getValue()));
}

boundFuncVal->setAttr(CAPTURE_USES_ATTR_NAME, builder.getDictionaryAttr(uses));
}
}

builder.create<mlir_ts::RetainOp>(location, boundFuncVal);
boundFuncVal->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr());

Expand Down
13 changes: 13 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2216,6 +2216,14 @@ class MLIRGenImpl
if (!isConst || varClass == VariableType::ConstRef || needsIdentityStorage)
{
varDecl->setReadWriteAccess();
// A `const` Shared<T> has a slot, but nothing assigns it: each closure takes a counted
// handle of its own, so any number of them can share the value, where a cell would
// have one owner (TSLANG_ISSUES 31).
if (isConst && !(varClass == VariableType::ConstRef) && MLIRTypeHelper::isSharedHandleType(type))
{
varDecl->setCaptureByValue();
}

// TODO: HACK: to mark var as local and ignore when capturing. Not a generator's alias
// of its `this` parameter (buildGeneratorWrapperDeclaration), which its `next`
// captures: it captures the parameter's storage
Expand Down Expand Up @@ -16468,6 +16476,11 @@ class MLIRGenImpl
return currentNamespace->captureVarsMap;
}

auto getCaptureUsesMap() -> llvm::StringMap<llvm::StringMap<mlir::LocationAttr>> &
{
return currentNamespace->captureUsesMap;
}

auto getLocalVarsInThisContextMap() -> llvm::StringMap<llvm::SmallVector<mlir::typescript::FieldInfo>> &
{
return currentNamespace->localVarsInThisContextMap;
Expand Down
1 change: 1 addition & 0 deletions tslang/lib/TypeScript/MLIRGenVariables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1185,6 +1185,7 @@ namespace mlirgen
// special case, to prevent capturing ".a" because of reference to outer VaribleOp, which is hack (review
// solution for it)
genContext.passResult->outerVariables.insert({value.second->getName(), value.second});
genContext.passResult->outerVariableUses.insert({value.second->getName(), mlir::LocationAttr(location)});
}

// end of logic: outer vars
Expand Down
5 changes: 3 additions & 2 deletions tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1455,10 +1455,11 @@ namespace own_inference
auto root = rootOf(value);
captured = ownerName(root);
Chain chain;
if (holdsNoBlock(value) || placeReadOf(root) || borrowedParam(root) >= 0 || isHandle(root))
if (holdsNoBlock(value) || placeReadOf(root) || borrowedParam(root) >= 0 ||
(isHandle(root) && !fill.second->hasAttr(OWN_CAPTURE_BORROW_ATTR_NAME)))
{
// nothing to own, a read the read's check bounds, a parameter, or a handle,
// whose copy in the box is counted (spec 23.2)
// whose copy in the box is counted (spec 23.2) - unless the box borrows it
}
else if (auto slotLoad = slotLoadOf(root))
{
Expand Down
Loading
Loading