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
19 changes: 19 additions & 0 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,22 @@ Regression tests `tslang/test/tester/tests/00tslang_issue_37.ts`, `00tslang_issu

Still open from 38: a symbol made at run time can't be a property key (`obj[sym]`). Fields are laid out at
compile time, so a symbol needs a run-time value and a way to look a key up. It has not been tried.

Items 39-42, `-mm=own` limits found in the default library on 2026-11-09 (TypeScriptCompilerDefaultLib
PRs #80-#85), are fixed. 39 (a chain from a new value, `JsonValue.newObject().set(...).set(...)`, could
not be returned or kept): a method whose result type is `this` returns the object it is called on, and
called on a temporary the caller owns, its result is that object, the caller's to keep. `: this` says
it, with no decorator, and implies `@lends("this")`; under `-mm=own` a body that returns another object
of the type is an error. A method typed with its class that returns `this` on every path works the same
within its module; for another module, `: this` is how a declaration says it (the `-shared` declaration
printer writes it). The default library's `set` and `push` return `this` now, and `tests/json.ts` runs
its chains under every model. 40 (an arrow that captures something could not store a closure over its
object parameter into a field of that object): it is a back-reference as it is from an arrow that
captures nothing. 41 (a closure kept in a field could not capture a parameter, and `@keeps` could not
say it did): a closure that is kept owns the parameters it captures, so the function keeps them and its
callers give them up; `@keeps("body")` is accepted. The error for a capture that still cannot move names
the variable. 42 (`[data, this.data] = [this.data, data]` did not move a class instance out of a
`T | undefined` field): an exchange of a local and a field or an element hands each value over under
every model, and `<T>data` of such a local is a view of it. Regression tests
`tslang/test/tester/own/own_chain_returns_this.ts`, `own_closure_keeps_param.ts`,
`own_swap_local_field.ts`, `own_err_this_result_other.ts` and `own_err_closure_kept_param_used.ts`.
64 changes: 62 additions & 2 deletions docs/own-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,30 @@ function main() {
6 2
```

A closure kept - stored into a field, a global or an array, or given to a function that keeps it -
owns the parameters it captures, so the function keeps them and its callers give them up, as for a
parameter stored into a field. A closure stored into a field of the object it captures is a
back-reference instead: it borrows that object.

```typescript
class Holder {
run: () => number;

constructor(body: (n: number) => number) {
this.run = () => body(2); // the closure is kept, and owns body
}
}

function main() {
const h = new Holder((n: number) => n * 21);
print(h.run());
}
```

```text
42
```

A closure kept for good, in an array that is only ever pushed onto, is covered by
[`@immortalizes`](#immortalizes).

Expand Down Expand Up @@ -441,6 +465,40 @@ function main() {
`@lends` with one name is a plain borrow. With several, the result is a record that borrows each
of them, and it needs [`@record`](#record).

### A method that returns `this`

A method whose result type is `this` returns the object it is called on, so calls chain. It lends
`this` without saying `@lends("this")`, and the compiler checks that the body returns `this` on every
path (one that returns another object of the type is an error under own). Called on an object the
caller owns no more after the call - a new one - the result is that object, the caller's to keep:
a chain from a new value can be returned, stored or given to a function that keeps it. A method of
a class only this module uses may say the class instead of `this`; its body shows the same.

```typescript
export class Bag {
items: number[] = [];

add(n: number): this {
this.items.push(n);
return this;
}
}

function filled(): Bag {
return new Bag().add(1).add(2); // the new Bag, given back
}

function main() {
const b = filled();
b.add(3); // on b: a borrow of it, used in place
print(b.items.length);
}
```

```text
3
```

### `@record`

`@record`, always beside `@lends`: the result is a *borrowing record* - a new object the caller
Expand Down Expand Up @@ -744,8 +802,10 @@ a reference gives it back on every path out of a function.
or build the result from copies.
- `reverse` and `sort` work on arrays of numbers, strings and class instances. They exchange
elements with `[a[i], a[j]] = [a[j], a[i]]`, which moves nothing; swap two elements or two fields
the same way in your own code. A swap through a local (`let t = a[i]; a[i] = a[j]; a[j] = t`)
gives an object in `t` a second owner, which is an error. A callback your function only calls,
the same way in your own code. To take a value out of a place, exchange it with a local:
`let v: T | undefined = undefined; [v, this.f] = [this.f, v]` leaves the place holding what the
local held and the local owning what the place held. A swap through a local (`let t = a[i];
a[i] = a[j]; a[j] = t`) gives an object in `t` a second owner, which is an error. A callback your function only calls,
tests (`compare && compare(a, b)`), hands on to another function (as `sort` hands its comparison
to a helper), names again (`const g = f`) or captures in a closure that calls it (`a.forEach((v)
=> f(v))`, also kept in a local) is known by the functions its callers pass. So is one stored in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5641,3 +5641,71 @@ 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.

## 75. A back-reference from an arrow that captures, 2026-11-09

An arrow given an object stores a closure over that object into one of its fields (spec 70's
back-reference: the field owns the closure, the box borrows the object). The rule asked for the
member's `this`, the function's first parameter of a class type. A closure body takes its box first
(a reference to the tuple of what it captures), so once the outer arrow captured anything its object
parameter was second and the inner closure was taken for one that owns a parameter it cannot
(TSLANG_ISSUES 40). `isMemberThis` now skips a first argument that is a reference to a tuple: the
outer arrow's own captures do not change whose its parameter is.

## 76. A closure kept owns the parameters it captures, 2026-11-09

An escaping closure owns what it captures; a parameter's value is the caller's, so a closure that
captured one was refused (spec 16) unless it was a back-reference. When the closure itself is kept
- stored into a field, a global or an array, or given to a call that keeps it (`keeps`, through views) -
and is no back-reference, the function keeps each parameter its box holds, captured by copy or in a
cell (`keepsClosure`, `localOwnedParams`): its callers move the argument in, as they do for one stored
into a field, and `@keeps` may say so (TSLANG_ISSUES 41). The cell then moves into the box as a kept
parameter's does (decideEscaping). Not the member's `this`, which the object the closure goes into
would own. A closure returned still cannot capture a parameter: its result would be a fact (a result
that owns a parameter) callers have no way to be told.

The error for a capture that still cannot move names it, from the box's field (`'this'`, `'c'`).

## 77. A local exchanged with a place, 2026-11-09

`[data, this.data] = [this.data, data]` was built through an array literal: the field's value, read
out of it, was a borrow stored into the array (TSLANG_ISSUES 42). MLIRGen now writes an exchange of a
local that owns what it holds and a field or an element of the same type as two reads, both counted,
then the place given the local's value and the local given the place's, each store releasing what
its storage held (`mlirGenSwapWithLocal`), under every model. The place goes first: rc's counts stay
whole, and own sees the place's release, right before the store that refills it, as the hand-over of
the value read to the local: `refilledFieldTakeOf` takes a read whose one taker comes after the
refill, with nothing but reads, counts and stores of locals between (no call, no release of the
object's local), erases rc's retain and the refill's release, and the read is the local's. A string
is copied instead (spec 22). The local's old value moves into the place as any `let` moves into a
field, and the local's assignment after it is a kill (spec 24).

`<T>data` of a `T | undefined` with T a class was `HasValue ? Value : null`, a merge own could not
follow. It is now one `ts.ValueOrDefault` (marked as an explicit cast, so it does not warn), which is a
view: the optional's object or none.

## 78. A method that returns its receiver, 2026-11-09

A method that returns `this` so calls chain (`set(k, v).set(k2, v2)`) has a result that borrows its
receiver. Called on a temporary (`JsonValue.newObject().set(...)`), that borrow had no owner but the
temporary, released at the end of the statement, so the chain could not be returned or kept
(TSLANG_ISSUES 39). `@lends("this")` cannot mean more: `at()` and `get()` lend an element.

**The fact.** `__own_result_itself`, beside `__own_result_borrows` naming one argument: the result is
that argument itself on every path - each returned value is the parameter or a read of its unassigned
slot, through views, never `null` (`isParameterItself`). The signature pass infers it from a body, so
a method typed with its class that returns `this` has it; families must agree on it as on the rest.

**Saying it.** A method whose result type is `this` says it: MLIRGen marks it
(`ts.own_declared_returns_this`) and implies `@lends("this")` (`ts.own_implied_lends`). A function only
this module calls drops the implied `@lends` (its callers go by its body; a declared one would want
every other fact declared too). A body is held to it: one that returns another object of the type
(`clone(): this { return <this>new A() }`, valid TypeScript) is an error under own. A declaration
(`lib.d.ts`) has no body, so its `: this` is what callers know, and the `-shared` declaration printer
writes `: this` for such a method. There is no decorator: `: this` is the one way.

**The call.** After the facts settle (`transferTemporaryReceivers`, in program order so a chain's next
call sees the one before it): a call with the fact whose argument is fresh, that the callee does not
keep, and that nothing uses after the call but its releases in the same block, loses those releases,
and its result is `__own_fresh_result` - the temporary, now the result's to release. On an object
someone owns the result stays a borrow, bounded by it.
13 changes: 13 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
// retain nobody performed and free live memory.
#define OWNED_RESULT_ATTR_NAME "__owned_result"

// On a `ts.ValueOrDefault`: an explicit cast in the source (`<T>data` of a `T | undefined`) made
// it, so its lowering does not warn that an optional value is read as it is.
#define EXPLICIT_CAST_ATTR_NAME "__explicit_cast"

// -mm=own only, set by OwnershipInferencePass for the lowering. On a `ts.Release` of an array: the
// array borrowed its elements (the array a rest parameter is given), so its release frees the
// array and not them.
Expand Down Expand Up @@ -376,6 +380,15 @@
// that returns such a record has to say it. A unit attribute on the FuncOp.
#define RECORD_DECORATOR "record"
#define OWN_DECLARED_RECORD_ATTR_NAME "ts.own_declared_record"
// A method whose result type is `this`: it returns the object it is called on, on every path, not
// another of its type nor a borrow of something in it. Called on a value the caller owns no more
// after the call - a temporary - the result is that value, the caller's to own (own spec 78). A unit
// attribute on the FuncOp, set by MLIRGen beside OWN_DECLARED_LENDS_ATTR_NAME naming `this`.
#define OWN_DECLARED_RETURNS_THIS_ATTR_NAME "ts.own_declared_returns_this"
// Beside OWN_DECLARED_LENDS_ATTR_NAME: no `@lends` said it, the result type `this` did. For a function
// no other module calls, -mm=own goes by its body and drops it (a declared `@lends` would want every
// other fact declared too).
#define OWN_IMPLIED_LENDS_ATTR_NAME "ts.own_implied_lends"
// `@copies`: inside this function -mm=own may copy an array whose elements own nothing where it cannot
// prove one owner (own spec 71), as it copies a string anywhere. A copy of an array can be told from
// the array - a change to one is not a change to the other - so only a function that says so makes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ namespace typescript
void printOwnMarkers(ArrayRef<int32_t>, ArrayRef<int32_t>, ArrayRef<int32_t>, bool, bool, unsigned,
ArrayRef<int32_t> = {});
void printFunction(StringRef, ArrayRef<mlir::Type>, mlir::Type);
void printMethod(bool, StringRef, ArrayRef<mlir::Type>, mlir::Type, mlir::Type);
void printMethod(bool, StringRef, ArrayRef<mlir::Type>, mlir::Type, mlir::Type, bool = false);
void printAccessor(bool, StringRef, StringRef, mlir_ts::AccessLevel, ArrayRef<mlir::Type>, mlir::Type, mlir::Type, StringRef);
void printIndexer(mlir::Type, mlir::Type);
void printNamespaceBegin(NamespaceInfo::TypePtr);
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 @@ -177,6 +177,8 @@ struct MethodInfo
uint64_t ownLendsMask = 0;
// `@record` (OWN_DECLARED_RECORD_ATTR_NAME): what `@lends` names, the result is a record of
bool ownRecord = false;
// the result is `this`, the object itself (OWN_DECLARED_RETURNS_THIS_ATTR_NAME, own spec 78)
bool ownReturnsThis = false;
// `@immortalizes` (OWN_DECLARED_IMMORTALIZES_ATTR_NAME), as a mask like `@lends`'s, of 32 bits
uint32_t ownImmortalizesMask = 0;
};
Expand Down
12 changes: 9 additions & 3 deletions tslang/lib/TypeScript/DeclarationPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,8 @@ namespace typescript
}
}

void MLIRDeclarationPrinter::printMethod(bool isStatic, StringRef name, ArrayRef<mlir::Type> params, mlir::Type returnType, mlir::Type thisType)
void MLIRDeclarationPrinter::printMethod(bool isStatic, StringRef name, ArrayRef<mlir::Type> params, mlir::Type returnType, mlir::Type thisType,
bool returnsThis)
{
if (isStatic)
{
Expand All @@ -297,7 +298,12 @@ namespace typescript

printParams(params, thisType);

if (returnType)
// `: this` - the object the method is called on (own spec 78), which the class would not say
if (returnType && returnsThis && !isStatic)
{
os << " : this";
}
else if (returnType)
{
os << " : ";
print(returnType);
Expand Down Expand Up @@ -798,7 +804,7 @@ namespace typescript
StringRef(method.name).split(CPP_OVERLOAD_SEPARATOR).first,
funcType.getParams(),
funcType.getNumResults() > 0 ? funcType.getResult(0) : mlir::Type(),
thisTypeOf(method.isStatic, funcType.getParams()));
thisTypeOf(method.isStatic, funcType.getParams()), method.ownReturnsThis);

newline();
}
Expand Down
9 changes: 7 additions & 2 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2403,7 +2403,9 @@ struct FuncOpLowering : public TsLlvmPattern<mlir_ts::FuncOp>
// read by -mm=own only
if (name == OWN_DECLARED_NO_DROPS_ATTR_NAME || name == OWN_DECLARED_KEEPS_ATTR_NAME ||
name == OWN_DECLARED_BORROWS_ATTR_NAME || name == OWN_DECLARED_LENDS_ATTR_NAME ||
name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME ||
name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_RETURNS_THIS_ATTR_NAME ||
name == OWN_IMPLIED_LENDS_ATTR_NAME ||
name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME ||
name == OWN_DECLARED_IMMORTALIZES_ATTR_NAME || name == OWN_DECLARED_COPIES_ATTR_NAME ||
name == OWN_CANNOT_SHARE_ATTR_NAME) {
continue;
Expand Down Expand Up @@ -6252,7 +6254,10 @@ struct ValueOrDefaultOpLowering : public TsLlvmPattern<mlir_ts::ValueOrDefaultOp
{
auto loc = valueOrDefaultOp->getLoc();

valueOrDefaultOp->emitWarning("casting from optional (undefined) value");
if (!valueOrDefaultOp->hasAttr(EXPLICIT_CAST_ATTR_NAME))
{
valueOrDefaultOp->emitWarning("casting from optional (undefined) value");
}

TypeHelper th(rewriter);
TypeConverterHelper tch(getTypeConverter());
Expand Down
10 changes: 10 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2184,6 +2184,16 @@ namespace mlirgen
return unwrappedValue;
}

// a class object or null: the value, or null when there is none (`<T>data` of a `T |
// undefined`). One select, not a branch: under -mm=own the result is a view of the optional,
// the same block or none (spec 77), where a merge of two branches would hide whose it is
if (type == optType.getElementType() && isa<mlir_ts::ClassType>(type))
{
auto valueOrDefault = builder.create<mlir_ts::ValueOrDefaultOp>(location, type, value);
valueOrDefault->setAttr(EXPLICIT_CAST_ATTR_NAME, builder.getUnitAttr());
return V(valueOrDefault);
}

// optional to value cast(when we change types)
auto hasValue = builder.create<mlir_ts::HasValueOp>(location, mlir_ts::BooleanType::get(builder.getContext()), value);

Expand Down
4 changes: 2 additions & 2 deletions tslang/lib/TypeScript/MLIRGenFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1450,8 +1450,8 @@ namespace mlirgen
if (auto globalOp = theModule.lookupSymbol<mlir_ts::GlobalOp>(globalName))
{
for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME,
OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME,
OWN_DECLARED_PARAM_NAMES_ATTR_NAME})
OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_RETURNS_THIS_ATTR_NAME, OWN_IMPLIED_LENDS_ATTR_NAME,
OWN_DECLARED_IMMORTALIZES_ATTR_NAME, OWN_DECLARED_PARAM_NAMES_ATTR_NAME})
{
if (auto attr = declared->getAttr(name))
{
Expand Down
Loading
Loading