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
75 changes: 75 additions & 0 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,78 @@ the call, `x instanceof A` of the borrowed union was refused ("borrows ... and c
was of a field read (`const x = this.f; x instanceof A`) before: the object seen as an opaque pointer,
whose vtable is read for its class's `.instanceOf`, is a test that keeps nothing, as for an owned value.
Regression test `tslang/test/tester/tests/00tslang_issue_46.ts`, JIT and compiled, under every model.

Items 47 and 48, found on 2026-11-13 porting powder_sandbox and native_ts_graphics to `-mm=own`, are
fixed. 47 (a lazily cached field could not be returned through a local: `let result = this.cached; if
(!result) { result = new Q(1); this.cached = result; } return result;` was refused three ways): two
changes. First, before the facts, a read of a local where it holds what a field holds is read as the
field. That is a `let` or a `const` declared from the field and not assigned since, or a local given a
value that was just moved into the field. So `return result` is `return this.cached`, a borrow of
`this`, and the local's first value, read by nothing now, is dropped. The check-then-return form
(`const hit = this.cached; if (hit) return hit; ... return result;`) and `r = n` after
`this.cached = n` work the same. Second, a store into a field that was tested empty on the way (`!f`,
`f == null`, `f === undefined`, or the else branch of `if (f)`, reading the field or such a local) frees
nothing. A method whose only overwrites are such fills drops nothing, so a second `d.getQ()` no longer
ends the borrow the first one returned, and `main` prints `1 1 true`. A loop between the test and the
store, a test of another field, or a call in between that may write the field leaves the store a drop.
A call in between is judged by facts that count every fill as a drop, since a method that only fills
may still fill this field. An exported method still says what it returns (`@lends("this")`), and
an importer calling it twice needs it `@final` (48). The diagnostics name the variable now: a folded
`const` by its debug name under `--di`, and "while another read of it still borrows it" where no local
does. Regression tests `tslang/test/tester/tests/00tslang_issue_47.ts` (every model),
`own/own_lazy_cache_main.ts` with `own_lazy_cache_lib.ts` (an exported class in a namespace, imported,
every model), and `own/own_err_fill_after_call.ts`, `own_err_fill_in_loop.ts`, `own_err_fill_other_field.ts`,
`own_err_fill_after_fill_call.ts`.

48 (in an exported class that isn't `@final`, any `this.method()` may overwrite any field): a method can
be `@final` now, as a class can. No subclass may override it ("method 'x' overrides the @final method of
'Base'"), and it cannot be abstract. A call of it runs that method: directly when its class is defined in
the module, through the vtable with the one callee known when it is imported. The `-shared` declaration
printer writes `@final`, so an importer knows it too. Under `-mm=own` the call goes by the method's own
facts: `this.factor()` reading a number drops nothing, and a borrow of `this.items[1]` held across it
compiles. The error for a borrow ended by such a call has a note: "'Base.factor' may be overridden in
another module by a method that does; '@final' on the method, or on its class, says it is not". Also
fixed: the store into a field whose type holds no block was still counted a drop when the body was
checked for drops (`!releasesNothing(...) && a || b` read as `(... && a) || b`). Regression tests
`tslang/test/tester/tests/00tslang_issue_48.ts` (every model), `own/own_final_method_main.ts` with
`own_final_method_lib.ts` (a `@final` method of an imported class), `own/own_err_overridable_call.ts`,
`tests/final_method_override_error.ts` and `final_method_abstract_error.ts`.

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
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`):

```ts
class Level { name: string = "a"; }
export class App {
level: 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]`.
8 changes: 7 additions & 1 deletion docs/own-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ about it, and `Shared<T>` gives opt-in shared ownership.
- [`@borrows`](#borrows) - the arguments a generator borrows
- [`@immortalizes`](#immortalizes) - the parameters a function keeps for good
- [`@nodrops`](#nodrops) - a C function that frees nothing
- [`@final`](#final) - a class nobody extends
- [`@final`](#final) - a class nobody extends, a method nobody overrides
- [`@value`](#value) - a type that is copied, not shared
- [Separate compilation](#separate-compilation)
- [Code for one memory model](#code-for-one-memory-model)
Expand Down Expand Up @@ -704,11 +704,17 @@ m8_virtual_err.ts:11:16: error: 'this value' borrows a field but is used here af
m8_virtual_err.ts:11:38: note: it may be released or overwritten here
return `${this.color} area=${this.area()}`;
^
m8_virtual_err.ts:11:38: note: 'S.area' may be overridden in another module by a method that does; '@final' on the method, or on its class, says it is not
```

With `@final export class S` it compiles and prints `red area=4`. Mark exported classes `@final`
unless another module has to extend them.

A class that other modules extend can mark single methods instead: `@final area()` may not be
overridden (a subclass that does is an error, and an abstract method can't be `@final`), so a call
of it runs that method, and `-mm=own` goes by what its body does. That holds for a class imported
from another module too: the declaration it is imported by says `@final`.

### `@value`

`@value class C` and `@value interface R`: a type whose values are copied, like numbers, not
Expand Down
27 changes: 27 additions & 0 deletions tslang/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,33 @@ add_subdirectory(tslang)
add_subdirectory(tsbindgen)
add_subdirectory(ts-new-parser)

# Whole-program optimization of the compiler itself (MSVC /GL + /LTCG, with /Ob3 inlining):
# slower links, a little smaller and faster tslang/tsbindgen. Only the compiler's own code: the LLVM
# it links (~90% of the executable) comes prebuilt, and /GL objects only link with the exact MSVC
# toolset that compiled them.
# Only the compiler's own targets: the runtime libraries (TypeScriptMimalloc, the async runtime,
# TypeScriptRuntime, gc) are linked into the programs tslang builds, by lld, which cannot read /GL
# objects.
option(TSLANG_ENABLE_LTCG "Build the compiler with link-time code generation (MSVC Release)" OFF)
if (TSLANG_ENABLE_LTCG AND MSVC)
set(TSLANG_LTCG_TARGETS
MLIRTypeScript
TypeScriptAliasPass
TypeScriptDebugInfoPass
TypeScriptExceptionPass
TypeScriptExportPass
TypeScriptMemAllocPass
TsClangImporter
ts-new-parser-lib
tslang
tsbindgen)
foreach(target ${TSLANG_LTCG_TARGETS})
set_property(TARGET ${target} PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
target_compile_options(${target} PRIVATE $<$<CONFIG:Release>:/Ob3>)
endforeach()
message(STATUS "LTCG for: ${TSLANG_LTCG_TARGETS}")
endif()

if (NOT DEFINED TYPESCRIPT_IGNORE_UNIT_TESTS)
# enable unit tests
set (MLIRTYPESCRIPT_LLVM_THIRD_PARTY_DIR "${CMAKE_SOURCE_DIR}/../3rdParty/llvm-project/third-party")
Expand Down
7 changes: 7 additions & 0 deletions tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,13 @@ class CastLogicHelper
if (!needTag)
{
auto llvmBoolType = tch.convertType(boolType);
// `(() => void) | null` is the function's own value, and a function is true when
// it has code to run (GetMethodOp below): that op takes a function, not the union
if (isa<mlir_ts::HybridFunctionType, mlir_ts::BoundFunctionType>(baseType) && isa<mlir_ts::UnionType>(in.getType()))
{
in = rewriter.create<mlir_ts::GetValueFromUnionOp>(loc, baseType, in);
}

auto valAsBool = cast(in, baseType, tch.convertType(baseType), boolType, llvmBoolType);
return valAsBool;
}
Expand Down
14 changes: 14 additions & 0 deletions tslang/include/TypeScript/LowerToLLVM/UnaryBinLogicalOrHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,20 @@ mlir::Value LogicOp(Operation *binOp, SyntaxKind op, mlir::Value left, mlir::Typ
auto value = builder.create<StdIOpTy>(loc, v1, leftPtrValue, rightPtrValue);
return value;
}
// a function value compared with null (`f !== null` of a `(() => void) | null`, which is the
// function's own value): it is null when it has no code to run. Without it the comparison fell
// to the "not applicable" warning at the bottom and was constant false
else if (isa<mlir_ts::HybridFunctionType, mlir_ts::BoundFunctionType>(leftType)
&& (right.getDefiningOp<mlir_ts::NullOp>() || right.getDefiningOp<LLVM::ZeroOp>() || matchPattern(right, m_Zero())))
{
auto llvmFuncType = typeConverter.convertType(leftType);
mlir::Value llvmFunc = left.getType() == llvmFuncType
? left
: builder.create<mlir_ts::DialectCastOp>(loc, llvmFuncType, left).getResult();
auto codePointer = builder.create<LLVM::ExtractValueOp>(loc, llvmFunc, ArrayRef<int64_t>{DATA_VALUE_INDEX});
auto zero = builder.create<LLVM::ZeroOp>(loc, codePointer.getType());
return builder.create<StdIOpTy>(loc, v1, codePointer, zero);
}
else if (auto unionType = dyn_cast<mlir_ts::UnionType>(leftType))
{
::typescript::MLIRTypeHelper mth(builder.getContext(), compileOptions);
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 @@ -174,6 +174,8 @@ struct MethodInfo
int cppSlot = -1;
// @destructor: the C++ virtual destructor of a @cpp class, which can't be called
bool isCppDestructor = false;
// @final: no subclass may override it, so a call of it runs this very method (TSLANG 48)
bool isFinal = 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
Expand Down
1 change: 1 addition & 0 deletions tslang/lib/TypeScript/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ add_mlir_dialect_library(MLIRTypeScript
OwnershipSignaturePass.cpp
OwnershipSignatureCallbacks.cpp
OwnershipSignatureClosedWorld.cpp
OwnershipSignatureFieldLocals.cpp
OwnershipSignatureGenerators.cpp
OwnershipSignatureGlobals.cpp
OwnershipSignatureInterfaces.cpp
Expand Down
8 changes: 8 additions & 0 deletions tslang/lib/TypeScript/DeclarationPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,14 @@ namespace typescript
}
}

// no override: the importer's calls of it run it (TSLANG 48)
if (method.isFinal && !method.isStatic)
{
os.indent(4);
os << "@" FINAL_DECORATOR;
newline();
}

os.indent(4);

if (method.accessLevel == mlir_ts::AccessLevel::Protected)
Expand Down
9 changes: 9 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2715,6 +2715,15 @@ namespace mlirgen
// it does not match, instead of naming the whole union
if (auto unionType = dyn_cast<mlir_ts::UnionType>(type))
{
// `(() => number) | null` has no tag: it is the function's own value, null an empty
// one, as `C | null` is the class's pointer. A function of that type is stored as it is
// (castToNullableUnionType has made one of any other)
mlir::Type baseType;
if (!mth.isUnionTypeNeedsTag(location, unionType, baseType) && baseType == valueType)
{
return mlir::success();
}

for (auto memberType : unionType.getTypes())
{
if (!mth.isAnyFunctionType(memberType))
Expand Down
14 changes: 13 additions & 1 deletion tslang/lib/TypeScript/MLIRGenExpressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1274,8 +1274,20 @@ namespace mlirgen

LLVM_DEBUG(llvm::dbgs() << "\n!! evaluate function: " << funcResult << "\n";);

// `(() => void) | null` has no tag: it is the function's own value (isUnionTypeNeedsTag), as
// `C | null` is the class's pointer, and is called as that function - a field `this.f` read
// again after `if (this.f)` is the union still
if (auto funcUnionType = dyn_cast<mlir_ts::UnionType>(funcResult.getType()))
{
mlir::Type baseType;
if (!mth.isUnionTypeNeedsTag(location, funcUnionType, baseType) && baseType && mth.isAnyFunctionType(baseType))
{
funcResult = builder.create<mlir_ts::GetValueFromUnionOp>(location, baseType, funcResult);
}
}

auto funcType = funcResult.getType();
if (!mth.isAnyFunctionType(funcType)
if (!mth.isAnyFunctionType(funcType)
&& !mth.isBuiltinFunctionType(funcResult)
// TODO: do I need to use ConstructFunction instead?
// to support constructor calls
Expand Down
Loading
Loading