From 7902f5a70ab361225245d2520e255f21e6d897ec Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 14:35:07 +0000 Subject: [PATCH 01/11] WIP 215: Record is a dictionary of T (built-in Record and a mapped type of string keys) Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 2 +- tslang/lib/TypeScript/MLIRGenTypes.cpp | 41 ++++-- tslang/test/tester/CMakeLists.txt | 5 + .../test/tester/tests/00tslang_issue_215.ts | 124 ++++++++++++++++++ 4 files changed, 162 insertions(+), 10 deletions(-) create mode 100644 tslang/test/tester/tests/00tslang_issue_215.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 21ab54362..d1bc30147 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -21076,7 +21076,7 @@ class MLIRGenImpl mlir::Type ExtractTypes(mlir::Location location, mlir::Type type, mlir::Type extract); - mlir::Type RecordType(mlir::Type keys, mlir::Type valueType); + mlir::Type RecordType(mlir::Location location, mlir::Type keys, mlir::Type valueType, const GenContext &genContext); mlir::Type PickTypes(mlir::Type type, mlir::Type keys); diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index 6b48a0f55..d0bbe3fc7 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -1490,7 +1490,7 @@ namespace mlirgen case EmbeddedType::Omit: return OmitTypes(firstType, secondType); case EmbeddedType::Record: - return RecordType(firstType, secondType); + return RecordType(location, firstType, secondType, genContext); default: return mlir::Type(); } @@ -1622,7 +1622,8 @@ namespace mlirgen return resultType; } - mlir::Type MLIRGenImpl::RecordType(mlir::Type keys, mlir::Type valueType) + mlir::Type MLIRGenImpl::RecordType(mlir::Location location, mlir::Type keys, mlir::Type valueType, + const GenContext &genContext) { // keys or values that could not be made (their error is reported where they were made) if (!keys || !valueType) @@ -1631,7 +1632,16 @@ namespace mlirgen } LLVM_DEBUG(llvm::dbgs() << "\n!! Record: " << valueType << ", keys: " << keys << "\n";); - + + // `Record` is `{ [key: string]: T }`: a dictionary of T (see getTupleType of a type literal) + if (isa(keys)) + { + if (auto dictionaryType = getObjectDictionaryType(location, valueType, genContext)) + { + return dictionaryType; + } + } + SmallVector fields; auto addTypeProcessKey = [&](mlir::Type keyType) @@ -1654,12 +1664,9 @@ namespace mlirgen { addTypeProcessKey(litType); } - // else: keys isn't a literal or a union of literals (e.g. the general `string`/`number` - // type, as in `Record`) - this builtin fallback can't enumerate an unbounded - // key set into fields. In practice this is dead: Record is declared as a mapped - // type in lib.generics.ts and resolveGenericType resolves it before this fallback is - // ever reached (see docs/not-implemented-audit.md); kept as a no-op rather than a crash - // for the same reason PickTypes's analogous pickTypesProcessKey already no-ops here. + // else: keys isn't a literal or a union of literals (`number`, or `string` without the default library's + // dictionary class) - this builtin can't enumerate an unbounded key set into fields. With the default + // library, Record is the mapped type of lib.generics.ts, made by getMappedType, not here. return getTupleType(fields); } @@ -2469,6 +2476,22 @@ namespace mlirgen return mlir::Type(); } + // `{ [K in string]: T }` (`Record`) is `{ [key: string]: T }`: a dictionary of T, its keys known + // at run time (see getTupleType of a type literal). Without the default library's dictionary class, no + // fields, as before. + if (isa(constrainType) && !hasNameType) + { + GenContext stringKeyGenContext(genContext); + stringKeyGenContext.typeParamsWithArgs.insert({typeParam->getName(), std::make_pair(typeParam, constrainType)}); + if (auto valueType = getType(mappedTypeNode->type, stringKeyGenContext)) + { + if (auto dictionaryType = getObjectDictionaryType(loc(mappedTypeNode), valueType, genContext)) + { + return dictionaryType; + } + } + } + if (auto keyOfType = dyn_cast(constrainType)) { // `{ [K in keyof T]: T[K] }` of a T not known yet: K stands for its constraint (`keyof T`) while the diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2c5a71369..0d8d634e9 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2609,6 +2609,11 @@ foreach(issue214_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_214-${issue214_mm} COMMAND test-runner -jit -mm=${issue214_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_214.ts") tslang_add_test(NAME test-compile-00tslang_issue_214-${issue214_mm} COMMAND test-runner -mm=${issue214_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_214.ts") endforeach() +# TSLANG 215: Record a dictionary, a union of tuples cast to one of them, -mm=own slice of one +foreach(issue215_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_215-${issue215_mm} COMMAND test-runner -jit -mm=${issue215_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_215.ts") + tslang_add_test(NAME test-compile-00tslang_issue_215-${issue215_mm} COMMAND test-runner -mm=${issue215_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_215.ts") +endforeach() # TSLANG 213 (140): an `await` in a `finally` block foreach(issue213a_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_213_await_finally-${issue213a_mm} COMMAND test-runner -jit -mm=${issue213a_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_213_await_finally.ts") diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts new file mode 100644 index 000000000..558a2bb8a --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -0,0 +1,124 @@ +// TSLANG 215: `Record` is `{ [key: string]: T }`, a dictionary of T (it was an object with no fields: the +// literal given to it lost its fields, and Object.keys gave none), both as the built-in Record and as a mapped type +// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them; under -mm=own `slice` of one. +// The tests compile without the default library: its ObjectDictionary, as the compiler finds it by name. +@dictionary +class ObjectDictionary { + private _keys: string[] = []; + private _values: T[] = []; + + get size() { + return this._keys.length; + } + + 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) { + this._keys.push("" + key); + this._values.push(value); + return; + } + + 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; + } + + 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 objectDictionaryAssign(target: ObjectDictionary, source: ObjectDictionary) { + for (const k in source) { + target[k] = source[k]; + } +} + +type Rec = { [P in K]: T }; + +function keysOf(r: Record) { + return Object.keys(r).length; +} + +function sumOf(r: Rec) { + let total: number = 0; + for (const k in r) { + total += r[k] ?? 0; + } + + return total; +} + +function main() { + const r: Record = { a: 1, b: 2 }; + assert(Object.keys(r).length == 2); + assert(r["a"] == 1); + const k = "b"; + assert(r[k] == 2); + assert(r["c"] === undefined); + r["c"] = 3; + assert(keysOf(r) == 3); + + const m: Rec = { x: 10, y: 20 }; + assert(sumOf(m) == 30); + + let made = ""; + for (let i = 0; i < 3; i++) { + const s: Record = { first: "f" + i }; + s["second"] = "s" + i; + made += s["first"] + s["second"]; + } + + assert(made == "f0s0f1s1f2s2"); + + // a Record of known keys stays an object of those fields + const p: Record<"a" | "b", number> = { a: 5, b: 6 }; + assert(p.a + p.b == 11); + + print("done."); +} From daaf976f35c01d82e89e41a9e23ca6d174dda842 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 14:39:30 +0000 Subject: [PATCH 02/11] WIP 215: a union of tuples cast to one of them (a member lacking its elements throws), indexed at a common element; a missing tuple element is an error, not a silent failure Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 62 +++++++++++++++++++ tslang/lib/TypeScript/MLIRGenCast.cpp | 47 ++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 2 + .../test/tester/tests/00tslang_issue_215.ts | 47 ++++++++++++++ 4 files changed, 158 insertions(+) diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 66b2fe6ff..72b51fdad 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1763,6 +1763,60 @@ namespace mlirgen return lookup(0); } + // The first member of a union of tuples, all of elements only, when each has the element at the constant index + // `index` holds and the same element types up to it: one laid out alike there, whichever member a value holds. + // No type otherwise. + mlir::Type MLIRGenImpl::unionTuplesCommonPrefixMember(mlir_ts::UnionType unionType, mlir::Value index) + { + auto constantOp = index.getDefiningOp(); + if (!constantOp) + { + return mlir::Type(); + } + + int64_t position = -1; + if (auto intAttr = dyn_cast(constantOp.getValue())) + { + position = intAttr.getValue().getSExtValue(); + } + else if (auto floatAttr = dyn_cast(constantOp.getValue()); + floatAttr && floatAttr.getValueAsDouble() == (double)(int64_t)floatAttr.getValueAsDouble()) + { + position = (int64_t)floatAttr.getValueAsDouble(); + } + + if (position < 0) + { + return mlir::Type(); + } + + SmallVector tuples; + for (auto member : unionType.getTypes()) + { + auto tupleType = dyn_cast(mth.convertConstTupleTypeToTupleType(member)); + if (!tupleType || (int64_t)tupleType.size() <= position + || llvm::any_of(tupleType.getFields(), [](auto &field) { return !!field.id; })) + { + return mlir::Type(); + } + + tuples.push_back(tupleType); + } + + for (auto tupleType : ArrayRef(tuples).drop_front()) + { + for (int64_t i = 0; i <= position; i++) + { + if (tupleType.getFieldInfo(i).type != tuples.front().getFieldInfo(i).type) + { + return mlir::Type(); + } + } + } + + return unionType.getTypes().front(); + } + ValueOrLogicalResult MLIRGenImpl::mlirGenElementAccess(mlir::Location location, mlir::Value expression, mlir::Value argumentExpression, bool isConditionalAccess, const GenContext &genContext) { auto arrayType = expression.getType(); @@ -1792,6 +1846,14 @@ namespace mlirgen expression = builder.create(location, baseType, expression); } } + // `x[1]` of a union of tuples (`[number, string] | [number, string, string]`), each holding that element after + // the same elements: it is where the first member has it, whichever member the value holds (it was "access + // expression is not applicable") + else if (auto firstTuple = unionTuplesCommonPrefixMember(unionType, argumentExpression)) + { + expression = builder.create(location, firstTuple, expression); + arrayType = firstTuple; + } } if (isa(arrayType)) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index fd4b227a5..2626f2c19 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -207,6 +207,25 @@ namespace mlirgen return mlir::Value(); } + // Whether a tuple lacks a field of `fields` that absentFieldValue can't make: one of another type than an optional, + // `undefined` or `any`, which is neither in it by name nor, an element, at its index (`[number, string]` for + // `[number, string, string]`). Nothing is generated. + bool MLIRGenImpl::tupleLacksField(mlir_ts::TupleType srcTupleType, ArrayRef fields) + { + for (auto [index, fieldInfo] : enumerate(fields)) + { + auto positional = fieldInfo.id == mlir::Attribute() + || (index < srcTupleType.size() && srcTupleType.getFieldInfo(index).id == mlir::Attribute()); + auto present = positional ? index < srcTupleType.size() : srcTupleType.getIndex(fieldInfo.id) >= 0; + if (!present && !isa(fieldInfo.type)) + { + return true; + } + } + + return false; + } + ValueOrLogicalResult MLIRGenImpl::mapTupleToFields(mlir::Location location, SmallVector &values, mlir::Value value, mlir_ts::TupleType srcTupleType, ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, bool filterSpecialCases, const GenContext &genContext, bool errorAsWarning) { @@ -237,6 +256,12 @@ namespace mlirgen values.push_back(undefVal); continue; } + + // (it was read past the tuple's end, and failed with nothing said: "failed statement") + emitError(location) << "element " << index << " of '" + << to_print(mlir_ts::TupleType::get(builder.getContext(), fields)) + << "' is not in tuple '" << to_print(srcTupleType) << "'"; + return mlir::failure(); } MLIRPropertyAccessCodeLogic cl(compileOptions, builder, location, value, builder.getI32IntegerAttr(index)); @@ -5911,8 +5936,30 @@ namespace mlirgen { auto members = unionType.getTypes(); auto box = builder.create(location, getAnyType(), value); + auto targetTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(type)); std::function castOf = [&](size_t index) -> ValueOrLogicalResult { auto asMember = [&]() -> ValueOrLogicalResult { + // a member the target can't be made of (`<[number, string, string]>x` of `[number, string] | + // [number, string, string]`, holding the first): the assertion is false. The value is not a + // target, a run-time error, as a cast from an interface that does not hold the class is. (Its + // cast failed with nothing said: "failed statement".) + auto memberTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(members[index])); + if (targetTuple && memberTuple && tupleLacksField(memberTuple, targetTuple.getFields())) + { + auto message = builder.create( + location, getStringType(), + getStringAttr("Can't cast from " + to_print(members[index]) + " to " + to_print(type))); + builder.create(location, message); + if (!mlirGenRttiForType(location, message.getType())) + { + emitError(location, "Not supported type in throw"); + return mlir::failure(); + } + + // not reached; the branch still needs a value of the target type + return V(builder.create(location, type)); + } + auto memberValue = builder.create(location, members[index], value); return cast(location, type, memberValue, genContext); }; diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index d1bc30147..5d984ed26 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -20723,6 +20723,8 @@ class MLIRGenImpl ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, bool filterSpecialCases, const GenContext &genContext, bool errorAsWarning = false); mlir::Value absentFieldValue(mlir::Location location, mlir::Type fieldType, const GenContext &genContext); + bool tupleLacksField(mlir_ts::TupleType srcTupleType, ArrayRef fields); + mlir::Type unionTuplesCommonPrefixMember(mlir_ts::UnionType unionType, mlir::Value index); // TODO: needs to unified with selectFieldsValues ValueOrLogicalResult mapTupleToFields(mlir::Location location, SmallVector &values, mlir::Value value, mlir_ts::TupleType srcTupleType, diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index 558a2bb8a..e9bafbdc0 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -94,7 +94,54 @@ function sumOf(r: Rec) { return total; } +type Two = [number, string]; +type Three = [number, string, string]; + +function third(x: Two | Three) { + return (x)[2]; +} + +function secondOf(x: Two | Three) { + return x[1]; +} + +function tuples() { + let total = 0; + for (let i = 0; i < 3; i++) { + const x: Two | Three = [i, "a" + i, "b" + i]; + const t = x; + assert(t[2] == "b" + i); + const u = x as [number, string, string]; + assert(u[1] == "a" + i); + assert(x[1] == "a" + i); + assert(x[0] == i); + assert(third(x) == "b" + i); + assert(secondOf(x) == "a" + i); + total += x.length; + + const y: Two | Three = [i, "c" + i]; + assert(y[1] == "c" + i); + assert(secondOf(y) == "c" + i); + assert((y)[1] == "c" + i); + total += y.length; + + // a false assertion: the value is no Three + let caught = false; + try { + third(y); + } catch (e) { + caught = true; + } + + assert(caught); + } + + assert(total == 15); +} + function main() { + tuples(); + const r: Record = { a: 1, b: 2 }; assert(Object.keys(r).length == 2); assert(r["a"] == 1); From ba5292d50ebb6dd6436f3bbcc77fe05ca719cd6e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 14:51:10 +0000 Subject: [PATCH 03/11] WIP 215: Array members of a union of tuples read the member it holds, own copies a tuple's strings for its array, union-of-shapes tests read the union's tag (no leaked box) Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 15 +++ tslang/lib/TypeScript/MLIRGenCast.cpp | 7 +- tslang/lib/TypeScript/MLIRGenImpl.h | 109 ++++++++++++++++-- .../test/tester/tests/00tslang_issue_215.ts | 35 +++++- 4 files changed, 152 insertions(+), 14 deletions(-) diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 72b51fdad..71847765e 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -559,6 +559,21 @@ namespace mlirgen return V(fieldRead); } + // a member of Array reading a union of tuples (`x.slice(1)`): of the array of the member it holds + if (isArrayReadMember(name)) + { + auto arrayValue = mlirGenUnionOfTuplesAsArray(location, objectValue, unionType, genContext); + if (arrayValue.failed()) + { + return mlir::Value(); + } + + if (arrayValue.value) + { + return mlirGenPropertyAccessExpression(location, V(arrayValue), name, false, genContext); + } + } + // the same field in every member (or a method, dispatched where it is called): read as the first auto frontType = mth.getFirstNonNullUnionType(unionType); //auto casted = cast(location, frontType, objectValue, genContext); diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 2626f2c19..932b4c9d5 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -5935,7 +5935,8 @@ namespace mlirgen && !MLIRTypeHelper::isFirstFieldDiscriminatedUnion(unionType)) { auto members = unionType.getTypes(); - auto box = builder.create(location, getAnyType(), value); + // the union's own tag, as the box of it had (which nothing gave back: 48 bytes a cast, rc and own) + auto tag = builder.create(location, getStringType(), value); auto targetTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(type)); std::function castOf = [&](size_t index) -> ValueOrLogicalResult { auto asMember = [&]() -> ValueOrLogicalResult { @@ -5969,8 +5970,8 @@ namespace mlirgen return asMember(); } - auto holds = builder.create(location, getBooleanType(), box, - mlir::TypeAttr::get(members[index])); + auto holds = builder.create(location, getBooleanType(), tag, + mlir::TypeAttr::get(members[index])); auto ifOp = builder.create(location, mlir::TypeRange{type}, holds, true); builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 5d984ed26..f6a8ea58c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -16973,7 +16973,9 @@ class MLIRGenImpl // A tuple of unnamed elements as an array of them, of the union of their types: what TypeScript // gives `[1, "a"]` with no tuple wanted ((number | string)[]), so the members of Array are a // tuple's too (`[1, "a"].map(f)`). Null for a tuple with named fields: that is an object. - mlir::Value mlirGenTupleAsArray(mlir::Location location, mlir::Value tupleValue, const GenContext &genContext) + // `elementType`, when given, is the array's element type instead (of a union of tuples, all their elements'). + mlir::Value mlirGenTupleAsArray(mlir::Location location, mlir::Value tupleValue, const GenContext &genContext, + mlir::Type elementType = mlir::Type()) { if (auto refType = dyn_cast(tupleValue.getType())) { @@ -17007,14 +17009,16 @@ class MLIRGenImpl } // -mm=own: the array takes the tuple's elements. A tuple just made gives them up; one read from - // where it is kept (`t.map(f)` of a local `t`) keeps its own, and an element owning memory - // would have two owners + // where it is kept (`t.map(f)` of a local `t`) keeps its own: a string, a value, is copied for the + // array (as castTupleToTuple copies one, TSLANG 211), and another element owning memory would have + // two owners + auto copyStrings = false; if (compileOptions.memoryModel == MemoryModelOwn) { auto source = tupleValue; while (auto *def = source.getDefiningOp()) { - if (!mlir::isa(def) && !own_facts::isView(def)) + if (!mlir::isa(def) && !own_facts::isView(def)) { break; } @@ -17022,22 +17026,38 @@ class MLIRGenImpl source = def->getOperand(0); } - if (source.getDefiningOp() - && llvm::any_of(fieldTypes, [&](mlir::Type type) { return mth.ownsHeapMemory(location, type); })) + if (source.getDefiningOp()) { - emitError(location) << "-mm=own: an element of '" << to_print(tupleType) - << "' would have two owners as an element of an array; give it an array type"; - return mlir::Value(); + if (llvm::any_of(fieldTypes, [&](mlir::Type type) { + return mth.ownsHeapMemory(location, type) && !isa(type); + })) + { + emitError(location) << "-mm=own: an element of '" << to_print(tupleType) + << "' would have two owners as an element of an array; give it an array type"; + return mlir::Value(); + } + + copyStrings = true; } } - auto elementType = mth.getUnionTypeWithMerge(location, elementTypes); + if (!elementType) + { + elementType = mth.getUnionTypeWithMerge(location, elementTypes); + } auto fields = builder.create(location, fieldTypes, tupleValue); SmallVector elements; for (auto field : fields.getResults()) { mlir::Value element = field; + if (copyStrings && isa(element.getType())) + { + auto copy = builder.create(location, element.getType(), element); + copy->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + element = copy; + } + if (element.getType() != elementType) { auto result = cast(location, elementType, element, genContext); @@ -17058,6 +17078,75 @@ class MLIRGenImpl return builder.create(location, getArrayType(elementType), elements); } + // A union of tuples of unnamed elements as an array (`x.slice(1)` of `[number, string] | [number, string, string]`): + // the array of the member the value holds, told by the layout of its tag as castFromUnion tells them, of the union + // of all members' element types. Null when a member is no such tuple. (Read as the first member, a shorter one + // gained the first's last elements: `[0, "c"].join(",")` was "0,c,null".) + ValueOrLogicalResult mlirGenUnionOfTuplesAsArray(mlir::Location location, mlir::Value unionValue, + mlir_ts::UnionType unionType, const GenContext &genContext) + { + auto members = unionType.getTypes(); + SmallVector elementTypes; + for (auto member : members) + { + auto tupleType = dyn_cast(mth.convertConstTupleTypeToTupleType(member)); + if (!tupleType || tupleType.size() == 0 + || llvm::any_of(tupleType.getFields(), [](auto &field) { return !!field.id; })) + { + return mlir::Value(); + } + + for (auto &field : tupleType.getFields()) + { + elementTypes.push_back(mth.wideStorageType(field.type)); + } + } + + auto elementType = mth.getUnionTypeWithMerge(location, elementTypes); + auto arrayType = getArrayType(elementType); + // the union's own tag (not a box of it, which nothing gave back) + auto tag = builder.create(location, getStringType(), unionValue); + + std::function arrayOf = [&](size_t index) -> ValueOrLogicalResult { + auto asMember = [&]() -> ValueOrLogicalResult { + auto memberValue = builder.create(location, members[index], unionValue); + auto arrayValue = mlirGenTupleAsArray(location, memberValue, genContext, elementType); + if (!arrayValue) + { + return mlir::failure(); + } + + return arrayValue; + }; + + if (index + 1 == members.size()) + { + return asMember(); + } + + auto holds = builder.create(location, getBooleanType(), tag, + mlir::TypeAttr::get(members[index])); + auto ifOp = builder.create(location, mlir::TypeRange{arrayType}, holds, true); + + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto thenValue = asMember(); + EXIT_IF_FAILED_OR_NO_VALUE(thenValue) + builder.create(location, mlir::ValueRange{V(thenValue)}); + + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + auto elseValue = arrayOf(index + 1); + EXIT_IF_FAILED_OR_NO_VALUE(elseValue) + builder.create(location, mlir::ValueRange{V(elseValue)}); + + builder.setInsertionPointAfter(ifOp); + // the array either branch made, given up to whoever reads it, as a call's new result is + ifOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + return V(ifOp.getResults().front()); + }; + + return arrayOf(0); + } + ValueOrLogicalResult createFixedSizeArrayFromArrayLiteral(mlir::Location location, ArrayRef values, struct ArrayInfo arrayInfo, const GenContext &genContext) { SmallVector arrayValues; diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index e9bafbdc0..c483e1df1 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -1,6 +1,7 @@ // TSLANG 215: `Record` is `{ [key: string]: T }`, a dictionary of T (it was an object with no fields: the // literal given to it lost its fields, and Object.keys gave none), both as the built-in Record and as a mapped type -// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them; under -mm=own `slice` of one. +// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them, indexed, and read as an array (`slice`, +// `forEach`: of the member it holds; under -mm=own its strings copied). // The tests compile without the default library: its ObjectDictionary, as the compiler finds it by name. @dictionary class ObjectDictionary { @@ -105,6 +106,37 @@ function secondOf(x: Two | Three) { return x[1]; } +// a member of Array on a union of tuples is of the array of the member it holds (read as the first, the shorter one +// had three elements); under -mm=own a tuple's strings are copied for that array +function count(x: Two | Three) { + let n = 0; + x.forEach((e) => { n++; }); + return n; +} + +function mapped(x: Two | Three) { + let n = 0; + for (const v of x.map((e) => 1)) { + n += v; + } + + return n; +} + +function arrays() { + let total = 0; + for (let i = 0; i < 3; i++) { + const x: Two | Three = [i, "a" + i, "b" + i]; + const y: Two | Three = [i, "c" + i]; + total += count(x) + count(y); + total += mapped(x) + mapped(y); + const t: Two = [i, "d" + i]; + t.forEach((e) => { total++; }); + } + + assert(total == 36); +} + function tuples() { let total = 0; for (let i = 0; i < 3; i++) { @@ -141,6 +173,7 @@ function tuples() { function main() { tuples(); + arrays(); const r: Record = { a: 1, b: 2 }; assert(Object.keys(r).length == 2); From 4e46278b71860b4da120bf0094b1cfa6b2042a28 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 14:51:28 +0000 Subject: [PATCH 04/11] WIP 215: TSLANG_ISSUES 215 Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index b5da9eda2..8832fc11f 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4006,3 +4006,37 @@ Not yet: as a value; design questions without a ruling: overloads of a declared function (136) and class constructor (140). Tests `00tslang_issue_214.ts` (all models). + +215. Leftovers of 214 (2026-11-27). Fixed: +- `Record` was an object with no fields in every model ("mapped type is empty for constrain: string"): the + literal given to it lost its fields, `Object.keys` gave none and `r["a"]` read nothing (131). It is `{ [key: string]: + T }`, the dictionary of T a string index signature is, both as the built-in Record (no default library) and as the + mapped type `{ [P in K]: T }` of K = string (the default library's Record). Without the dictionary class, as before. +- A union of tuples cast to one of them (`<[number, string, string]>x` of `[number, string] | [number, string, + string]`) failed with nothing said ("failed statement"): each member is tested for and cast, and the shorter one + could not be made the longer - its cast read past its end. The member the value holds is cast; one lacking an + element of the target throws "Can't cast from [number, string] to [number, string, string]" there, as a cast from + an interface that does not hold the class throws (TypeScript reads the element as undefined). A tuple cast to one + with more elements (not of a union) is a compile error that says so (tsc refuses it too). +- `x[1]` of such a union, "access expression is not applicable": an element at a constant index every member has, + after the same element types, is read where the first member has it. +- A member of Array of a union of tuples (`x.slice(1)`, `x.join(",")`, `forEach`, `map`) read the value as the first + member, in every model: a `[0, "c"]` held by `[number, string] | [number, string, string]` joined "0,c,null". It is + the array of the member the value holds, of the union of all members' element types. +- Under -mm=own a tuple read from a variable made an array (`t.slice(1)`, `t.forEach(f)` of `t: [number, string]`) + was refused ("an element ... would have two owners as an element of an array"): its strings are copied for the array, + as a tuple cast to another copies them (211). Another element owning memory stays refused. +- A union of object shapes or tuples cast to one of its members boxed the union in an `any` to read its tag, and + nothing gave the box back: 48 bytes a cast under rc and -mm=own. The union's own tag is read. + +Not yet: +- Under -mm=rc an array made for a call and given as `this` to a method (`([i, s] as (number | string)[]).slice(1)`, + `t.slice(1)` of a tuple) is never given back: about 100 bytes a call (before this batch). +- Under -mm=own `a.join(",")` of a `(number | string)[]` leaks about 120 bytes a call (default library; before this + batch). +- Still from 214: 128 under own (a capture by value for value types), own `Constructor` of `...args: any[]`; from + 213: 56, 153, 159 under own; 131 (`Object.keys` of `object`, `Object.assign`, `defineProperty`, `create`), 108, 191's + callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads + of a declared function (136) and of a `declare class` constructor (140). + +Tests `00tslang_issue_215.ts` (all models). From eb7f40d4fde2bf65c4c69107c279100288129209 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 15:01:08 +0000 Subject: [PATCH 05/11] WIP 215: spread of a union of tuples, the run-time throw only for tuples of elements, TSLANG_ISSUES measurements Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 22 +++++++++++++------ tslang/lib/TypeScript/MLIRGenCast.cpp | 5 +++++ tslang/lib/TypeScript/MLIRGenImpl.h | 22 ++++++++++++++++++- .../test/tester/tests/00tslang_issue_215.ts | 12 +++++++++- 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 8832fc11f..502321e9b 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4016,24 +4016,32 @@ Tests `00tslang_issue_214.ts` (all models). string]`) failed with nothing said ("failed statement"): each member is tested for and cast, and the shorter one could not be made the longer - its cast read past its end. The member the value holds is cast; one lacking an element of the target throws "Can't cast from [number, string] to [number, string, string]" there, as a cast from - an interface that does not hold the class throws (TypeScript reads the element as undefined). A tuple cast to one - with more elements (not of a union) is a compile error that says so (tsc refuses it too). + an interface that does not hold the class throws (TypeScript reads the element as undefined). Only for tuples of + elements: a union of object shapes cast to a shape one member lacks a field of stays the compile error it was. A + tuple cast to one with more elements (not of a union) is a compile error that says so (tsc refuses it too). - `x[1]` of such a union, "access expression is not applicable": an element at a constant index every member has, after the same element types, is read where the first member has it. - A member of Array of a union of tuples (`x.slice(1)`, `x.join(",")`, `forEach`, `map`) read the value as the first member, in every model: a `[0, "c"]` held by `[number, string] | [number, string, string]` joined "0,c,null". It is - the array of the member the value holds, of the union of all members' element types. + the array of the member the value holds, of the union of all members' element types. So is `[...x]` (it was "can't + estimate element of array"). - Under -mm=own a tuple read from a variable made an array (`t.slice(1)`, `t.forEach(f)` of `t: [number, string]`) was refused ("an element ... would have two owners as an element of an array"): its strings are copied for the array, as a tuple cast to another copies them (211). Another element owning memory stays refused. - A union of object shapes or tuples cast to one of its members boxed the union in an `any` to read its tag, and - nothing gave the box back: 48 bytes a cast under rc and -mm=own. The union's own tag is read. + nothing gave the box back: about 40 bytes a cast under rc and -mm=own. The union's own tag is read. Not yet: - Under -mm=rc an array made for a call and given as `this` to a method (`([i, s] as (number | string)[]).slice(1)`, - `t.slice(1)` of a tuple) is never given back: about 100 bytes a call (before this batch). -- Under -mm=own `a.join(",")` of a `(number | string)[]` leaks about 120 bytes a call (default library; before this - batch). + `t.slice(1)` of a tuple, `[...x]` of a union of tuples) is never given back: about 100 bytes a call (before this + batch, with the triage compiler of c2a88259d too). +- Under -mm=own `a.join(",")` of a `(number | string)[]` leaks about 120 bytes a call (default library; the same with + the compiler of c2a88259d). +- A union of tuples: `for (const e of x)` and `x[i]` of a run-time index are "access expression is not applicable", + and `x[1] = v` is refused ("can't assign to a field of a value ... that is not held anywhere"). +- Under -mm=own a dictionary written in a generic loop (`out[key(it)] = (out[k] ?? 0) + 1` for `it` of `items: T[]`): + "'it' borrows an element but is used here after it may be released", of `Record` and of `{ [k: + string]: number }` alike. - Still from 214: 128 under own (a capture by value for value types), own `Constructor` of `...args: any[]`; from 213: 56, 153, 159 under own; 131 (`Object.keys` of `object`, `Object.assign`, `defineProperty`, `create`), 108, 191's callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 932b4c9d5..5a61e3bf7 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -5937,7 +5937,12 @@ namespace mlirgen auto members = unionType.getTypes(); // the union's own tag, as the box of it had (which nothing gave back: 48 bytes a cast, rc and own) auto tag = builder.create(location, getStringType(), value); + // (a tuple of elements only: a shape lacking a field stays the compile error mapTupleToFields gives) auto targetTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(type)); + if (targetTuple && llvm::any_of(targetTuple.getFields(), [](auto &field) { return !!field.id; })) + { + targetTuple = mlir_ts::TupleType(); + } std::function castOf = [&](size_t index) -> ValueOrLogicalResult { auto asMember = [&]() -> ValueOrLogicalResult { // a member the target can't be made of (`<[number, string, string]>x` of `[number, string] | diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index f6a8ea58c..52b8b9941 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -16608,7 +16608,27 @@ class MLIRGenImpl } return mlir::success(); - } + } + + // `[...x]` of a union of tuples: the array of the member it holds (mlirGenUnionOfTuplesAsArray). Taken as + // array-like, its elements were read at a run-time index, which a union of tuples has not got + if (auto unionType = dyn_cast(type)) + { + auto arrayValue = mlirGenUnionOfTuplesAsArray(location, itemValue, unionType, genContext); + if (arrayValue.failed()) + { + return mlir::failure(); + } + + if (arrayValue.value) + { + arrayInfo.isConst = false; + values.push_back({V(arrayValue), true, true}); + accumulateArrayItemType(location, mlir::cast(arrayValue.value.getType()).getElementType(), + arrayInfo); + return mlir::success(); + } + } // ArrayLike, do not put it before Tuple & Const Tuple, otherwise [xxx] will return wrong type if (auto indexAccessType = evaluateElementAccess(location, itemValue, false, genContext)) diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index c483e1df1..641d36867 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -123,6 +123,14 @@ function mapped(x: Two | Three) { return n; } +function spreadLength(x: Two | Three) { + return [...x].length; +} + +function lengthOf(x: Two | Three) { + return x.length; +} + function arrays() { let total = 0; for (let i = 0; i < 3; i++) { @@ -130,11 +138,13 @@ function arrays() { const y: Two | Three = [i, "c" + i]; total += count(x) + count(y); total += mapped(x) + mapped(y); + total += spreadLength(x) + spreadLength(y); + total += lengthOf(x) + lengthOf(y); const t: Two = [i, "d" + i]; t.forEach((e) => { total++; }); } - assert(total == 36); + assert(total == 66); } function tuples() { From de6a741b0d98daaa2e69c94ddd4ecf3af9ab864f Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 15:17:16 +0000 Subject: [PATCH 06/11] WIP 215: rc gives back a new array a method is called on, own a spread literal given to a call, a union of tuples iterated and read at a run-time index Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 28 +++-- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 27 +++++ tslang/lib/TypeScript/MLIRGenImpl.h | 107 +++++++++++++++++- tslang/lib/TypeScript/MLIRGenStatements.cpp | 16 +++ .../TypeScript/OwnedReturnConsumptionPass.cpp | 103 +++++++++++++++++ tslang/test/tester/CMakeLists.txt | 5 +- .../test/tester/tests/00tslang_issue_215.ts | 24 +++- .../tester/tests/own_tuple_as_array_error.ts | 4 +- 8 files changed, 296 insertions(+), 18 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 502321e9b..990be5181 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4030,18 +4030,28 @@ Tests `00tslang_issue_214.ts` (all models). as a tuple cast to another copies them (211). Another element owning memory stays refused. - A union of object shapes or tuples cast to one of its members boxed the union in an `any` to read its tag, and nothing gave the box back: about 40 bytes a cast under rc and -mm=own. The union's own tag is read. +- A union of tuples iterated (`for (const e of x)`) or read at a run-time index (`x[i]`), "access expression is not + applicable": the elements of the member it holds, and the element of that member (each member tested for, as a + cast is). `x[1] = v` stays refused, and says why: the element is read out of the member the union holds, a copy. +- Under -mm=rc an array made for a call and given as `this` to a method (`([i, s] as (number | string)[]).slice(1)`, + `t.slice(1)` of a tuple, `[...x]` of a union of tuples) was never given back: about 100 bytes a call (with the + compiler of c2a88259d too). Born uncounted, it gets the reference a new string has (markFreshBlockOwned) and is given + back where nothing takes it. +- Under -mm=own a spread literal given to a call (`cnt(...xs)`, the default library's `join`: `"".concat(...parts)`) + was never given back: about 100 bytes a call (with the compiler of c2a88259d too). It is given back as a literal + given to a call is (ownNewArrayArguments), with copies of the text pushed into it; one holding an object read from + elsewhere stays as it was. Not yet: -- Under -mm=rc an array made for a call and given as `this` to a method (`([i, s] as (number | string)[]).slice(1)`, - `t.slice(1)` of a tuple, `[...x]` of a union of tuples) is never given back: about 100 bytes a call (before this - batch, with the triage compiler of c2a88259d too). -- Under -mm=own `a.join(",")` of a `(number | string)[]` leaks about 120 bytes a call (default library; the same with - the compiler of c2a88259d). -- A union of tuples: `for (const e of x)` and `x[i]` of a run-time index are "access expression is not applicable", - and `x[1] = v` is refused ("can't assign to a field of a value ... that is not held anywhere"). -- Under -mm=own a dictionary written in a generic loop (`out[key(it)] = (out[k] ?? 0) + 1` for `it` of `items: T[]`): +- Under -mm=own the result of a default-library string function used as a temporary (`"".concat(s, "e").length`, + `s.toUpperCase().length`) is never given back: about 32 bytes a call (with the compiler of c2a88259d too). The + library declares `__String` `@owned`, which rc trusts and own does not (USER DECISION 2026-11-18: JsonValue.get + lends); trusting it under own for string results is a decision to make. +- Under -mm=own a dictionary written in a loop over an array it is not (`for (const it of items) out[it] = 1`): "'it' borrows an element but is used here after it may be released", of `Record` and of `{ [k: - string]: number }` alike. + string]: number }` alike. The dictionary's `set` is known only to drop strings held anywhere (its drop facts are + `[-1, string]`), so any string read out of an array is taken for freed by it; facts naming what is under `this` would + tell `items` apart. - Still from 214: 128 under own (a capture by value for value types), own `Constructor` of `...args: any[]`; from 213: 56, 153, 159 under own; 131 (`Object.keys` of `object`, `Object.assign`, `defineProperty`, `create`), 108, 191's callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 71847765e..ffe64a34e 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -719,6 +719,27 @@ namespace mlirgen LLVM_DEBUG(llvm::dbgs() << "!! this type of function is : " << thisTypeFromFunc << "\n";); + // -mm=rc: a new array a method is called on (`[a, b].slice(1)`, `t.slice(1)` of a tuple made an array) is born + // uncounted, and nothing gave it back: about 100 bytes a call. It gets the standing a new string has + // (markFreshBlockOwned): a reference of its own, marked so, given back where nothing takes it (§9.30) + if (compileOptions.isRefCounted() && isa(thisValue.getType())) + { + auto source = thisValue; + while (auto castOp = source.getDefiningOp()) + { + source = castOp.getIn(); + } + + auto *definingOp = source.getDefiningOp(); + auto isNewArray = isa_and_nonnull(definingOp) + || (isa_and_nonnull(definingOp) && definingOp->hasAttr(SPREAD_ARRAY_LITERAL_ATTR_NAME)); + if (isNewArray && !definingOp->hasAttr(OWNED_RESULT_ATTR_NAME) && isa(source.getType())) + { + builder.create(location, source); + definingOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + } + } + // a key of an `any` is read at run time: a function of the same name found in some namespace is no member // of it unless it takes an `any` (`foo.get = class {}` with `foo: any` found the library's generic // `Reflect.get(target: T, ...)`, whose `T` takes anything, and assigned to it) @@ -1869,6 +1890,12 @@ namespace mlirgen expression = builder.create(location, firstTuple, expression); arrayType = firstTuple; } + // `x[i]` of a run-time index: the element of the member the value holds (a value, as above: not a place + // to assign to) + else if (auto element = mlirGenUnionOfTuplesElementAt(location, expression, unionType, argumentExpression, genContext)) + { + return *element; + } } if (isa(arrayType)) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 52b8b9941..09a338df6 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -10418,6 +10418,15 @@ class MLIRGenImpl // an enum's member is its value by now (`E.a = 1` assigns to `0`) error << "the constant " << to_print(type) << " (a literal, or an enum's member): it is a value, not a variable"; } + // `x[1] = v` of a union of tuples: the element is read out of the member the value holds (TSLANG 215) + else if (auto extractOp = target.getDefiningOp(); + (extractOp && extractOp->getOperand(0).getDefiningOp()) + || (target.getDefiningOp() && target.getDefiningOp()->getNumOperands() == 1 + && target.getDefiningOp()->getOperand(0).getDefiningOp())) + { + error << "an element or a field of a union's member: it is read out of the member the union holds, a copy; give " + "the variable that member's type to assign to it"; + } else if (target.getDefiningOp()) { error << "a field of a value of type '" << to_print(type) @@ -17159,12 +17168,106 @@ class MLIRGenImpl builder.create(location, mlir::ValueRange{V(elseValue)}); builder.setInsertionPointAfter(ifOp); - // the array either branch made, given up to whoever reads it, as a call's new result is + return V(ifOp.getResults().front()); + }; + + auto result = arrayOf(0); + EXIT_IF_FAILED_OR_NO_VALUE(result) + + // the array a branch made, given up to whoever reads it, as a call's new result is; under rc, born uncounted, it + // takes the reference that stands for that (markFreshBlockOwned). (The `ts.If` of the first member: those of the + // others are in its branches.) + if (auto ifOp = V(result).getDefiningOp()) + { ifOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + if (compileOptions.isRefCounted()) + { + builder.create(location, V(result)); + } + } + + return result; + } + + // `x[i]` of a union of tuples of unnamed elements and an index known at run time: the element of the member the + // value holds (mlirGenTupleElementAtIndex of it), told by the union's tag, of the union of all members' element + // types. A value, not a place: `x[i] = v` stays refused. No value when it doesn't apply (a member of another kind, + // a constant index). + std::optional mlirGenUnionOfTuplesElementAt(mlir::Location location, mlir::Value unionValue, + mlir_ts::UnionType unionType, mlir::Value index, + const GenContext &genContext) + { + if (index.getDefiningOp() + || !isa(index.getType())) + { + return std::nullopt; + } + + auto members = unionType.getTypes(); + SmallVector elementTypes; + for (auto member : members) + { + auto tupleType = dyn_cast(mth.convertConstTupleTypeToTupleType(member)); + if (!tupleType || tupleType.size() == 0 + || llvm::any_of(tupleType.getFields(), [](auto &field) { return !!field.id; })) + { + return std::nullopt; + } + + for (auto &field : tupleType.getFields()) + { + elementTypes.push_back(mth.wideStorageType(field.type)); + } + } + + auto resultType = mth.getUnionTypeWithMerge(location, elementTypes); + auto tag = builder.create(location, getStringType(), unionValue); + + std::function elementOf = [&](size_t memberIndex) -> ValueOrLogicalResult { + auto asMember = [&]() -> ValueOrLogicalResult { + auto tupleType = mlir::cast(mth.convertConstTupleTypeToTupleType(members[memberIndex])); + auto memberValue = builder.create(location, tupleType, unionValue); + auto element = mlirGenTupleElementAtIndex(location, memberValue, index, tupleType, genContext); + if (!element) + { + return mlir::failure(); + } + + auto elementValue = *element; + EXIT_IF_FAILED_OR_NO_VALUE(elementValue) + auto value = V(elementValue); + if (value.getType() == resultType) + { + return value; + } + + return cast(location, resultType, value, genContext); + }; + + if (memberIndex + 1 == members.size()) + { + return asMember(); + } + + auto holds = builder.create(location, getBooleanType(), tag, + mlir::TypeAttr::get(members[memberIndex])); + auto ifOp = builder.create(location, mlir::TypeRange{resultType}, holds, true); + + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto thenValue = asMember(); + EXIT_IF_FAILED_OR_NO_VALUE(thenValue) + builder.create(location, mlir::ValueRange{V(thenValue)}); + + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + auto elseValue = elementOf(memberIndex + 1); + EXIT_IF_FAILED_OR_NO_VALUE(elseValue) + builder.create(location, mlir::ValueRange{V(elseValue)}); + + builder.setInsertionPointAfter(ifOp); return V(ifOp.getResults().front()); }; - return arrayOf(0); + return elementOf(0); } ValueOrLogicalResult createFixedSizeArrayFromArrayLiteral(mlir::Location location, ArrayRef values, struct ArrayInfo arrayInfo, const GenContext &genContext) diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 57a809899..4fbb8f111 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -2254,6 +2254,22 @@ namespace mlirgen } } + // a union of tuples (`for (const e of x)` of `[number, string] | [number, string, string]`): the elements of the + // member it holds, as an array (it was "access expression is not applicable") + if (auto unionType = dyn_cast(exprValue.getType())) + { + auto arrayValue = mlirGenUnionOfTuplesAsArray(location, exprValue, unionType, genContext); + if (arrayValue.failed()) + { + return mlir::failure(); + } + + if (arrayValue.value) + { + exprValue = V(arrayValue); + } + } + auto skip = isa(exprValue.getType()) || isa(exprValue.getType()); // we need to ignore SYMBOL_ITERATOR for array to use simplier method and do not cause the stackoverflow diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 2b1edfca1..ef663b702 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -682,6 +682,94 @@ class OwnedReturnConsumptionPass } } + // -mm=own: may a spread literal's array (read out of its slot, `loadOp`) own what was pushed into the slot? Each + // item owning memory must be a new value moved in, or text, which is copied for it as copyBorrowedTextElements copies + // a literal's (the retain taken of it before the push goes). Anything else - an object read from elsewhere - and + // nothing is changed: the array borrows it, and stays as it was (never given back). The slot is the literal's + // alone: pushes and reads of it, nothing stored into it. + static bool ownSpreadSlotPushes(MLIRTypeHelper &mth, mlir_ts::LoadOp loadOp) + { + auto slot = loadOp.getReference(); + if (!slot.getDefiningOp()) + { + return false; + } + + auto elementType = mlir::cast(loadOp.getType()).getElementType(); + auto ownsElements = mth.ownsHeapMemory(loadOp->getLoc(), elementType); + + llvm::SmallVector pushes; + for (auto *user : slot.getUsers()) + { + if (auto pushOp = mlir::dyn_cast(user)) + { + pushes.push_back(pushOp); + continue; + } + + if (!mlir::isa(user)) + { + return false; + } + } + + if (!ownsElements) + { + return true; + } + + auto movedIn = [](mlir::Value item) { + auto *itemOp = item.getDefiningOp(); + return itemOp && itemOp->hasAttr(OWNED_RESULT_ATTR_NAME) && itemOp->hasAttr(OWNED_RESULT_CONSUMED_ATTR_NAME); + }; + + for (auto pushOp : pushes) + { + for (auto item : pushOp.getItems()) + { + if (mth.ownsHeapMemory(pushOp->getLoc(), item.getType()) && !movedIn(item) && !isBorrowedText(item)) + { + return false; + } + } + } + + for (auto pushOp : pushes) + { + for (auto &operand : pushOp->getOpOperands()) + { + auto item = operand.get(); + if (operand.getOperandNumber() == 0 || !mth.ownsHeapMemory(pushOp->getLoc(), item.getType()) || movedIn(item)) + { + continue; + } + + // the retain taken of it for the push: the last one before the push, in its block + mlir::Operation *retain = nullptr; + for (auto *user : item.getUsers()) + { + if (mlir::isa(user) && user->getBlock() == pushOp->getBlock() && user->isBeforeInBlock(pushOp) && + (!retain || retain->isBeforeInBlock(user))) + { + retain = user; + } + } + + mlir::OpBuilder builder(pushOp); + auto copy = builder.create(pushOp->getLoc(), item.getType(), item); + copy->setAttr(OWNED_RESULT_ATTR_NAME, mlir::UnitAttr::get(pushOp->getContext())); + copy->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(pushOp->getContext())); + operand.set(copy); + if (retain) + { + retain->erase(); + } + } + } + + return true; + } + // The array a conversion makes for one call (`f(a)` of an `int[]` given as a `number[]`, an array given as // an Iterable): a `ts.NewArray` whose elements are written one by one, then given to the call - // its other uses are the element references of that loop @@ -833,6 +921,21 @@ class OwnedReturnConsumptionPass auto *definingOp = argument.getDefiningOp(); + // a spread literal's array (`cnt(...xs)`, `"".concat(...parts)` of the default library's join), read out of + // the slot it was filled in: the same, when what was pushed into it can be its own (spreadSlotPushes) + if (auto loadOp = mlir::dyn_cast_or_null(definingOp); + loadOp && loadOp->hasAttr(SPREAD_ARRAY_LITERAL_ATTR_NAME) && !loadOp->hasAttr(OWNED_RESULT_ATTR_NAME) && + mlir::isa(argument.getType()) && seen.insert(argument).second && + arrayMadeFor(argument, op, true)) + { + if (ownSpreadSlotPushes(mth, loadOp)) + { + loadOp->setAttr(OWNED_RESULT_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + + continue; + } + // `f([])`: the empty constant array cast to an array - a copy made on the heap there - is the new empty // array it is (ts.NewEmptyArray), which the inference moves into a callee that keeps it (`new // Order(-1, [])`, the constructor storing it) and gives back after one that does not (`ln([])`, which diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 0d8d634e9..843c5b492 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2405,10 +2405,11 @@ foreach(union_method_mm gc rc none own) tslang_add_test(NAME test-jit-00-union-method-dispatch-${union_method_mm} COMMAND test-runner -jit -mm=${union_method_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00union_method_dispatch.ts") endforeach() tslang_add_test(NAME test-compile-00-union-method-dispatch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00union_method_dispatch.ts") -# -mm=own: a tuple kept in a local used as an array would give its owned elements a second owner +# -mm=own: a tuple kept in a local used as an array would give its owned elements a second owner (its strings are +# copied, TSLANG 215; an array element is not) add_test(NAME test-compile-own-tuple-as-array-error COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/own_tuple_as_array_error.ts") -set_tests_properties(test-compile-own-tuple-as-array-error PROPERTIES PASS_REGULAR_EXPRESSION "an element of '\\[number, string\\]' would have two owners as an element of an array" +set_tests_properties(test-compile-own-tuple-as-array-error PROPERTIES PASS_REGULAR_EXPRESSION "an element of '\\[number, number\\[\\]\\]' would have two owners as an element of an array" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # Mixins (a generic function given a class) under every memory model foreach(mixin_mm gc rc none own) diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index 641d36867..f052520df 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -1,7 +1,8 @@ // TSLANG 215: `Record` is `{ [key: string]: T }`, a dictionary of T (it was an object with no fields: the // literal given to it lost its fields, and Object.keys gave none), both as the built-in Record and as a mapped type -// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them, indexed, and read as an array (`slice`, -// `forEach`: of the member it holds; under -mm=own its strings copied). +// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them, indexed (at a constant or a run-time +// index), iterated, and read as an array (`slice`, `forEach`, `[...x]`: of the member it holds; under -mm=own its +// strings copied). // The tests compile without the default library: its ObjectDictionary, as the compiler finds it by name. @dictionary class ObjectDictionary { @@ -131,6 +132,19 @@ function lengthOf(x: Two | Three) { return x.length; } +function ofCount(x: Two | Three) { + let n = 0; + for (const e of x) { + n++; + } + + return n; +} + +function at(x: Two | Three, i: number) { + return x[i]; +} + function arrays() { let total = 0; for (let i = 0; i < 3; i++) { @@ -140,11 +154,15 @@ function arrays() { total += mapped(x) + mapped(y); total += spreadLength(x) + spreadLength(y); total += lengthOf(x) + lengthOf(y); + total += ofCount(x) + ofCount(y); + assert(at(x, 2) == "b" + i); + assert(at(y, 1) == "c" + i); + assert(at(x, 0) == i); const t: Two = [i, "d" + i]; t.forEach((e) => { total++; }); } - assert(total == 66); + assert(total == 81); } function tuples() { diff --git a/tslang/test/tester/tests/own_tuple_as_array_error.ts b/tslang/test/tester/tests/own_tuple_as_array_error.ts index 52c4bedf4..6f3cfc957 100644 --- a/tslang/test/tester/tests/own_tuple_as_array_error.ts +++ b/tslang/test/tester/tests/own_tuple_as_array_error.ts @@ -1,6 +1,6 @@ // -mm=own: a tuple kept in a local, used as an array (`t.map(f)`), would give each element it owns -// a second owner, the array's +// a second owner, the array's. A string is copied for the array (TSLANG 215); an array element is not function main() { - let t: [number, string] = [3, "b" + 1]; + let t: [number, number[]] = [3, [1, 2]]; print(t.map(x => 1).length); } From ec77071280cbea70b0ddeed00df2df6c114df9c5 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 15:34:44 +0000 Subject: [PATCH 07/11] WIP 215: -mm=own reads @owned as rc does (a declaration that lends its result excepted) Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 13 ++++-- tslang/include/TypeScript/Defines.h | 6 ++- .../TypeScript/OwnedReturnConsumptionPass.cpp | 29 +++++++----- tslang/test/tester/CMakeLists.txt | 22 +++++---- tslang/test/tester/owned-declarations.cmake | 46 ++++++++++++++----- .../owned-declarations/owned_declarations.ts | 22 +++++++-- 6 files changed, 95 insertions(+), 43 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 990be5181..9b478e9a9 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4041,12 +4041,15 @@ Tests `00tslang_issue_214.ts` (all models). was never given back: about 100 bytes a call (with the compiler of c2a88259d too). It is given back as a literal given to a call is (ownNewArrayArguments), with copies of the text pushed into it; one holding an object read from elsewhere stays as it was. +- Under -mm=own no result of a default-library function was ever given back, held in a local or not + (`s.toUpperCase()` 16 bytes a call, `s.split("b")` 107, `(1.5).toFixed(2)` 64, `JSON.parse(t)` about 800; with the + compiler of c2a88259d too; rc freed them all): own did not read `@owned`, the declaration's word that its result is + the caller's (USER DECISION 2026-11-27, reversing 2026-11-18's rc only: what rc reads, own reads the same way, the two + models being alike). It does now, except where a declaration says it lends its result (`@lends`, or a result type + `this`: `JsonValue.get`, `ArrayBuffer.__bytes`), which own goes by - under rc that result is the caller's all the same. + Each of those probes is flat under own. Not yet: -- Under -mm=own the result of a default-library string function used as a temporary (`"".concat(s, "e").length`, - `s.toUpperCase().length`) is never given back: about 32 bytes a call (with the compiler of c2a88259d too). The - library declares `__String` `@owned`, which rc trusts and own does not (USER DECISION 2026-11-18: JsonValue.get - lends); trusting it under own for string results is a decision to make. - Under -mm=own a dictionary written in a loop over an array it is not (`for (const it of items) out[it] = 1`): "'it' borrows an element but is used here after it may be released", of `Record` and of `{ [k: string]: number }` alike. The dictionary's `set` is known only to drop strings held anywhere (its drop facts are @@ -4057,4 +4060,4 @@ Not yet: callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads of a declared function (136) and of a `declare class` constructor (140). -Tests `00tslang_issue_215.ts` (all models). +Tests `00tslang_issue_215.ts` (all models), `test-{rc,own}-owned-declarations` (the IR of `@owned` and `@lends` calls). diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 886ac6aa6..dbd8e762c 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -510,8 +510,10 @@ // it returns a reference its caller owns (§9.24), as an imported `export`ed function does. An // unmarked declaration may be C, or TypeScript that hands back a pointer into a buffer // (`convertNumber`): nothing can be said of its result, and its callers keep retaining. Said on a -// function with a body it is ignored - a body is read, not trusted. Only rc reads it: -mm=own goes by -// its declared facts (`@lends`, `@record`). A unit attribute on the FuncOp. +// function with a body it is ignored - a body is read, not trusted. rc and own read it alike (own: its +// result is the caller's to own, as a call of a function here that returns a new value is), except +// where a declaration says it lends its result (`@lends`, or a result type `this`): that is own's to +// go by. A unit attribute on the FuncOp. // An array literal with a spread of run-time length (`[...xs]`, and the rest argument `f(...xs)` packs) // is filled through a slot of its own, and what MLIRGen hands on is a read of that slot: this unit // attribute on the `ts.Load` says it is the new array, born uncounted as a `ts.CreateArray` is. Under rc diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index ef663b702..f59cb2bb4 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -98,7 +98,8 @@ class OwnedReturnConsumptionPass } auto name = funcOp.getName(); - auto classified = functionReturnsOwned(mth, funcOp, compileOptions.isRefCounted()); + auto classified = functionReturnsOwned(mth, funcOp, compileOptions.isRefCounted(), + compileOptions.memoryModel == MemoryModelOwn); if (classified) { returnsOwned.insert(name); @@ -201,8 +202,9 @@ class OwnedReturnConsumptionPass // The same for the functions a class given to a construct signature is called through (`new c(i)` of `c: { new // (x: number): Pt }`): MLIRGen makes every one (generateSynthMethodToCallNewCtor) - an object literal can't - // have a construct signature - and each returns the object it makes. Under -mm=own, where library - // declarations are never classified, the call's result was a borrow, and returning it "a second reference". + // have a construct signature - and each returns the object it makes. Under -mm=own, where a library + // declaration that lends its result is never classified, the call's result was a borrow, and returning it + // "a second reference". auto everyNewCtorReturnsOwned = true; module.walk([&](mlir_ts::FuncOp funcOp) { if (funcOp.getName().contains(NEW_CTOR_METHOD_NAME) && !returnsOwned.contains(funcOp.getName())) @@ -5148,16 +5150,21 @@ class OwnedReturnConsumptionPass // and moving it into the object is what lets this say yes without asking which model the // other module was built under - a question a static link cannot answer, because the import // is resolved by re-parsing source before any artifact of it exists. - static bool importedFunctionReturnsOwned(MLIRTypeHelper &mth, mlir_ts::FuncOp funcOp, bool refCounted) + static bool importedFunctionReturnsOwned(MLIRTypeHelper &mth, mlir_ts::FuncOp funcOp, bool refCounted, bool own) { - // ...or, under rc, a declaration that says it is one: `@owned` + // ...or, under rc and own, a declaration that says it is one: `@owned` // (DECLARED_OWNED_RESULT_ATTR_NAME), which the default library's lib.d.ts says of what lib.ts // defines. Without it every library declaration was unclassified, so closed world never held // in a program that has the library - every call through a function value, and every direct - // library call, kept its result's +1 for good. -mm=own goes by its own declared facts instead - // (`@lends`: `JsonValue.get` lends what it returns, which counted as fresh here was released - // under the borrow), and gc and none have no count to give back. - auto declaredOwned = refCounted && funcOp->hasAttr(DECLARED_OWNED_RESULT_ATTR_NAME); + // library call, kept its result's +1 for good; under own, where lib.ts is compiled under own + // too, every library result was a borrow no one gave back, held in a local or not + // (`s.toUpperCase()`, `JSON.parse(t)`). A declaration that says it lends its result + // (`@lends`, or a result type `this`: `JsonValue.get`, `ArrayBuffer.__bytes`) is one own + // must not give back - it says more than `@owned` of the class it is in. Under rc it is the + // caller's all the same: rc's body retains what it lends for its caller. gc and none have no + // count to give back. + auto declaredOwned = funcOp->hasAttr(DECLARED_OWNED_RESULT_ATTR_NAME) && + (refCounted || (own && !funcOp->hasAttr(OWN_DECLARED_LENDS_ATTR_NAME))); if (!funcOp->hasAttr("export") && !declaredOwned) { return false; @@ -5176,11 +5183,11 @@ class OwnedReturnConsumptionPass // body, a return whose retain is not in the same block, a return with no retain at all. A // false "no" costs a leak; a false "yes" frees a value the callee never retained. - static bool functionReturnsOwned(MLIRTypeHelper &mth, mlir_ts::FuncOp funcOp, bool refCounted) + static bool functionReturnsOwned(MLIRTypeHelper &mth, mlir_ts::FuncOp funcOp, bool refCounted, bool own) { if (funcOp.isExternal() || funcOp.getBody().empty()) { - return importedFunctionReturnsOwned(mth, funcOp, refCounted); + return importedFunctionReturnsOwned(mth, funcOp, refCounted, own); } // A generator's `next` - the function the yields are in - hands its caller a `{ value, diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 843c5b492..0dcadd692 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -6962,15 +6962,19 @@ add_test(NAME test-rc-conditional-named-const-release COMMAND ${CMAKE_COMMAND} -DTSLANG=$ "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/tests/00conditional_named_const_release.ts" -P "${CMAKE_CURRENT_SOURCE_DIR}/conditional-named-const-release.cmake") -# `@owned` on a declared function, class or namespace: its result is the caller's under rc, so a module -# whose only body-less functions say it still consumes the results of calls through function values -# (closed world). The default library's lib.d.ts says it; without it every program with the library -# leaked each such result. No run can see the leak, so the IR is read. -add_test(NAME test-rc-owned-declarations - COMMAND ${CMAKE_COMMAND} -DTSLANG=$ - "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/owned-declarations/owned_declarations.ts" - "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/owned-declarations.cmake") +# `@owned` on a declared function, class or namespace: its result is the caller's under rc and own, so a +# call of one gives back what it is not given to keep, and under rc a module whose only body-less +# functions say it still consumes the results of calls through function values (closed world). Under +# own a `@lends` declaration's result stays a borrow. The default library's lib.d.ts says it; without it +# every program with the library leaked each such result (under own, even one held in a local). No run +# can see the leak, so the IR is read. +foreach(mm rc own) + add_test(NAME test-${mm}-owned-declarations + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMM=${mm} + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/owned-declarations/owned_declarations.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/owned-declarations.cmake") +endforeach() # A spread of run-time length given to a rest parameter, `cat(...parts)`, packs a new array: under rc # the call holds it and gives it back after, as for `cat(a, b)` - the IR is read, as no run shows the # leak (Array.join's `"".concat(...parts)` lost one per call). It runs in every model. diff --git a/tslang/test/tester/owned-declarations.cmake b/tslang/test/tester/owned-declarations.cmake index b14672245..a7bc6e09b 100644 --- a/tslang/test/tester/owned-declarations.cmake +++ b/tslang/test/tester/owned-declarations.cmake @@ -1,15 +1,22 @@ # `@owned` on a declaration (owned-declarations/owned_declarations.ts): the function it covers is # marked ts.declared_owned_result - said on the function, on its `declare class` (methods and `..new`) -# or on its `declare namespace` - and, since nothing else in the file returns a heap value it did not -# retain, the call through a parameter in `viaValue` has its result consumed (__owned_result, not -# MLIRGen's __owned_result_named). +# or on its `declare namespace` - and the result of a call of it, read and dropped (`direct`), is given +# back (__owned_result). Under rc, since nothing else in the file returns a heap value it did not +# retain, the call through a parameter in `viaValue` has its result consumed as well (__owned_result, +# not MLIRGen's __owned_result_named) - and so is `lent`'s, a `@lends` method's, which rc's body +# retains for its caller. Under own a `@lends` method's result is a borrow: `lent`'s call is not +# marked, and with it among the declarations closed world does not hold. # The same file with every `@owned` taken out is the other side: a declaration may be C, or hand back a -# pointer into a buffer, so nothing is marked and the indirect call keeps retaining - closed world -# does not hold. Read after OwnedReturnConsumptionPass (--emit=mlir), under rc. +# pointer into a buffer, so nothing is marked and the calls keep retaining - closed world does not +# hold. Read after OwnedReturnConsumptionPass (--emit=mlir), under rc and under own (MM). cmake_minimum_required(VERSION 3.17.3) +if(NOT MM) + set(MM rc) +endif() + function(compile file outVar) - execute_process(COMMAND "${TSLANG}" --emit=mlir --no-default-lib -mm=rc "${file}" + execute_process(COMMAND "${TSLANG}" --emit=mlir --no-default-lib -mm=${MM} "${file}" OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) # the IR is printed to stderr string(APPEND out "${err}") @@ -44,14 +51,27 @@ foreach(function ${declared}) message(FATAL_ERROR "`${function}` is not marked ts.declared_owned_result:\n${text}") endif() endforeach() +# the result of a call given back: `"ts.CallIndirect"(...) {__owned_result...}`, not `__owned_result_named` alone +set(consumed "\"ts[.]CallIndirect\"[^\n]*[{ ]__owned_result[,}]") +func_text("${marked}" direct text) +if(NOT text MATCHES "${consumed}") + message(FATAL_ERROR "the result of the call of `lib_text` in `direct` is not given back (${MM}):\n${text}") +endif() func_text("${marked}" viaValue text) -if(NOT text MATCHES "\"ts[.]CallIndirect\"[^\n]*__owned_result[,}]") +if(MM STREQUAL "rc" AND NOT text MATCHES "${consumed}") message(FATAL_ERROR "the call through a function value in `viaValue` is not consumed:\n${text}") endif() +func_text("${marked}" lent text) +if(MM STREQUAL "rc" AND NOT text MATCHES "${consumed}") + message(FATAL_ERROR "under rc the result of `label` in `lent` is the caller's:\n${text}") +endif() +if(MM STREQUAL "own" AND text MATCHES "${consumed}") + message(FATAL_ERROR "under own `label` lends its result (`@lends`): `lent` must not give it back:\n${text}") +endif() file(READ "${FILE}" source) string(REPLACE "@owned" "" source "${source}") -set(unmarkedFile "${WORK_DIR}/owned_declarations_unmarked.ts") +set(unmarkedFile "${WORK_DIR}/owned_declarations_unmarked_${MM}.ts") file(WRITE "${unmarkedFile}" "${source}") compile("${unmarkedFile}" unmarked) foreach(function ${declared}) @@ -60,7 +80,9 @@ foreach(function ${declared}) message(FATAL_ERROR "`${function}` says nothing, yet is marked ts.declared_owned_result:\n${text}") endif() endforeach() -func_text("${unmarked}" viaValue text) -if(text MATCHES "\"ts[.]CallIndirect\"[^\n]*__owned_result[,}]") - message(FATAL_ERROR "with unmarked declarations the call in `viaValue` must keep retaining:\n${text}") -endif() +foreach(function viaValue direct) + func_text("${unmarked}" ${function} text) + if(text MATCHES "${consumed}") + message(FATAL_ERROR "with unmarked declarations the call in `${function}` must keep retaining (${MM}):\n${text}") + endif() +endforeach() diff --git a/tslang/test/tester/owned-declarations/owned_declarations.ts b/tslang/test/tester/owned-declarations/owned_declarations.ts index ae26ed191..99c136b89 100644 --- a/tslang/test/tester/owned-declarations/owned_declarations.ts +++ b/tslang/test/tester/owned-declarations/owned_declarations.ts @@ -1,7 +1,9 @@ // `@owned` on a declaration: the function is TypeScript defined elsewhere under the same memory model, -// so under rc its result is a reference the caller owns (DECLARED_OWNED_RESULT_ATTR_NAME). Said on a +// so under rc and own its result is a value the caller owns (DECLARED_OWNED_RESULT_ATTR_NAME). Said on a // `declare function`, a `declare class` (each method, and `..new`) or a `declare namespace` (each -// function in it). Read by owned-declarations.cmake, as it is and with every `@owned` taken out. +// function in it). A method that says it lends its result (`@lends`) is own's to go by: under own its +// result is a borrow, given back by no one. Read by owned-declarations.cmake, as it is and with every +// `@owned` taken out, under rc and under own. @owned declare function lib_text(n: number): string; @@ -10,6 +12,8 @@ declare function lib_text(n: number): string; declare class LibBox { constructor(n: number); describe(): string; + @lends("this") + label(): string; } @owned @@ -26,13 +30,23 @@ function make(n: number): P { } // a call through a parameter names no callee: its result is consumed only when no function here may -// return a heap value without retaining it - and the three declarations above are the only ones that -// could +// return a heap value without retaining it - and the declarations above are the only ones that could +// (`label` among them under own, so own reads `viaValue` as unconsumed either way) function viaValue(g: (n: number) => P, n: number) { const p = g(n); return p.x; } +// a declared function's result, read once and dropped: the caller's to give back +function direct(n: number) { + return lib_text(n).length; +} + +// a borrow of `b`: never the caller's under own +function lent(b: LibBox) { + return b.label().length; +} + function main() { print(viaValue(make, 1)); } From 59b983a6814a496a463a4a11eb6497deeefc21ba Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 15:50:45 +0000 Subject: [PATCH 08/11] WIP 215: -mm=own takes an @owned declaration's result for the caller's own (a new value, not a part of what the call was given) Co-Authored-By: Claude Opus 5.5 --- .../lib/TypeScript/OwnershipSignaturePass.h | 23 ++++++++++++++++--- tslang/test/tester/owned-declarations.cmake | 12 +++++++++- .../owned-declarations/owned_declarations.ts | 9 ++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index f9f77da21..70a47ac76 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -645,9 +645,26 @@ class OwnershipSignaturePass : public mlir::PassWrappergetNumResults() == 1 && - ((!call.callees.importedOverwrites && call.callees.importedName.ends_with("." NEW_METHOD_NAME)) || - importedFreshResults.contains(call.callees.importedName)); + return (call.callees.known && call.callees.imported && call.op->getNumResults() == 1 && + ((!call.callees.importedOverwrites && call.callees.importedName.ends_with("." NEW_METHOD_NAME)) || + importedFreshResults.contains(call.callees.importedName))) || + isDeclaredOwnedResult(call); + } + + // ...or a call of declarations that each say `@owned` (DECLARED_OWNED_RESULT_ATTR_NAME) - the default + // library's lib.d.ts, whose lib.ts is compiled under own too - and nothing of lending their result + // (`@lends`, a result type `this`; `@borrows`' state is marked where it is bounded): the result is the + // caller's, as OwnedReturnConsumptionPass counts it, which gives it back where nothing takes it. Whether + // or not the call is known: `@owned` speaks of the result, not of what the callee destroys. + bool isDeclaredOwnedResult(const Call &call) + { + return call.op->getNumResults() == 1 && !call.callees.named.empty() && + llvm::all_of(call.callees.named, [&](mlir::StringAttr symbol) { + auto funcOp = functions.lookup(symbol.getValue()); + return funcOp && funcOp.isDeclaration() && funcOp->hasAttr(DECLARED_OWNED_RESULT_ATTR_NAME) && + !funcOp->hasAttr(OWN_DECLARED_LENDS_ATTR_NAME) && !funcOp->hasAttr(OWN_DECLARED_BORROWS_ATTR_NAME) && + !funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME); + }); } // The body's own share of a function's FieldDrops: its stores, not its calls. With `fills`, a diff --git a/tslang/test/tester/owned-declarations.cmake b/tslang/test/tester/owned-declarations.cmake index a7bc6e09b..c043d78b3 100644 --- a/tslang/test/tester/owned-declarations.cmake +++ b/tslang/test/tester/owned-declarations.cmake @@ -42,7 +42,7 @@ function(func_text out function outVar) set(${outVar} "${body}" PARENT_SCOPE) endfunction() -set(declared lib_text LibBox..new LibBox.describe LibNS.name) +set(declared lib_text LibBox..new LibBox.describe LibBox.child LibNS.name) compile("${FILE}" marked) foreach(function ${declared}) @@ -69,6 +69,16 @@ if(MM STREQUAL "own" AND text MATCHES "${consumed}") message(FATAL_ERROR "under own `label` lends its result (`@lends`): `lent` must not give it back:\n${text}") endif() +# ...and own's inference takes an `@owned` result for the caller's own, not a part of what it was called on +# (`ofChild`): checked past the affine lowering, where inference runs +if(MM STREQUAL "own") + execute_process(COMMAND "${TSLANG}" --emit=mlir-affine --no-default-lib -mm=own "${FILE}" + OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) + if(NOT result EQUAL 0) + message(FATAL_ERROR "-mm=own refused ${FILE} (${result}):\n${err}") + endif() +endif() + file(READ "${FILE}" source) string(REPLACE "@owned" "" source "${source}") set(unmarkedFile "${WORK_DIR}/owned_declarations_unmarked_${MM}.ts") diff --git a/tslang/test/tester/owned-declarations/owned_declarations.ts b/tslang/test/tester/owned-declarations/owned_declarations.ts index 99c136b89..c790e4a2c 100644 --- a/tslang/test/tester/owned-declarations/owned_declarations.ts +++ b/tslang/test/tester/owned-declarations/owned_declarations.ts @@ -14,6 +14,8 @@ declare class LibBox { describe(): string; @lends("this") label(): string; + @lends("this") + child(): LibBox; } @owned @@ -47,6 +49,13 @@ function lent(b: LibBox) { return b.label().length; } +// what `@owned` returns from a borrow is no part of it: a new string, given back after `b` is (JsonValue's +// `value.get("k").asString()`, which -mm=own took for a use of the borrow after `b`'s release) +function ofChild(n: number) { + const b = new LibBox(n); + return b.child().describe().length; +} + function main() { print(viaValue(make, 1)); } From e125f53e921447e5cc36c316b28fb02813db3210 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 15:55:52 +0000 Subject: [PATCH 09/11] WIP 215: TSLANG_ISSUES: own reads @owned results as fresh Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 9b478e9a9..7abf29afb 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4047,7 +4047,9 @@ Tests `00tslang_issue_214.ts` (all models). the caller's (USER DECISION 2026-11-27, reversing 2026-11-18's rc only: what rc reads, own reads the same way, the two models being alike). It does now, except where a declaration says it lends its result (`@lends`, or a result type `this`: `JsonValue.get`, `ArrayBuffer.__bytes`), which own goes by - under rc that result is the caller's all the same. - Each of those probes is flat under own. + Own's inference takes such a result for the caller's own too (OWN_FRESH_RESULT): a new value, not a part of what the + call was given - else `value.get("k").asString()` read the string's release, after `value`'s, as a use of the borrow + `get` lends. Each of those probes is flat under own, with the default library built by this compiler. Not yet: - Under -mm=own a dictionary written in a loop over an array it is not (`for (const it of items) out[it] = 1`): From 1b18bb27d93d1db17ebc9debe3a6df8834260510 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 16:17:09 +0000 Subject: [PATCH 10/11] WIP 215: a union of tuples cast to a longer member fills the elements a shorter one lacks (user ruling); none to fill them with is a compile error Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 21 ++- tslang/lib/TypeScript/MLIRGenCast.cpp | 160 ++++++++++++++---- tslang/lib/TypeScript/MLIRGenImpl.h | 6 +- tslang/test/tester/CMakeLists.txt | 14 ++ .../test/tester/tests/00tslang_issue_215.ts | 28 +-- .../tests/tuple_union_cast_fill_error.ts | 13 ++ .../tests/tuple_union_cast_fill_nonstrict.ts | 15 ++ 7 files changed, 204 insertions(+), 53 deletions(-) create mode 100644 tslang/test/tester/tests/tuple_union_cast_fill_error.ts create mode 100644 tslang/test/tester/tests/tuple_union_cast_fill_nonstrict.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 7abf29afb..0a375f6fc 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4014,11 +4014,15 @@ Tests `00tslang_issue_214.ts` (all models). mapped type `{ [P in K]: T }` of K = string (the default library's Record). Without the dictionary class, as before. - A union of tuples cast to one of them (`<[number, string, string]>x` of `[number, string] | [number, string, string]`) failed with nothing said ("failed statement"): each member is tested for and cast, and the shorter one - could not be made the longer - its cast read past its end. The member the value holds is cast; one lacking an - element of the target throws "Can't cast from [number, string] to [number, string, string]" there, as a cast from - an interface that does not hold the class throws (TypeScript reads the element as undefined). Only for tuples of - elements: a union of object shapes cast to a shape one member lacks a field of stays the compile error it was. A - tuple cast to one with more elements (not of a union) is a compile error that says so (tsc refuses it too). + could not be made the longer - its cast read past its end. The member the value holds is cast, and each element a + shorter member lacks is filled (USER RULING 2026-11-27; TypeScript reads undefined there): "" for a string under + strict null checks and null without them, 0 for a number, false for a boolean, undefined where the type admits it + (`T | undefined`, `T?`, `any`), and null for a class, an interface or an array without strict null checks. One whose + type has nothing to fill it with - an object literal's, which is a value, or a class's, an interface's or an array's + under strict null checks - makes the cast a compile error ("can't cast '[number]' to '[number, number[]]': it has no + element 1 of 'number[]', and nothing fills it under strict null checks"). Only for tuples of elements: a union of + object shapes cast to a shape one member lacks a field of stays the compile error it was. A tuple cast to one with + more elements (not of a union) is a compile error that says so (tsc refuses it too). - `x[1]` of such a union, "access expression is not applicable": an element at a constant index every member has, after the same element types, is read where the first member has it. - A member of Array of a union of tuples (`x.slice(1)`, `x.join(",")`, `forEach`, `map`) read the value as the first @@ -4052,6 +4056,10 @@ Tests `00tslang_issue_214.ts` (all models). `get` lends. Each of those probes is flat under own, with the default library built by this compiler. Not yet: +- Under -mm=own a union of tuples cast to a longer member is read where it is cast or held in a local (`const l = + x`), but a function can't return it whole (`return x`): "a value is merged from several branches". Each + branch borrows `x` - the member that is the target, or the shorter one filled - and own proves a merge of new values, + not a merge of borrows of one value. - Under -mm=own a dictionary written in a loop over an array it is not (`for (const it of items) out[it] = 1`): "'it' borrows an element but is used here after it may be released", of `Record` and of `{ [k: string]: number }` alike. The dictionary's `set` is known only to drop strings held anywhere (its drop facts are @@ -4062,4 +4070,5 @@ Not yet: callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads of a declared function (136) and of a `declare class` constructor (140). -Tests `00tslang_issue_215.ts` (all models), `test-{rc,own}-owned-declarations` (the IR of `@owned` and `@lends` calls). +Tests `00tslang_issue_215.ts` (all models), `test-{rc,own}-owned-declarations` (the IR of `@owned` and `@lends` calls), +`tuple_union_cast_fill_error.ts`, `tuple_union_cast_fill_nonstrict.ts` (`--strict-null-checks=false`, all models). diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 5a61e3bf7..35cb6b8ec 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -207,28 +207,91 @@ namespace mlirgen return mlir::Value(); } - // Whether a tuple lacks a field of `fields` that absentFieldValue can't make: one of another type than an optional, - // `undefined` or `any`, which is neither in it by name nor, an element, at its index (`[number, string]` for - // `[number, string, string]`). Nothing is generated. - bool MLIRGenImpl::tupleLacksField(mlir_ts::TupleType srcTupleType, ArrayRef fields) + // Is there a value for an element a union's member lacks, when the union is cast to a longer member + // (castFromUnion, USER RULING 2026-11-27)? What absentFieldValue makes of a type that admits undefined, 0 of a + // number, false of a boolean, "" of a string under strict null checks and null without them, null of a class, an + // interface or an array without strict null checks, and undefined or null of a union that has it. Nothing for + // any other type - an object literal's, which is a value, or an array under strict null checks: the cast is a + // compile error. + bool MLIRGenImpl::hasElementFill(mlir::Type type) { - for (auto [index, fieldInfo] : enumerate(fields)) + if (isa(type)) { - auto positional = fieldInfo.id == mlir::Attribute() - || (index < srcTupleType.size() && srcTupleType.getFieldInfo(index).id == mlir::Attribute()); - auto present = positional ? index < srcTupleType.size() : srcTupleType.getIndex(fieldInfo.id) >= 0; - if (!present && !isa(fieldInfo.type)) - { - return true; - } + return true; } - return false; + if (auto unionType = dyn_cast(type)) + { + return llvm::any_of(unionType.getTypes(), + [](mlir::Type member) { return isa(member); }); + } + + return !compileOptions.strictNullChecks && isa(type); + } + + // ...and the value itself (TypeScript reads undefined there, which a number or a string can't hold here) + mlir::Value MLIRGenImpl::elementFillValue(mlir::Location location, mlir::Type type, const GenContext &genContext) + { + if (auto absent = absentFieldValue(location, type, genContext)) + { + return absent; + } + + if (isa(type)) + { + return builder.create(location, type, builder.getF64FloatAttr(0.0)); + } + + if (isa(type)) + { + return builder.create(location, type, builder.getIntegerAttr(type, 0)); + } + + if (isa(type)) + { + return builder.create(location, type, builder.getFloatAttr(type, 0.0)); + } + + if (isa(type)) + { + return builder.create(location, type, builder.getBoolAttr(false)); + } + + if (isa(type) && compileOptions.strictNullChecks) + { + return builder.create(location, type, getStringAttr("")); + } + + if (!hasElementFill(type)) + { + return mlir::Value(); + } + + // undefined of a union that has it; else null + auto unionType = dyn_cast(type); + mlir::Value nothing; + if (unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); })) + { + nothing = builder.create(location, getUndefinedType()); + } + else + { + nothing = builder.create(location, getNullType()); + } + + auto result = cast(location, type, nothing, genContext); + return result.failed() ? mlir::Value() : V(result); } - ValueOrLogicalResult MLIRGenImpl::mapTupleToFields(mlir::Location location, SmallVector &values, mlir::Value value, mlir_ts::TupleType srcTupleType, + ValueOrLogicalResult MLIRGenImpl::mapTupleToFields(mlir::Location location, SmallVector &values, mlir::Value value, mlir_ts::TupleType srcTupleType, ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, bool filterSpecialCases, const GenContext &genContext, bool errorAsWarning) { + // a union's member made a longer member (castFromUnion): its missing elements filled - its own, not those of + // a tuple in an element of it, which this casts in turn (the first mapping takes it) + auto fillAbsent = fillAbsentTupleElements; + fillAbsentTupleElements = false; + auto count = 0; for (auto [index, fieldInfo] : enumerate(fields)) { @@ -251,7 +314,8 @@ namespace mlirgen { if (index >= srcTupleType.size()) { - if (auto undefVal = absentFieldValue(location, fieldInfo.type, genContext)) + if (auto undefVal = fillAbsent ? elementFillValue(location, fieldInfo.type, genContext) + : absentFieldValue(location, fieldInfo.type, genContext)) { values.push_back(undefVal); continue; @@ -426,6 +490,9 @@ namespace mlirgen SmallVector values; + // a union's member made a longer member, its missing elements filled (castFromUnion), which mapTupleToFields + // takes + auto filling = fillAbsentTupleElements; auto result = mapTupleToFields(location, values, value, srcTupleType, fields, false, genContext, errorAsWarning); if (mlir::failed(result)) { @@ -445,13 +512,16 @@ namespace mlirgen // that only now takes its type, `[{ a: "x", c: "" }, { a: "y", c: 0 }]` re-made as the common record: its fields // are its own, given on as they were. A named `const` built in its slot is read with OWNED_RESULT_NAMED: a // variable, whose fields are borrowed) + // (not of a union's member made a longer member either: it stays a borrow of the union - what it reads of the + // member and constants -, as the member that already is the target is, which the same `?:` of the cast gives: + // one branch owned and the other borrowed is a merge -mm=own cannot settle) auto sourceLoad = value.getDefiningOp(); auto sourceSlot = sourceLoad ? sourceLoad.getReference().getDefiningOp() : mlir_ts::VariableOp(); auto literalSource = value.getDefiningOp() || value.getDefiningOp() || (sourceSlot && !sourceSlot->hasAttr(OWNED_LOCAL_ATTR_NAME) && sourceSlot.getInitializer() && sourceSlot.getInitializer().getDefiningOp() && !sourceLoad->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME)); - if (compileOptions.memoryModel == MemoryModelOwn && !literalSource && canMakeOwnedTemporaryLocal(genContext)) + if (compileOptions.memoryModel == MemoryModelOwn && !literalSource && !filling && canMakeOwnedTemporaryLocal(genContext)) { // a string read out of the source is copied; every other field that holds a block has to be a new value or // constant data, or the local would release what the source still holds: the tuple stays a borrow then @@ -5943,31 +6013,53 @@ namespace mlirgen { targetTuple = mlir_ts::TupleType(); } - std::function castOf = [&](size_t index) -> ValueOrLogicalResult { - auto asMember = [&]() -> ValueOrLogicalResult { - // a member the target can't be made of (`<[number, string, string]>x` of `[number, string] | - // [number, string, string]`, holding the first): the assertion is false. The value is not a - // target, a run-time error, as a cast from an interface that does not hold the class is. (Its - // cast failed with nothing said: "failed statement".) - auto memberTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(members[index])); - if (targetTuple && memberTuple && tupleLacksField(memberTuple, targetTuple.getFields())) + // A member that lacks elements of the target (`<[number, string, string]>x` of `[number, string] | + // [number, string, string]`, holding the first) is made the target with each element it lacks filled + // (USER RULING 2026-11-27): "" for a string - null without strict null checks -, 0 for a number, false + // for a boolean, undefined where the type admits it (elementFillValue; TypeScript reads undefined). + // An element whose type has nothing to fill it with (an object literal's, or a class's, an interface's + // or an array's under strict null checks) makes the cast a compile error. (Its cast failed with + // nothing said, "failed statement"; then it threw at run time.) + if (targetTuple) + { + for (auto member : members) + { + auto memberTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(member)); + if (!memberTuple) + { + continue; + } + + for (auto [elementIndex, field] : enumerate(targetTuple.getFields())) { - auto message = builder.create( - location, getStringType(), - getStringAttr("Can't cast from " + to_print(members[index]) + " to " + to_print(type))); - builder.create(location, message); - if (!mlirGenRttiForType(location, message.getType())) + if (elementIndex < memberTuple.size() || hasElementFill(field.type)) { - emitError(location, "Not supported type in throw"); - return mlir::failure(); + continue; } - // not reached; the branch still needs a value of the target type - return V(builder.create(location, type)); + auto diag = emitError(location) << "can't cast '" << to_print(member) << "' to '" << to_print(type) + << "': it has no element " << elementIndex << " of '" + << to_print(field.type) << "', and nothing fills it"; + if (compileOptions.strictNullChecks + && isa(field.type)) + { + diag << " under strict null checks (it would be null)"; + } + + return mlir::failure(); } + } + } + std::function castOf = [&](size_t index) -> ValueOrLogicalResult { + auto asMember = [&]() -> ValueOrLogicalResult { auto memberValue = builder.create(location, members[index], value); - return cast(location, type, memberValue, genContext); + auto memberTuple = dyn_cast(mth.convertConstTupleTypeToTupleType(members[index])); + auto shorter = targetTuple && memberTuple && memberTuple.size() < targetTuple.size(); + fillAbsentTupleElements = shorter; + auto result = cast(location, type, memberValue, genContext); + fillAbsentTupleElements = false; + return result; }; if (index + 1 == members.size()) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 09a338df6..2afa639ec 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -20935,7 +20935,8 @@ class MLIRGenImpl ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, bool filterSpecialCases, const GenContext &genContext, bool errorAsWarning = false); mlir::Value absentFieldValue(mlir::Location location, mlir::Type fieldType, const GenContext &genContext); - bool tupleLacksField(mlir_ts::TupleType srcTupleType, ArrayRef fields); + bool hasElementFill(mlir::Type type); + mlir::Value elementFillValue(mlir::Location location, mlir::Type type, const GenContext &genContext); mlir::Type unionTuplesCommonPrefixMember(mlir_ts::UnionType unionType, mlir::Value index); // TODO: needs to unified with selectFieldsValues @@ -21113,6 +21114,9 @@ class MLIRGenImpl // the union casts whose helper is being made: the same one met again in it (its `return t` not narrowed, a // member that failed) is an error, not a helper that instantiates itself until the stack overflows llvm::DenseSet> castsFromUnionInProgress; + // a member of a union of tuples cast to a longer member (castFromUnion): mapTupleToFields fills each element it + // lacks (elementFillValue) instead of refusing it + bool fillAbsentTupleElements = false; ValueOrLogicalResult castNullableToString(mlir::Location location, mlir::Type type, mlir::Value value, mlir::Type baseType, const GenContext &genContext); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 0dcadd692..8cd15e96d 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2411,6 +2411,20 @@ add_test(NAME test-compile-own-tuple-as-array-error COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/own_tuple_as_array_error.ts") set_tests_properties(test-compile-own-tuple-as-array-error PROPERTIES PASS_REGULAR_EXPRESSION "an element of '\\[number, number\\[\\]\\]' would have two owners as an element of an array" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +# A union of tuples cast to a longer member fills what the shorter one lacks (TSLANG 215, USER RULING 2026-11-27); an +# array under strict null checks has nothing to fill it with, a compile error. Without them it, a string and a class are +# null: run there by tslang itself, as test-runner has no switch for strict null checks +add_test(NAME test-compile-tuple-union-cast-fill-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/tuple_union_cast_fill_error.ts") +set_tests_properties(test-compile-tuple-union-cast-fill-error PROPERTIES PASS_REGULAR_EXPRESSION "can't cast '\\[number, string\\]' to '\\[number, string, number\\[\\]\\]': it has no element 2 of 'number\\[\\]', and nothing fills it under strict null checks" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +foreach(fill_mm gc rc none own) + add_test(NAME test-compile-tuple-union-cast-fill-nonstrict-${fill_mm} + COMMAND $ --emit=mlir-affine --no-default-lib --strict-null-checks=false -mm=${fill_mm} + "${PROJECT_SOURCE_DIR}/test/tester/tests/tuple_union_cast_fill_nonstrict.ts") + set_tests_properties(test-compile-tuple-union-cast-fill-nonstrict-${fill_mm} PROPERTIES PASS_REGULAR_EXPRESSION "ts\\.Null" + FAIL_REGULAR_EXPRESSION "error:|Stack dump|Assertion failed") +endforeach() # Mixins (a generic function given a class) under every memory model foreach(mixin_mm gc rc none own) tslang_add_test(NAME test-jit-00-mixins-${mixin_mm} COMMAND test-runner -jit -mm=${mixin_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00mixins.ts") diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index f052520df..3a81bfde5 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -1,8 +1,8 @@ // TSLANG 215: `Record` is `{ [key: string]: T }`, a dictionary of T (it was an object with no fields: the // literal given to it lost its fields, and Object.keys gave none), both as the built-in Record and as a mapped type -// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them, indexed (at a constant or a run-time -// index), iterated, and read as an array (`slice`, `forEach`, `[...x]`: of the member it holds; under -mm=own its -// strings copied). +// `{ [P in K]: T }` of K = string; a union of tuples cast to one of them (a shorter member's missing elements filled: +// USER RULING 2026-11-27), indexed (at a constant or a run-time index), iterated, and read as an array (`slice`, +// `forEach`, `[...x]`: of the member it holds; under -mm=own its strings copied). // The tests compile without the default library: its ObjectDictionary, as the compiler finds it by name. @dictionary class ObjectDictionary { @@ -185,20 +185,24 @@ function tuples() { assert((y)[1] == "c" + i); total += y.length; - // a false assertion: the value is no Three - let caught = false; - try { - third(y); - } catch (e) { - caught = true; - } - - assert(caught); + // the value is no Three: the element it lacks is filled - "" for a string under strict null checks + assert(third(y) == ""); + + // ...0 for a number, false for a boolean, undefined where the type admits it (cast where it is read: under + // -mm=own the cast is a merge of the members' branches, which a function can't return whole yet) + const z: Two | Long = [i, "c" + i]; + const l = z; + assert(l[0] == i && l[1] == "c" + i && l[2] == 0 && l[3] == false && l[4] == "" && l[5] === undefined); + const w: Two | Long = [i, "e" + i, 7, true, "f" + i, 9]; + const m = w; + assert(m[2] == 7 && m[3] && m[4] == "f" + i && m[5] == 9); } assert(total == 15); } +type Long = [number, string, number, boolean, string, number | undefined]; + function main() { tuples(); arrays(); diff --git a/tslang/test/tester/tests/tuple_union_cast_fill_error.ts b/tslang/test/tester/tests/tuple_union_cast_fill_error.ts new file mode 100644 index 000000000..3fab35122 --- /dev/null +++ b/tslang/test/tester/tests/tuple_union_cast_fill_error.ts @@ -0,0 +1,13 @@ +// A union of tuples cast to a longer member fills each element the shorter one lacks (TSLANG 215, USER RULING +// 2026-11-27) - but under strict null checks nothing fills an array: only null could. A compile error. +type Short = [number, string]; +type Long = [number, string, number[]]; + +function third(x: Short | Long) { + return (x)[2].length; +} + +function main() { + const x: Short | Long = [1, "a"]; + print(third(x)); +} diff --git a/tslang/test/tester/tests/tuple_union_cast_fill_nonstrict.ts b/tslang/test/tester/tests/tuple_union_cast_fill_nonstrict.ts new file mode 100644 index 000000000..43504bcb7 --- /dev/null +++ b/tslang/test/tester/tests/tuple_union_cast_fill_nonstrict.ts @@ -0,0 +1,15 @@ +// A union of tuples cast to a longer member without strict null checks (TSLANG 215, USER RULING 2026-11-27): a +// string, a class or an array the shorter member lacks is filled with null. Compiled with --strict-null-checks=false. +class Box { + constructor(public n: number) {} +} + +type Short = [number, boolean]; +type Long = [number, boolean, string, Box, number[]]; + +function main() { + const x: Short | Long = [1, true]; + const l = x; + assert(l[0] == 1 && l[1] && l[2] == null && l[3] == null && l[4] == null); + print("done."); +} From 4c81334137de032f61d3b054b1cc3dc832ad115c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 27 Nov 2026 16:29:32 +0000 Subject: [PATCH 11/11] WIP 215: a Record result type read elsewhere, a Record constraint met by any object, keyof of a dictionary is string; verifier skips the fill tests Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 5 +++++ tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 18 ++++++++++++++++-- tslang/lib/TypeScript/MLIRGenTypes.cpp | 15 +++++++++++++++ .../test/tester/tests/00tslang_issue_215.ts | 19 +++++++++++++++++++ tslang/test/tester/verify-ownership.cmake | 3 +++ 5 files changed, 58 insertions(+), 2 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 0a375f6fc..7efece0fc 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4012,6 +4012,11 @@ Tests `00tslang_issue_214.ts` (all models). literal given to it lost its fields, `Object.keys` gave none and `r["a"]` read nothing (131). It is `{ [key: string]: T }`, the dictionary of T a string index signature is, both as the built-in Record (no default library) and as the mapped type `{ [P in K]: T }` of K = string (the default library's Record). Without the dictionary class, as before. + Such a dictionary as a function's result type has its members generated where it is read (`Object.keys(f())` was + "'ObjectDictionary.keys' does not reference a valid function": the alias is read once, in an early pass); + as a constraint (`T extends Record`) an object of any fields meets it, as `{}` did; and `keyof` of one is + `string`, not the members of the class that holds it (the tsc sweep's 7 tests of these, failing with the change + alone, pass). - A union of tuples cast to one of them (`<[number, string, string]>x` of `[number, string] | [number, string, string]`) failed with nothing said ("failed statement"): each member is tested for and cast, and the shorter one could not be made the longer - its cast read past its end. The member the value holds is cast, and each element a diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index ffe64a34e..a310d11e2 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -4223,12 +4223,21 @@ namespace mlirgen mlir::Type MLIRGenImpl::instantiatedDictionaryType(mlir::Location location, mlir::Type type, const GenContext &genContext) { auto classInfo = dictionaryClassInfoOf(type, genContext); - if (!classInfo || classInfo->typeParamsWithArgs.size() != 1) + auto genericClassInfo = classInfo ? getGenericClassInfoByFullName(OBJECT_DICTIONARY_CLASS_NAME) : GenericClassInfo::TypePtr(); + if (!genericClassInfo || genericClassInfo->typeParams.size() != 1) { return type; } - auto valueType = std::get<1>(classInfo->typeParamsWithArgs.begin()->getValue()); + // its value type, by the name of the class's type parameter: one instantiated inside a generic alias + // (`Record`, the mapped type `{ [P in K]: T }`) carries the alias's type arguments as well + auto found = classInfo->typeParamsWithArgs.find(genericClassInfo->typeParams.front()->getName()); + if (found == classInfo->typeParamsWithArgs.end()) + { + return type; + } + + auto valueType = std::get<1>(found->getValue()); auto instantiated = getObjectDictionaryType(location, valueType, genContext); return instantiated ? instantiated : type; } @@ -4295,6 +4304,11 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::mlirGenDictionaryCall(mlir::Location location, mlir::Value dictionary, StringRef method, SmallVector &operands, const GenContext &genContext) { + // a dictionary whose type was found in an earlier pass (`f(): Record`: the alias is read once) may + // have had its members generated nowhere: instantiated here, as for an entry read ("'ts.Call' op + // 'ObjectDictionary.keys' does not reference a valid function" of `Object.keys(f())`) + instantiatedDictionaryType(location, dictionary.getType(), genContext); + auto methodResult = mlirGenPropertyAccessExpression(location, dictionary, method, genContext); EXIT_IF_FAILED_OR_NO_VALUE(methodResult) return mlirGenCall(location, V(methodResult), operands, genContext); diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index d0bbe3fc7..a236c1ffe 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -329,6 +329,14 @@ namespace mlirgen } auto extendsResult = mth.extendsType(location, type, constraintType, pairs); + // `T extends Record` (a dictionary, TSLANG 215): an object of any fields can be given to one, as + // to `{}`, which it was before - not only another dictionary + if (extendsResult != ExtendsResult::True && dictionaryClassInfoOf(constraintType, genContext) + && isa(type)) + { + extendsResult = ExtendsResult::True; + } + if (extendsResult != ExtendsResult::True) { // special case when we work with generic type(which are not specialized yet) @@ -2059,6 +2067,13 @@ namespace mlirgen return mth.getFieldNames(type); } + // a dictionary (`{ [key: string]: T }`, `Record`, TSLANG 215): its keys are strings, not the members + // of the class that holds them (`[K in keyof B]` of `B extends Record` read `close` and the like) + if (dictionaryClassInfoOf(type, genContext)) + { + return getStringType(); + } + if (auto objType = dyn_cast(type)) { // TODO: I think this is mistake diff --git a/tslang/test/tester/tests/00tslang_issue_215.ts b/tslang/test/tester/tests/00tslang_issue_215.ts index 3a81bfde5..8eac7caf7 100644 --- a/tslang/test/tester/tests/00tslang_issue_215.ts +++ b/tslang/test/tester/tests/00tslang_issue_215.ts @@ -99,6 +99,21 @@ function sumOf(r: Rec) { type Two = [number, string]; type Three = [number, string, string]; +// a Record as a function's result type, read in another function (its members generated where it is read), and as a +// constraint, which an object of any fields meets +function recordOf(i: number): Record { + return { a: i, b: i + 1 }; +} + +function countOf>(t: T) { + let n = 0; + for (const k in t) { + n++; + } + + return n; +} + function third(x: Two | Three) { return (x)[2]; } @@ -228,6 +243,10 @@ function main() { assert(made == "f0s0f1s1f2s2"); + const fromCall = recordOf(4); + assert(Object.keys(fromCall).length == 2 && fromCall["b"] == 5); + assert(countOf({ x: 1, y: 2, z: 3 }) == 3); + // a Record of known keys stays an object of those fields const p: Record<"a" | "b", number> = { a: 5, b: 6 }; assert(p.a + p.b == 11); diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index e07777683..de2be621c 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -63,6 +63,9 @@ set(not_compilable_alone class_value_constructor_error.ts class_value_union_abstract_error.ts own_tuple_as_array_error.ts + tuple_union_cast_fill_error.ts + # compiled with --strict-null-checks=false (test-compile-tuple-union-cast-fill-nonstrict-*): null fills a string + tuple_union_cast_fill_nonstrict.ts class_local_capture_error.ts class_field_capture_error.ts cpp_class_value_error.ts