From c2ded8afc12828197d6963df2b80a184d5d9bf3d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 08:40:30 +0000 Subject: [PATCH 1/3] WIP 212: generic class for a constructor type (132), own instanceof narrowing borrows + generic instanceof (164), own record strings into dictionaries (152), own forward-captured consts (144), array of a union as members (191), class to a constructor interface (139), object literal function callee named Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 60 +++++++ tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 13 +- tslang/lib/TypeScript/MLIRGenCast.cpp | 72 ++++++++- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 6 +- tslang/lib/TypeScript/MLIRGenGenerics.cpp | 49 +++++- tslang/lib/TypeScript/MLIRGenImpl.h | 91 ++++++++++- tslang/lib/TypeScript/MLIRGenVariables.cpp | 30 ++++ .../TypeScript/OwnedReturnConsumptionPass.cpp | 8 + tslang/lib/TypeScript/OwnershipFacts.h | 19 +++ tslang/test/tester/CMakeLists.txt | 20 ++- .../test/tester/tests/00tslang_issue_212.ts | 149 ++++++++++++++++++ .../00tslang_issue_212_ctor_interface.ts | 36 +++++ .../tests/00tslang_issue_212_dictionary.ts | 111 +++++++++++++ .../tests/00union_interfaces_instanceof.ts | 4 +- .../tests/class_itself_interface_error.ts | 4 +- 15 files changed, 656 insertions(+), 16 deletions(-) create mode 100644 tslang/test/tester/tests/00tslang_issue_212.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_212_ctor_interface.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_212_dictionary.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index dca9ca990..233884da8 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3847,3 +3847,63 @@ Not yet: constructor (140). Tests `00tslang_issue_211.ts` (all models), `own_grow_past_end_check.ts` (-mm=own). + +212. Leftovers of 211's triage (2026-11-27). Fixed: +- 132: a generic class given for a constructor type (`fruitFactory1(Banana)` of `new (...args: any[]) => TFruit`, + `class Banana`): "Can't find class Banana". Its type arguments come from the constructor type's + parameters, as `new Banana(...)`'s come from its arguments (171), and a rest among them gives its element type to each + constructor parameter the others do not reach, the constructor's own rest included: `any` makes T `any` (TypeScript's + `Banana`), `...args: "foo"[]` makes it a string. The tsc test contextualSignatureInstantiation4 compiles. +- 164: under -mm=own an interface narrowed to a class by `instanceof` (`if (v instanceof A) return v.a` of `v: IA` or + `IA | IB`): "'v' is a parameter, kept here". The narrowed value is the object the interface holds, a borrow as the + interface is; the cast also had a way for what is not an A (a new A of the interface's fields), never taken there, + which made the result a reference of its own. Not for a generic class, which `instanceof` answers for every G. + 00union_interfaces_instanceof.ts runs under -mm=own too. +- `v instanceof G` of a generic class narrowed to the generic itself, no type a value has: an interface `v` crashed the + compiler, a union "Can't resolve property". It narrows a union to its members that are a G (or derive from one), + else not at all. +- 152: under -mm=own a record's strings spread into a dictionary (`const d: { [k: string]: string } = { ...rec }`) or + given to `Object.assign(d, rec)`: "a value that borrows a field cannot be stored". Each string read out of the record + is copied (strings are values). A literal given to Object.assign goes into a local of its own (ownedLiteralArgument), + which gives back what it holds: left in a slot nothing owned, it leaked once its strings were copied. +- 144: under -mm=own a `const` a function before it reads, holding a closure or an object (`const f = () => g(); const g + = () => 10;`): "'g' is captured by a closure, but -mm=own cannot tell who owns its value here". Made one of the + function's variables (declared with no value, TSLANG 172/174), it is marked an owned local before anything captures + it, and its declaration gives it the value it owns. One whose value is a borrow (`const q = p`, `const g = this.c`) + stays refused, as before ("kept here", "borrows 'this.c'"). +- 191: an array of a union said to be an array of members of it (`x.slice(1) as readonly string[]` of `[number, + string] | [number, string, string]`, tsc sliceResultCast): "cast from array type ... is not supported" with no + location, at lowering. It is a new array, each element read as the member it is said to be (castArrayElementwise). +- 139: a class given to an interface of a construct signature only (`interface PtCtor { new (x: number): Pt }`, + `make(P)`; `const c: Constructor = A`): "the class 'P' itself can't be given as interface" (TSLANG 204's clear + error for an internal one). It is made over an object of one field, `new`, a function calling the class's + constructor and returning its object as the signature's result. An interface with other members as well is still + refused (class_itself_interface_error.ts). Not under -mm=own, which refuses a construct signature's result, through a + type literal (`{ new (x: number): Pt }`) as well: "a value takes a second reference". +- A leak under -mm=rc of the result of every call through a function value (a callback, an object literal's method, + an interface method an object literal's function field backs), in every program linking the default library since + DefaultLib #108: its `Temporal.Now` functions lacked `@owned`, the only heap results there the compiler could not + classify, and one is enough to turn off the rule that such a call hands its result over (DefaultLib #122). A call of + a function an object literal holds (`o.make(i)`, the literal a constant of the functions' names) names its callee + now, so its result is classified whatever else the program links, under -mm=own too (it leaked there). + +Not yet: +- Under -mm=own an interface method an object literal's function field backs (`const m: Mk = { make: (x) => new + P(x) }; m.make(i)`) leaks its result: the thunk calling the field cannot know whose result it is, and -mm=own never + takes a call through a value for one handing its result over. +- Under -mm=rc `new c(i)` of a type literal's construct signature (`c: { new (x: number): Pt }`) given a class crashes + at run time (before this batch too). +- Under -mm=own a tuple literal holding a new string given to a union of tuples (`const x: [number, string] | [number, + string, string] = [i, "a" + i, "b"]`): "a value that borrows a field cannot be stored"; `x.slice(1)` of such a + parameter: "an element ... would have two owners". +- Under -mm=own `make(L)` of `class L { constructor(...items: T[]) }` for `new (...args: number[]) => X`: "'items' + is a parameter, kept here" (gc runs it); and a `let` captured by a closure and assigned after (`let g = () => 10; + const f = () => g(); g = () => 11;`): "takes a second reference". +- The `any` dictionary of a spread record (`const d: { [k: string]: any } = { ...rec }`) leaks under -mm=own (before + this batch too). +- Still from the triage: 117, 131 (Object.keys of `object`, Object.defineProperty, Object.create), 128, 56, 140 `await` + in `finally`, 108, 191's callable interfaces naming each other, recursive conditional types, `Symbol` as a value, own + 153 and 159; design questions without a ruling: overloads of a declared function (136) and class constructor (140). + +Tests `00tslang_issue_212.ts`, `00tslang_issue_212_dictionary.ts` (all models), `00tslang_issue_212_ctor_interface.ts` +(gc, rc, none); `00union_interfaces_instanceof.ts` under -mm=own; `class_itself_interface_error.ts` changed. diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index f9e6855de..c62cd7d65 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -4396,8 +4396,19 @@ namespace mlirgen return mlir::failure(); } + // under -mm=own a string read out of the record is copied (strings are values): the dictionary keeps what it is + // given, and the record still holds its own - stored, the read was "a value that borrows a field" (TSLANG 152) + auto fieldValue = V(fieldResult); + if (compileOptions.memoryModel == MemoryModelOwn && isa(fieldValue.getType()) + && isa_and_nonnull(fieldValue.getDefiningOp())) + { + auto copy = builder.create(spreadLocation, fieldValue.getType(), fieldValue); + copy->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + fieldValue = copy; + } + auto fieldKey = builder.create(spreadLocation, getStringType(), name); - if (mlir::failed(mlirGenDictionarySet(spreadLocation, dictionary, fieldKey, V(fieldResult), genContext))) + if (mlir::failed(mlirGenDictionarySet(spreadLocation, dictionary, fieldKey, fieldValue, genContext))) { return mlir::failure(); } diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 2f68a044e..5481af979 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -574,6 +574,17 @@ namespace mlirgen return (name && name.getValue().starts_with(".")) || interfaceInfo->findField(field.id); }); + // narrowed by `v instanceof C` (TSLANG 164): it is a C, the test said so. The object it holds is all the cast is - + // a borrow of v, as v is. With the way for what is not a C, never taken there, the result was a new C in one + // branch, so -mm=own took the other for a reference of its own: a parameter `v` was kept ("cannot make the + // callers give it up"). Not a generic class's: `v instanceof G` is true of any G, which this one may not be + auto narrowedClassInfo = getClassInfoByFullName(classType.getName().getValue()); + if (castCheckedByInstanceOf && narrowedClassInfo && !narrowedClassInfo->originClassType) + { + auto thisPtr = builder.create(location, getOpaqueType(), value); + return ValueOrLogicalResult(builder.create(location, classType, thisPtr)); + } + auto classRefVal = builder.create( location, classType, mlir::FlatSymbolRefAttr::get(builder.getContext(), classType.getName().getValue())); auto isInstance = mlirGenInstanceOfInterface(location, value, classRefVal, genContext); @@ -1927,6 +1938,39 @@ namespace mlirgen // 'ts.ClassRef'"). Its type is `typeof A`, or a constructor type (`new (...args: any[]) => A`). if (value.getDefiningOp()) { + // ...but an interface of a construct signature only (`interface PtCtor { new (x: number): Pt }`, + // TSLANG 139) is made over an object of one field, `new`: the class's constructor called as `new + // P(...)` calls it (generatingStaticNewCtorForClass), as a type literal's construct signature is given + // the class (castClassToTuple). Its P is made the interface's Pt as the object is cast to it + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + auto onlyConstructSignature = interfaceInfo->hasNew && interfaceInfo->fields.empty() + && interfaceInfo->accessors.empty() && interfaceInfo->indexes.empty() && interfaceInfo->extends.empty() + && interfaceInfo->methods.size() == 1 && interfaceInfo->methods.front().name == NEW_CTOR_METHOD_NAME; + auto constructorMethod = classInfo ? classInfo->findMethod(CONSTRUCTOR_NAME) : nullptr; + auto memberResultType = onlyConstructSignature + ? mth.getReturnTypeFromFuncRef(interfaceInfo->methods.front().funcType) : mlir::Type(); + if (onlyConstructSignature && classInfo && !classInfo->isAbstract && constructorMethod && memberResultType) + { + // (the object it makes is returned as the signature's result, `Pt`: one returning a P was "can't + // assign '(p0: number) => P' to '(p0: number) => Pt'") + auto wrapperType = getFunctionType(constructorMethod->funcType.getInputs().slice(1) /*no this*/, + {memberResultType}, constructorMethod->funcType.isVarArg()); + auto wrapperName = generateSynthMethodToCallNewCtor(location, classInfo, interfaceInfo->fullName, 0, + wrapperType, 0, genContext); + if (wrapperName.empty()) + { + return mlir::failure(); + } + + mlir::Value newCtorValue = builder.create( + location, wrapperType, mlir::FlatSymbolRefAttr::get(builder.getContext(), wrapperName)); + SmallVector ctorFields{{MLIRHelper::TupleFieldName(NEW_CTOR_METHOD_NAME, builder.getContext()), + newCtorValue.getType(), false, mlir_ts::AccessLevel::Public}}; + auto ctorObject = builder.create(location, getTupleType(ctorFields), + mlir::ValueRange{newCtorValue}); + return cast(location, interfaceType, ctorObject, genContext); + } + // (said in a discovery pass too: the statement fails there, and is not made again) emitError(location) << "the class '" << to_print(valueType) << "' itself can't be given as interface '" << to_print(interfaceType) << "': give it an instance, or declare it as `typeof " @@ -2726,8 +2770,34 @@ namespace mlirgen && !isa(srcElementType); }; + // ...and an array of a union said to be an array of members of it (`x.slice(1) as readonly string[]` of + // `[number, string] | [number, string, string]`, TSLANG 191): each element is read as the member it is said to be. + // The array itself cannot be: its elements are unions, laid out as such ("cast from array type ... is not + // supported" when it was lowered) + auto narrowsElements = [&]() { + auto srcUnionType = dyn_cast(srcElementType); + if (!srcUnionType) + { + return false; + } + + SmallVector members; + if (auto unionType = dyn_cast(elementType)) + { + members.append(unionType.getTypes().begin(), unionType.getTypes().end()); + } + else + { + members.push_back(elementType); + } + + return llvm::all_of(members, [&](mlir::Type member) { + return llvm::is_contained(srcUnionType.getTypes(), member); + }); + }; + if (srcElementType == elementType - || !((isNumericSource(srcElementType) && isNumericTarget(elementType)) || boxesElements())) + || !((isNumericSource(srcElementType) && isNumericTarget(elementType)) || boxesElements() || narrowsElements())) { return std::nullopt; } diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 5be8e82f1..c69a26482 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1947,7 +1947,11 @@ namespace mlirgen auto sourceResult = mlirGen(source, genContext); EXIT_IF_FAILED_OR_NO_VALUE(sourceResult) - if (mlir::failed(mlirGenSpreadIntoDictionary(loc(source), target, V(sourceResult), genContext))) + // -mm=own: a literal given (`Object.assign(d, { a: "z" + i })`) goes into a local of its own, which gives + // back what it holds once its strings are copied into the dictionary: left in a slot nothing owns, they + // were never given back + auto sourceValue = ownedLiteralArgument(loc(source), source, V(sourceResult), genContext); + if (mlir::failed(mlirGenSpreadIntoDictionary(loc(source), target, sourceValue, genContext))) { return mlir::failure(); } diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index 792710d3c..91a3da15c 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -589,9 +589,22 @@ namespace mlirgen { if (auto genericClassInfo = getGenericClassInfoByFullName(classType.getName().getValue())) { + // `new (a: string, ...args: any[]) => T`: the rest's element type, given for each parameter + // after `a` + auto inputs = tempConstructType.getInputs(); + mlir::Type restArgumentType; + if (tempConstructType.isVarArg() && !inputs.empty()) + { + if (auto restArrayType = dyn_cast(inputs.back())) + { + restArgumentType = restArrayType.getElementType(); + inputs = inputs.drop_back(); + } + } + NodeArray noArguments; if (auto specClassType = inferClassTypeFromConstructorArguments( - location, genericClassInfo, noArguments, genContext, tempConstructType.getInputs())) + location, genericClassInfo, noArguments, genContext, inputs, restArgumentType)) { instanceType = specClassType; } @@ -2126,10 +2139,12 @@ namespace mlirgen GenericClassInfo::TypePtr genericClassInfo, NodeArray arguments, const GenContext &genContext, - ArrayRef knownArgumentTypes) + ArrayRef knownArgumentTypes, + mlir::Type restArgumentType) { // the arguments' count: of the call, or of the types given for them (a constructor type's parameters, - // `make(Box, 4)` of `make(c: new (n: number) => T, n)`) + // `make(Box, 4)` of `make(c: new (n: number) => T, n)`); with a rest among those (`new (a: string, + // ...args: any[]) => T`), its element type is given for each parameter after the others, so this many at least auto argumentCount = arguments.empty() ? knownArgumentTypes.size() : arguments.size(); SmallVector constructorDeclarations; for (auto member : genericClassInfo->classDeclaration->members) @@ -2147,7 +2162,7 @@ namespace mlirgen return mlir_ts::ClassType(); } - if (argumentCount == 0 + if (argumentCount == 0 && !restArgumentType && (!constructorDeclarations.empty() || !genericClassInfo->classDeclaration->heritageClauses.empty())) { return mlir_ts::ClassType(); @@ -2246,13 +2261,35 @@ namespace mlirgen } } - if (!hasSpread && (argumentCount < required || (!hasRest && argumentCount > parameters.size()))) + // a constructor type's rest (`new (...args: any[]) => T` given `Banana` of `(a: string, property: T)`): + // its element type is the argument for each parameter the others do not reach - `any` makes T `any`, as + // TypeScript infers it (`Banana`), `...args: "foo"[]` makes it a string (TSLANG 132) + SmallVector constructorArgumentTypes(argumentTypes.begin(), argumentTypes.end()); + auto constructorArgumentCount = argumentCount; + if (restArgumentType) + { + auto fixedParameters = hasRest ? parameters.size() - 1 : parameters.size(); + while (constructorArgumentTypes.size() < fixedParameters) + { + constructorArgumentTypes.push_back(restArgumentType); + } + + // ...and for its own rest (`constructor(...items: T[])` of `new (...args: number[]) => L`: T is number) + if (hasRest) + { + constructorArgumentTypes.push_back(restArgumentType); + } + + constructorArgumentCount = std::max(argumentCount, constructorArgumentTypes.size()); + } + + if (!hasSpread && (constructorArgumentCount < required || (!hasRest && constructorArgumentCount > parameters.size()))) { return {}; } StringMap inferredTypes; - for (auto [index, argumentType] : enumerate(argumentTypes)) + for (auto [index, argumentType] : enumerate(constructorArgumentTypes)) { if (index >= parameters.size() && !hasRest) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index c15747f2c..1a00929ca 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -2120,7 +2120,8 @@ class MLIRGenImpl GenericClassInfo::TypePtr genericClassInfo, NodeArray arguments, const GenContext &genContext, - ArrayRef knownArgumentTypes = {}); + ArrayRef knownArgumentTypes = {}, + mlir::Type restArgumentType = mlir::Type()); std::pair instantiateSpecializedInterfaceType( mlir::Location location, mlir_ts::InterfaceType genericInterfaceType, NodeArray typeArguments, @@ -3703,6 +3704,8 @@ class MLIRGenImpl const GenContext &genContext); mlir::LogicalResult declareFunctionVars(Node body, const GenContext &genContext); + + void markHoistedLexicalOwned(mlir::Location location, StringRef name); mlir::Type functionVarTypeOfGenericInit(VariableDeclaration typing, mlir::Type type, const GenContext &genContext); mlir::LogicalResult mlirGenFunctionVar(VariableDeclaration item, VariableClass varClass, const GenContext &genContext); @@ -5979,6 +5982,8 @@ class MLIRGenImpl // (`n is number` of a number is whatever the guard returns): a value of that type is narrowed to // nothing where it is false bool testIsTrueOfType = false; + // `!(x instanceof C)`: x is a C where the test is false, as checked at run time + bool checkedByInstanceOf = false; }; // what a false condition narrows: one test gives one case, `a || b` (false when both are) gives @@ -5991,6 +5996,8 @@ class MLIRGenImpl { // (as in checkSafeCast: a failed narrowing must not leave the builder before an op it erased) auto insertionPointBefore = builder.saveInsertionPoint(); + MLIRValueGuard checkedGuard(castCheckedByInstanceOf); + castCheckedByInstanceOf = elseSafeCase.checkedByInstanceOf; if (mlir::failed(addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext))) { builder.restoreInsertionPoint(insertionPointBefore); @@ -6027,9 +6034,50 @@ class MLIRGenImpl } } + // the members of `type` (a union, or one type) that are an instance of the generic class: a G, or a class derived + // from one; none: null + mlir::Type instancesOfGenericClass(mlir::Type type, mlir_ts::ClassType genericClassType) + { + auto isInstance = [&](mlir::Type member) { + auto classType = dyn_cast(member); + for (auto classInfo = classType ? getClassInfoByFullName(classType.getName().getValue()) : ClassInfo::TypePtr(); + classInfo; classInfo = classInfo->baseClasses.empty() ? ClassInfo::TypePtr() : classInfo->baseClasses.front()) + { + if (classInfo->originClassType == genericClassType) + { + return true; + } + } + + return false; + }; + + if (auto unionType = dyn_cast(type)) + { + SmallVector instances; + for (auto member : unionType.getTypes()) + { + if (isInstance(member)) + { + instances.push_back(member); + } + } + + return instances.empty() ? mlir::Type() : instances.size() == 1 ? instances.front() : getUnionType(instances); + } + + return isInstance(type) ? type : mlir::Type(); + } + mlir::LogicalResult addSafeCastStatement(Expression expr, Node typeToken, bool inverse, ElseSafeCase* elseSafeCase, const GenContext &genContext) { + // (an `instanceof` test's narrowing is for the narrowing cast only: not for what the type makes - a generic + // class instantiated - castCheckedByInstanceOf) + auto checkedByInstanceOf = castCheckedByInstanceOf; + MLIRValueGuard checkedGuard(castCheckedByInstanceOf); + castCheckedByInstanceOf = false; auto safeType = getType(typeToken, genContext); + castCheckedByInstanceOf = checkedByInstanceOf; return addSafeCastStatement(expr, safeType, inverse, elseSafeCase, genContext); } @@ -6070,6 +6118,11 @@ class MLIRGenImpl auto expr = stripParenthesesAndUntangleEquals(exprIn); + // (an `instanceof` test's narrowing is for the narrowing cast only, not for what reading the value makes) + auto checkedByInstanceOf = castCheckedByInstanceOf; + MLIRValueGuard checkedGuard(castCheckedByInstanceOf); + castCheckedByInstanceOf = false; + // only what names a place can be narrowed: the value is read again here, and a call (`o() === undefined && x`) // was made a second time - a third in an `if`. Its result is not named again, so there is nothing to narrow. if (!isNarrowableReference(expr)) @@ -6084,6 +6137,20 @@ class MLIRGenImpl EXIT_IF_FAILED_OR_NO_VALUE(result); auto exprValue = V(result); + // `v instanceof G` of a generic class: true of every G, and the generic itself is no type a value has - narrowed + // to it, an interface `v` crashed the compiler, a union "Can't resolve property". It is narrowed to the members + // of a union that are a G (or derive from one), else not at all + if (auto classType = dyn_cast(safeType); + classType && !getClassInfoByFullName(classType.getName().getValue()) + && getGenericClassInfoByFullName(classType.getName().getValue())) + { + safeType = instancesOfGenericClass(exprValue.getType(), classType); + if (!safeType) + { + return mlir::success(); + } + } + LLVM_DEBUG(llvm::dbgs() << "\n!! Is Safe Type the same: [" << exprValue.getType() << "] and [" << safeType << "]\n"); if (isSafeTypeTheSameAndNoNeedToCast(exprValue.getType(), safeType)) @@ -6118,7 +6185,9 @@ class MLIRGenImpl elseSafeCase->expr = expr; } + castCheckedByInstanceOf = checkedByInstanceOf; auto result2 = addSafeCastStatement(location, nameStr, exprValue, safeType, inverse, elseSafeCase, genContext); + castCheckedByInstanceOf = false; // we need to register pair type+field to associate to variable if (isNotLocalVariable) @@ -6182,6 +6251,11 @@ class MLIRGenImpl mlir::LogicalResult addSafeCastStatement(mlir::Location location, StringRef parameterName, mlir::Value exprValue, mlir::Type safeType, bool inverse, ElseSafeCase* elseSafeCase, const GenContext &genContext) { + // the narrowing is an `instanceof` test's: taken here, for its cast below only + auto checkedByInstanceOf = castCheckedByInstanceOf; + MLIRValueGuard checkedGuard(castCheckedByInstanceOf); + castCheckedByInstanceOf = false; + // narrowed to nothing (the `default` of a switch every case of which is handled, the `else` after the // last member was tested for): the code here is never reached, and the name is a `never`, with no value // to read out of what it was @@ -6283,7 +6357,9 @@ class MLIRGenImpl else { // (castToNarrowedType says how a class of a union of interfaces is read) + castCheckedByInstanceOf = checkedByInstanceOf; castedValue = castToNarrowedType(location, exprValue, safeType, genContext); + castCheckedByInstanceOf = false; if (!castedValue) { return mlir::failure(); @@ -6341,7 +6417,10 @@ class MLIRGenImpl } else { + // (an interface narrowed to a class by `instanceof` is the object it holds: castInterfaceToClass) + castCheckedByInstanceOf = checkedByInstanceOf; CAST_A(result, location, safeType, exprValue, genContext); + castCheckedByInstanceOf = false; castedValue = V(result); } } @@ -7012,7 +7091,9 @@ class MLIRGenImpl if (auto classType = getType(nf.createTypeReferenceNode(typeName), genContext); classType && !mth.isNoneType(classType)) { - elseSafeCases->push_back({stripParenthesesAndUntangleEquals(binExpr->left), classType}); + ElseSafeCase elseCase{stripParenthesesAndUntangleEquals(binExpr->left), classType}; + elseCase.checkedByInstanceOf = true; + elseSafeCases->push_back(elseCase); } } } @@ -7311,6 +7392,8 @@ class MLIRGenImpl // qualified name - handed over as the property access it is, it crashed if (auto typeName = instanceOfEntityName(nf, instanceOf->right)) { + MLIRValueGuard checkedGuard(castCheckedByInstanceOf); + castCheckedByInstanceOf = true; return addSafeCastStatement(instanceOf->left, nf.createTypeReferenceNode(typeName), false, elseSafeCase, genContext); } @@ -23437,6 +23520,10 @@ class MLIRGenImpl // were refused does not go on to the defaults (`any`), which would only be refused again bool sharedElementsRefused = false; + // a narrowing by `x instanceof C` is being cast (addSafeCastStatement): an interface x holds a C, checked at run + // time, so it is cast to the object it holds, with no other way for what is not a C (castInterfaceToClass) + bool castCheckedByInstanceOf = false; + // the declaration (no body) each declared function's full name came from, and the module it was // generated into - discovery's is thrown away, and a library's __decls is parsed again for the // next pass; see mlirGen(FunctionDeclaration) diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index 157846447..277b1d0db 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -2691,11 +2691,33 @@ namespace mlirgen { return mlir::failure(); } + + // under -mm=own a `let`/`const` a function before it reads owns the value its declaration gives it, as one + // declared with its value does: marked before anything captures it (mlirGenFunctionVar) + if (compileOptions.memoryModel == MemoryModelOwn && forwardReferenced.contains(name)) + { + markHoistedLexicalOwned(loc(declaration), name); + } } return mlir::success(); } + // A `let`/`const` a function before it reads (`const f = () => g(); const g = () => 10;`), made one of the function's + // variables (declareFunctionVars), is declared with no value - its slot starts as null - and given it once, by its + // declaration. Under -mm=own the variable owns that value, as one declared with it does: not marked, its cell was + // "captured by a closure, but -mm=own cannot tell who owns its value" (TSLANG 144) + void MLIRGenImpl::markHoistedLexicalOwned(mlir::Location location, StringRef name) + { + auto slot = symbolTable.lookup(name).first; + auto varOp = slot ? slot.getDefiningOp() : mlir_ts::VariableOp(); + auto refType = varOp ? dyn_cast(varOp.getType()) : mlir_ts::RefType(); + if (varOp && !varOp.getInitializer() && refType && mth.ownsHeapMemory(location, refType.getElementType())) + { + varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + } + } + // `var x = e` in a function: an assignment to the function's `x`, declared before the body or here, the first time // it is reached. `var x` again is nothing. A destructuring `var` is a variable of the block it is in, as `let`. mlir::LogicalResult MLIRGenImpl::mlirGenFunctionVar(VariableDeclaration item, VariableClass varClass, @@ -2876,6 +2898,14 @@ namespace mlirgen return mlir::success(); } + // under -mm=own a `let`/`const` a function before it reads, declared only here (its type known only here): it owns + // its value (markHoistedLexicalOwned) + if (compileOptions.memoryModel == MemoryModelOwn && genContext.functionTopLevelVars + && genContext.functionTopLevelVars->contains(item->pos.pos)) + { + markHoistedLexicalOwned(location, name); + } + NodeFactory nf(NodeFactoryFlags::None); auto identifier = nf.createIdentifier(stows(name.str())); auto assignment = diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 67e56ad21..92cca960e 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -4595,6 +4595,14 @@ class OwnedReturnConsumptionPass return thisSymbolRefOp.getIdentifier(); } + // a function an object literal holds (`o.make(i)` of `const o = { make: (x) => new P(x) }`): it names it. Named + // by nothing, its result was taken for one the call does not hand over, and never given back - a leak under + // rc and -mm=own whenever the program links anything whose returns are not classified + if (auto symbol = own_facts::constantFieldFunction(callee)) + { + return symbol.getValue(); + } + auto getMethodOp = callee.getDefiningOp(); if (!getMethodOp) { diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 0f3846bc2..04366fed2 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -164,6 +164,25 @@ inline mlir::FlatSymbolRefAttr directCallee(mlir::Operation *op) return {}; } +// A function an object literal holds, read out of it as the constant it folds to (`const o = { make: (x) => new P(x) }; +// o.make(i)`: a constant tuple of the functions' symbols): that function, named; else null +inline mlir::FlatSymbolRefAttr constantFieldFunction(mlir::Value value) +{ + auto extractOp = value ? value.getDefiningOp() : mlir_ts::ExtractPropertyOp(); + auto constantOp = extractOp && extractOp.getPosition().size() == 1 + ? extractOp.getObject().getDefiningOp() + : mlir_ts::ConstantOp(); + auto elements = constantOp ? mlir::dyn_cast(constantOp.getValue()) : mlir::ArrayAttr(); + if (!elements) + { + return {}; + } + + auto position = extractOp.getPosition().front(); + return position >= 0 && position < (int64_t)elements.size() ? mlir::dyn_cast(elements[position]) + : mlir::FlatSymbolRefAttr(); +} + // The function value a call goes through, or null when it names its callee. inline mlir::Value calleeValue(mlir::Operation *op) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index f8265b47e..de93e0fce 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2575,6 +2575,22 @@ foreach(issue211_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_211-${issue211_mm} COMMAND test-runner -jit -mm=${issue211_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_211.ts") tslang_add_test(NAME test-compile-00tslang_issue_211-${issue211_mm} COMMAND test-runner -mm=${issue211_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_211.ts") endforeach() +# TSLANG 212: 132 generic class for a constructor type, 164 instanceof narrowing (own borrows; generic classes), +# 144 forward-captured consts, 191 an array of a union as members, an object literal's function called +foreach(issue212_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_212-${issue212_mm} COMMAND test-runner -jit -mm=${issue212_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212.ts") + tslang_add_test(NAME test-compile-00tslang_issue_212-${issue212_mm} COMMAND test-runner -mm=${issue212_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212.ts") +endforeach() +# TSLANG 212 (152): a record's strings spread into a dictionary or given to Object.assign (own copies them) +foreach(issue212d_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_212_dictionary-${issue212d_mm} COMMAND test-runner -jit -mm=${issue212d_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212_dictionary.ts") + tslang_add_test(NAME test-compile-00tslang_issue_212_dictionary-${issue212d_mm} COMMAND test-runner -mm=${issue212d_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212_dictionary.ts") +endforeach() +# TSLANG 212 (139): a class given to an interface of a construct signature; not under -mm=own (refuses its result) +foreach(issue212c_mm gc rc none) + tslang_add_test(NAME test-jit-00tslang_issue_212_ctor_interface-${issue212c_mm} COMMAND test-runner -jit -mm=${issue212c_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212_ctor_interface.ts") + tslang_add_test(NAME test-compile-00tslang_issue_212_ctor_interface-${issue212c_mm} COMMAND test-runner -mm=${issue212c_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_212_ctor_interface.ts") +endforeach() # TSLANG 152, -mm=own: a store past the end through a parameter's alias stops with a check, not a write past the block add_test(NAME test-jit-own-grow-past-end-check COMMAND $ --emit=jit --no-default-lib -mm=own @@ -2595,8 +2611,8 @@ foreach(issues_mm gc none) tslang_add_test(NAME test-jit-00tslang_issue_176-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_176.ts") tslang_add_test(NAME test-compile-00tslang_issue_176-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_176.ts") endforeach() -# a union of interfaces: instanceof, the class it narrows to, `v` (own refuses the narrowing, as for one interface) -foreach(issues_mm gc rc none) +# a union of interfaces: instanceof, the class it narrows to, `v` +foreach(issues_mm gc rc none own) tslang_add_test(NAME test-jit-00union_interfaces_instanceof-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00union_interfaces_instanceof.ts") tslang_add_test(NAME test-compile-00union_interfaces_instanceof-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00union_interfaces_instanceof.ts") endforeach() diff --git a/tslang/test/tester/tests/00tslang_issue_212.ts b/tslang/test/tester/tests/00tslang_issue_212.ts new file mode 100644 index 000000000..ee3a7835f --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_212.ts @@ -0,0 +1,149 @@ +// TSLANG 212: leftovers of 211's triage. + +// 132: a generic class given for a constructor type takes its type arguments from the type's parameters - a rest's +// element type for each constructor parameter it reaches (`any` makes T `any`, as TypeScript infers `Banana`) +class Banana { + constructor(public a: string, public property: T) { } +} +function fruitFactory1(Fruit: new (...args: any[]) => TFruit): TFruit { return new Fruit("x1", "foo"); } +function fruitFactory2(Fruit: new (a: string, ...args: any[]) => TFruit): TFruit { return new Fruit("x2", "foo"); } +function fruitFactory3(Fruit: new (a: string, s: "foo", ...args: any[]) => TFruit): TFruit { return new Fruit("x3", "foo"); } +function fruitFactory4(Fruit: new (a: string, ...args: "foo"[]) => TFruit): TFruit { return new Fruit("x4", "foo"); } +function fruitFactory5(Fruit: new (...args: "foo"[]) => TFruit): TFruit { return new Fruit("foo", "foo"); } + +function testGenericClassForConstructorType() { + const b1 = fruitFactory1(Banana); + assert(b1.a == "x1" && b1.property == "foo", "132 rest of any"); + const b2 = fruitFactory2(Banana); + assert(b2.a == "x2" && b2.property == "foo", "132 a, rest of any"); + const b3 = fruitFactory3(Banana); + assert(b3.a == "x3" && b3.property == "foo", "132 a, s, rest"); + const b4 = fruitFactory4(Banana); + assert(b4.a == "x4" && b4.property == "foo", "132 a, rest of \"foo\""); + const b5 = fruitFactory5(Banana); + assert(b5.a == "foo" && b5.property == "foo", "132 rest of \"foo\""); +} + +// 164: an interface narrowed to a class by `instanceof` is the object it holds - under -mm=own a borrow, as the +// interface is (it was taken for a reference of its own: "'v' is a parameter, kept here") +interface IA { a: number; } +interface IB { b: string; } +class A implements IA { a: number = 1; s: string; constructor(s: string) { this.s = s; } } +class B implements IB { b = "x"; } + +function narrowed(v: IA): string { + if (v instanceof A) return "A" + v.a + v.s; + return "?"; +} + +function narrowedFromUnion(v: IA | IB): string { + if (!(v instanceof A)) return "?"; + return v.s; +} + +// ...and by a generic class: true of every G, it narrows a union to its members that are one, else not at all (an +// interface crashed the compiler, a union read "Can't resolve property") +class G implements IA { a: number = 2; field: T; constructor(f: T) { this.field = f; } } +class K extends G { k = "k"; } + +function genericOfInterface(v: IA): string { + if (v instanceof G) return "G" + v.a; + return "?"; +} + +function genericOfUnion(v: G | B): string { + if (v instanceof G) return "G" + v.field; + return "B" + v.b; +} + +function derivedOfUnion(v: K | B): string { + if (!(v instanceof G)) return "B" + v.b; + return "K" + v.k; +} + +function testInstanceOfNarrowing() { + for (let i = 0; i < 3; i++) { + const a: IA = new A("s" + i); + const u: IA | IB = new A("t" + i); + const b: IA | IB = new B(); + assert(narrowed(a) == "A1s" + i, "164 interface"); + assert(narrowedFromUnion(u) == "t" + i && narrowedFromUnion(b) == "?", "164 union of interfaces"); + } + + assert(genericOfInterface(new G(5)) == "G2", "generic of an interface"); + assert(genericOfInterface(new A("z")) == "?", "generic of an interface, another class"); + assert(genericOfUnion(new G(7)) == "G7" && genericOfUnion(new B()) == "Bx", "generic of a union"); + assert(derivedOfUnion(new K("s")) == "Kk" && derivedOfUnion(new B()) == "Bx", "derived of a union"); +} + +// 144: a const a function before it reads, holding a closure or an object, owns it under -mm=own ("captured by a +// closure, but -mm=own cannot tell who owns its value") +class C { v: string; constructor(v: string) { this.v = v; } } + +function forwardClosure(k: number): number { + const f = () => g() + k; + const g = () => 10 + k; + return f(); +} + +function forwardObjects(i: number): string { + const f = () => o.x + c.v; + const o = { x: "a" + i }; + const c = new C("c" + i); + const h = () => c.v + "!"; + return f() + h(); +} + +function forwardEarlyExit(i: number): string { + const f = () => k.v; + if (i % 2 == 0) return "early"; + const k = new C("k" + i); + return f(); +} + +function testForwardCaptures() { + for (let i = 0; i < 3; i++) { + assert(forwardClosure(i) == 10 + 2 * i, "144 closure"); + assert(forwardObjects(i) == "a" + i + "c" + i + "c" + i + "!", "144 objects"); + assert(forwardEarlyExit(i) == (i % 2 == 0 ? "early" : "k" + i), "144 early exit"); + } +} + +// 191: an array of a union said to be an array of members of it is read element by element (its elements are unions: +// "cast from array type ... is not supported" when it was lowered; tsc's `x.slice(1) as readonly string[]` of +// `[number, string] | [number, string, string]`, which needs the default library's slice) +function membersOf(i: number): number { + const m: (number | string)[] = ["a" + i, "bb"]; + const r = m as readonly string[]; + return r.length * 10 + r[0].length + r[1].length; +} + +function testArrayOfUnionAsMembers() { + for (let i = 0; i < 3; i++) { + assert(membersOf(i) == 24, "191 array of a union as readonly string[]"); + } +} + +// a function an object literal holds, called (`o.make(i)`): its result is given back (it was never, under rc and +// -mm=own, wherever the program links a library function whose result is not classified) +class Made { s: string; constructor(public n: number) { this.s = "m" + n; } } + +function testObjectLiteralFunction() { + const o = { make: (n: number): Made => new Made(n) }; + let total = 0; + for (let i = 0; i < 3; i++) { + const m = o.make(i); + total += m.n + m.s.length; + } + + assert(total == 9, "object literal function"); +} + +function main() { + testGenericClassForConstructorType(); + testInstanceOfNarrowing(); + testForwardCaptures(); + testArrayOfUnionAsMembers(); + testObjectLiteralFunction(); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_212_ctor_interface.ts b/tslang/test/tester/tests/00tslang_issue_212_ctor_interface.ts new file mode 100644 index 000000000..ece9814f5 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_212_ctor_interface.ts @@ -0,0 +1,36 @@ +// TSLANG 212 (139): a class given to an interface of a construct signature only (`interface PtCtor { new (x: number): +// Pt }`) - "the class 'P' itself can't be given as interface 'PtCtor'". It is made over an object of one field, `new`, +// which calls the class's constructor and returns its object as the signature's result. Not under -mm=own, which +// refuses a construct signature's result (through a type literal as well). +interface Pt { x: number; } +interface PtCtor { new (x: number): Pt; } +class P implements Pt { s: string; constructor(public x: number) { this.s = "s" + x; } } +class Q implements Pt { constructor(public x: number) { } } + +function make(c: PtCtor, x: number): Pt { return new c(x); } + +class R { constructor(public r: string) { } } +interface RCtor { new (r: string): R; } + +// a generic one (it was "the class 'A' itself can't be given as interface 'Constructor'", TSLANG 204) +interface Constructor { new (...args: any[]): T; } +class Plain { a = 1; } + +function makeR(c: RCtor): R { return new c("r"); } + +function main() { + let total = 0; + for (let i = 0; i < 3; i++) { + total += make(P, i).x + make(Q, 10).x; + } + + assert(total == 33, "constructor interface"); + + const ctor: PtCtor = P; + assert(new ctor(4).x == 4, "constructor interface held"); + assert(makeR(R).r == "r", "returning the class itself"); + + const c: Constructor = Plain; + assert(new c().a == 1, "a generic constructor interface"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_212_dictionary.ts b/tslang/test/tester/tests/00tslang_issue_212_dictionary.ts new file mode 100644 index 000000000..952bdc7c0 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_212_dictionary.ts @@ -0,0 +1,111 @@ +// TSLANG 212 (152): a record's strings spread into a dictionary, or given to Object.assign - named or a literal - are +// copied under -mm=own (strings are values): the dictionary keeps what it is given ("a value that borrows a field cannot +// be stored"); the literal is given back after (it leaked). The tests compile without the default library: its +// ObjectDictionary, as 00object_dictionary_builtins.ts has it. +@dictionary +class ObjectDictionary { + private _keys: string[] = []; + private _values: T[] = []; + private _closed: int = 0; + + close(level: int) { + if (level > this._closed) { + this._closed = level; + } + } + + closed(): int { + return this._closed; + } + + private find(key: string): int { + for (let i = 0; i < this._keys.length; i++) { + if (this._keys[i] == key) { + return i; + } + } + + return -1; + } + + get(key: string): T | undefined { + const i = this.find(key); + if (i < 0) { + return undefined; + } + + return this._values[i]; + } + + set(key: string, value: T | undefined) { + if (value === undefined) { + this.delete(key); + return; + } + + const i = this.find(key); + if (i < 0) { + if (this._closed > 0) { + throw "not extensible"; + } + + this._keys.push("" + key); + this._values.push(value); + return; + } + + if (this._closed == 3) { + throw "frozen"; + } + + this._values[i] = value; + } + + [key: string]: T | undefined; + + has(key: string): boolean { + return this.find(key) >= 0; + } + + delete(key: string): boolean { + const i = this.find(key); + if (i < 0) { + return false; + } + + if (this._closed >= 2) { + throw "sealed"; + } + + this._keys.splice(i, 1); + this._values.splice(i, 1); + return true; + } + + keys(): string[] { + const r: string[] = []; + for (let i = 0; i < this._keys.length; i++) { + r.push("" + this._keys[i]); + } + + return r; + } +} + +function main() { + for (let i = 0; i < 3; i++) { + const rec = { a: "x" + i, b: "y" }; + const d1: { [k: string]: string } = { ...rec }; + assert(d1["a"] == "x" + i && d1["b"] == "y", "spread"); + + const d2: { [k: string]: string } = {}; + Object.assign(d2, rec); + assert(d2["a"] == "x" + i && d2["b"] == "y", "Object.assign of a record"); + + const d3: { [k: string]: string } = {}; + Object.assign(d3, { a: "z" + i, b: "w" }); + assert(d3["a"] == "z" + i && d3["b"] == "w", "Object.assign of a literal"); + } + + print("done."); +} diff --git a/tslang/test/tester/tests/00union_interfaces_instanceof.ts b/tslang/test/tester/tests/00union_interfaces_instanceof.ts index f2cc6c52a..0269a44b8 100644 --- a/tslang/test/tester/tests/00union_interfaces_instanceof.ts +++ b/tslang/test/tester/tests/00union_interfaces_instanceof.ts @@ -1,7 +1,7 @@ // `v instanceof A` of a union of interfaces asks the interface the union holds (it said false), the class it // narrows to is the object that interface holds (it read the interface's vtable as the object), and `v` is -// the interface it holds (it crashed the compiler). Not under -mm=own: an interface narrowed to a class is -// refused there ("kept here") for a plain interface too. +// the interface it holds (it crashed the compiler). Under -mm=own the class it narrows to is a borrow, as the +// interface is (it was taken for a reference of its own: "kept here", TSLANG 164). interface IA { a: number; } interface IB { b: string; } class A implements IA { a: number = 1; } diff --git a/tslang/test/tester/tests/class_itself_interface_error.ts b/tslang/test/tester/tests/class_itself_interface_error.ts index 635291ca2..e950664ac 100644 --- a/tslang/test/tester/tests/class_itself_interface_error.ts +++ b/tslang/test/tester/tests/class_itself_interface_error.ts @@ -1,6 +1,8 @@ -// TSLANG 204: an error by design (it was an internal error) +// TSLANG 204: an error by design (it was an internal error). An interface of a construct signature only is made of the +// class (TSLANG 212, 00tslang_issue_212_ctor_interface.ts); one with other members as well is not interface Constructor { new (...args: any[]): T; + tag: string; } class A { From 3417459fda58e37ba8895a513532e24469b9cc28 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 08:43:40 +0000 Subject: [PATCH 2/3] WIP 212: array of a union as members only for a tagged union (a tag-free one keeps its cast) Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 5481af979..d9162ef40 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2775,8 +2775,11 @@ namespace mlirgen // The array itself cannot be: its elements are unions, laid out as such ("cast from array type ... is not // supported" when it was lowered) auto narrowsElements = [&]() { + // (a union with no tag - classes, `T | null` of a reference - is laid out as its members are: cast as it is, + // the same array, as before) auto srcUnionType = dyn_cast(srcElementType); - if (!srcUnionType) + mlir::Type srcBaseType; + if (!srcUnionType || !mth.isUnionTypeNeedsTag(location, srcUnionType, srcBaseType)) { return false; } From bb0c2e8f5a3b06cc1b338b170c31aee688575d0b Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 09:07:47 +0000 Subject: [PATCH 3/3] 212: an array of a union read as members only where asserted (as, ); an implicit conversion stays as it was Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 4 +++- tslang/lib/TypeScript/MLIRGenCast.cpp | 12 +++++++++++- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 6 ++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 4 ++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 233884da8..a076b22f1 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3873,7 +3873,9 @@ Tests `00tslang_issue_211.ts` (all models), `own_grow_past_end_check.ts` (-mm=ow stays refused, as before ("kept here", "borrows 'this.c'"). - 191: an array of a union said to be an array of members of it (`x.slice(1) as readonly string[]` of `[number, string] | [number, string, string]`, tsc sliceResultCast): "cast from array type ... is not supported" with no - location, at lowering. It is a new array, each element read as the member it is said to be (castArrayElementwise). + location, at lowering. It is a new array, each element read as the member it is said to be (castArrayElementwise), + for an assertion (`as`, ``) of a union with a tag only: TypeScript refuses `const s: string[] = m`, which stays + as it was, and a union with no tag (classes) is cast as it is, the same array. - 139: a class given to an interface of a construct signature only (`interface PtCtor { new (x: number): Pt }`, `make(P)`; `const c: Constructor = A`): "the class 'P' itself can't be given as interface" (TSLANG 204's clear error for an internal one). It is made over an object of one field, `new`, a function calling the class's diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index d9162ef40..b5ade16b1 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2763,6 +2763,11 @@ namespace mlirgen auto srcElementType = srcArrayType.getElementType(); auto elementType = arrayType.getElementType(); + // (the assertion is this cast's, not the casts that build the new array's elements) + auto asserted = castIsAssertion; + MLIRValueGuard assertionGuard(castIsAssertion); + castIsAssertion = false; + // ...and an array of any other elements given as `any[]` (`("a" | "b")[]` for a parameter // `ReadonlyArray` inferred `any`): each element is boxed on its own auto boxesElements = [&]() { @@ -2773,8 +2778,13 @@ namespace mlirgen // ...and an array of a union said to be an array of members of it (`x.slice(1) as readonly string[]` of // `[number, string] | [number, string, string]`, TSLANG 191): each element is read as the member it is said to be. // The array itself cannot be: its elements are unions, laid out as such ("cast from array type ... is not - // supported" when it was lowered) + // supported" when it was lowered). Only asserted: TypeScript refuses `const s: string[] = m` auto narrowsElements = [&]() { + if (!asserted) + { + return false; + } + // (a union with no tag - classes, `T | null` of a reference - is laid out as its members are: cast as it is, // the same array, as before) auto srcUnionType = dyn_cast(srcElementType); diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index c69a26482..88618421b 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -395,6 +395,9 @@ namespace mlirgen return reinterpreted; } + // (asserted: an array of a union may be read as an array of members of it, castArrayElementwise) + MLIRValueGuard assertionGuard(castIsAssertion); + castIsAssertion = isa(typeInfo) && isa(exprValue.getType()); CAST_A(castedValue, location, typeInfo, exprValue, genContext); return castedValue; } @@ -442,6 +445,9 @@ namespace mlirgen return reinterpreted; } + // (asserted: an array of a union may be read as an array of members of it, castArrayElementwise) + MLIRValueGuard assertionGuard(castIsAssertion); + castIsAssertion = isa(typeInfo) && isa(exprValue.getType()); CAST_A(castedValue, location, typeInfo, exprValue, genContext); return castedValue; } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 1a00929ca..78f9520e2 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -23524,6 +23524,10 @@ class MLIRGenImpl // time, so it is cast to the object it holds, with no other way for what is not a C (castInterfaceToClass) bool castCheckedByInstanceOf = false; + // the cast is an assertion's (`x as T`, `x`): castArrayElementwise reads an array of a union as an array of members + // of it only where the program says so + bool castIsAssertion = false; + // the declaration (no body) each declared function's full name came from, and the module it was // generated into - discovery's is thrown away, and a library's __decls is parsed again for the // next pass; see mlirGen(FunctionDeclaration)