Skip to content

Commit 62e50ff

Browse files
TSLANG 215: Record<string, T>, unions of tuples (cast fills missing elements), rc/own leaks, own reads @owned (#1051)
* WIP 215: Record<string, T> is a dictionary of T (built-in Record and a mapped type of string keys) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * WIP 215: TSLANG_ISSUES 215 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * WIP 215: -mm=own reads @owned as rc does (a declaration that lends its result excepted) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * WIP 215: TSLANG_ISSUES: own reads @owned results as fresh Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c804daf commit 62e50ff

17 files changed

Lines changed: 1176 additions & 76 deletions

‎TSLANG_ISSUES.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4006,3 +4006,74 @@ Not yet:
40064006
as a value; design questions without a ruling: overloads of a declared function (136) and class constructor (140).
40074007
40084008
Tests `00tslang_issue_214.ts` (all models).
4009+
4010+
215. Leftovers of 214 (2026-11-27). Fixed:
4011+
- `Record<string, T>` was an object with no fields in every model ("mapped type is empty for constrain: string"): the
4012+
literal given to it lost its fields, `Object.keys` gave none and `r["a"]` read nothing (131). It is `{ [key: string]:
4013+
T }`, the dictionary of T a string index signature is, both as the built-in Record (no default library) and as the
4014+
mapped type `{ [P in K]: T }` of K = string (the default library's Record). Without the dictionary class, as before.
4015+
Such a dictionary as a function's result type has its members generated where it is read (`Object.keys(f())` was
4016+
"'ObjectDictionary<!ts.number>.keys' does not reference a valid function": the alias is read once, in an early pass);
4017+
as a constraint (`T extends Record<string, X>`) an object of any fields meets it, as `{}` did; and `keyof` of one is
4018+
`string`, not the members of the class that holds it (the tsc sweep's 7 tests of these, failing with the change
4019+
alone, pass).
4020+
- A union of tuples cast to one of them (`<[number, string, string]>x` of `[number, string] | [number, string,
4021+
string]`) failed with nothing said ("failed statement"): each member is tested for and cast, and the shorter one
4022+
could not be made the longer - its cast read past its end. The member the value holds is cast, and each element a
4023+
shorter member lacks is filled (USER RULING 2026-11-27; TypeScript reads undefined there): "" for a string under
4024+
strict null checks and null without them, 0 for a number, false for a boolean, undefined where the type admits it
4025+
(`T | undefined`, `T?`, `any`), and null for a class, an interface or an array without strict null checks. One whose
4026+
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
4027+
under strict null checks - makes the cast a compile error ("can't cast '[number]' to '[number, number[]]': it has no
4028+
element 1 of 'number[]', and nothing fills it under strict null checks"). Only for tuples of elements: a union of
4029+
object shapes cast to a shape one member lacks a field of stays the compile error it was. A tuple cast to one with
4030+
more elements (not of a union) is a compile error that says so (tsc refuses it too).
4031+
- `x[1]` of such a union, "access expression is not applicable": an element at a constant index every member has,
4032+
after the same element types, is read where the first member has it.
4033+
- A member of Array of a union of tuples (`x.slice(1)`, `x.join(",")`, `forEach`, `map`) read the value as the first
4034+
member, in every model: a `[0, "c"]` held by `[number, string] | [number, string, string]` joined "0,c,null". It is
4035+
the array of the member the value holds, of the union of all members' element types. So is `[...x]` (it was "can't
4036+
estimate element of array").
4037+
- Under -mm=own a tuple read from a variable made an array (`t.slice(1)`, `t.forEach(f)` of `t: [number, string]`)
4038+
was refused ("an element ... would have two owners as an element of an array"): its strings are copied for the array,
4039+
as a tuple cast to another copies them (211). Another element owning memory stays refused.
4040+
- A union of object shapes or tuples cast to one of its members boxed the union in an `any` to read its tag, and
4041+
nothing gave the box back: about 40 bytes a cast under rc and -mm=own. The union's own tag is read.
4042+
- A union of tuples iterated (`for (const e of x)`) or read at a run-time index (`x[i]`), "access expression is not
4043+
applicable": the elements of the member it holds, and the element of that member (each member tested for, as a
4044+
cast is). `x[1] = v` stays refused, and says why: the element is read out of the member the union holds, a copy.
4045+
- Under -mm=rc an array made for a call and given as `this` to a method (`([i, s] as (number | string)[]).slice(1)`,
4046+
`t.slice(1)` of a tuple, `[...x]` of a union of tuples) was never given back: about 100 bytes a call (with the
4047+
compiler of c2a88259d too). Born uncounted, it gets the reference a new string has (markFreshBlockOwned) and is given
4048+
back where nothing takes it.
4049+
- Under -mm=own a spread literal given to a call (`cnt(...xs)`, the default library's `join`: `"".concat(...parts)`)
4050+
was never given back: about 100 bytes a call (with the compiler of c2a88259d too). It is given back as a literal
4051+
given to a call is (ownNewArrayArguments), with copies of the text pushed into it; one holding an object read from
4052+
elsewhere stays as it was.
4053+
- Under -mm=own no result of a default-library function was ever given back, held in a local or not
4054+
(`s.toUpperCase()` 16 bytes a call, `s.split("b")` 107, `(1.5).toFixed(2)` 64, `JSON.parse(t)` about 800; with the
4055+
compiler of c2a88259d too; rc freed them all): own did not read `@owned`, the declaration's word that its result is
4056+
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
4057+
models being alike). It does now, except where a declaration says it lends its result (`@lends`, or a result type
4058+
`this`: `JsonValue.get`, `ArrayBuffer.__bytes`), which own goes by - under rc that result is the caller's all the same.
4059+
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
4060+
call was given - else `value.get("k").asString()` read the string's release, after `value`'s, as a use of the borrow
4061+
`get` lends. Each of those probes is flat under own, with the default library built by this compiler.
4062+
4063+
Not yet:
4064+
- 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 =
4065+
<Long>x`), but a function can't return it whole (`return <Long>x`): "a value is merged from several branches". Each
4066+
branch borrows `x` - the member that is the target, or the shorter one filled - and own proves a merge of new values,
4067+
not a merge of borrows of one value.
4068+
- Under -mm=own a dictionary written in a loop over an array it is not (`for (const it of items) out[it] = 1`):
4069+
"'it' borrows an element but is used here after it may be released", of `Record<string, number>` and of `{ [k:
4070+
string]: number }` alike. The dictionary's `set` is known only to drop strings held anywhere (its drop facts are
4071+
`[-1, string]`), so any string read out of an array is taken for freed by it; facts naming what is under `this` would
4072+
tell `items` apart.
4073+
- Still from 214: 128 under own (a capture by value for value types), own `Constructor<T>` of `...args: any[]`; from
4074+
213: 56, 153, 159 under own; 131 (`Object.keys` of `object`, `Object.assign`, `defineProperty`, `create`), 108, 191's
4075+
callable interfaces, recursive conditional types, `Symbol` as a value; design questions without a ruling: overloads
4076+
of a declared function (136) and of a `declare class` constructor (140).
4077+
4078+
Tests `00tslang_issue_215.ts` (all models), `test-{rc,own}-owned-declarations` (the IR of `@owned` and `@lends` calls),
4079+
`tuple_union_cast_fill_error.ts`, `tuple_union_cast_fill_nonstrict.ts` (`--strict-null-checks=false`, all models).

‎tslang/include/TypeScript/Defines.h‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -510,8 +510,10 @@
510510
// it returns a reference its caller owns (§9.24), as an imported `export`ed function does. An
511511
// unmarked declaration may be C, or TypeScript that hands back a pointer into a buffer
512512
// (`convertNumber`): nothing can be said of its result, and its callers keep retaining. Said on a
513-
// function with a body it is ignored - a body is read, not trusted. Only rc reads it: -mm=own goes by
514-
// its declared facts (`@lends`, `@record`). A unit attribute on the FuncOp.
513+
// function with a body it is ignored - a body is read, not trusted. rc and own read it alike (own: its
514+
// result is the caller's to own, as a call of a function here that returns a new value is), except
515+
// where a declaration says it lends its result (`@lends`, or a result type `this`): that is own's to
516+
// go by. A unit attribute on the FuncOp.
515517
// An array literal with a spread of run-time length (`[...xs]`, and the rest argument `f(...xs)` packs)
516518
// is filled through a slot of its own, and what MLIRGen hands on is a read of that slot: this unit
517519
// attribute on the `ts.Load` says it is the new array, born uncounted as a `ts.CreateArray` is. Under rc

‎tslang/lib/TypeScript/MLIRGenAccessCall.cpp‎

Lines changed: 120 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,21 @@ namespace mlirgen
559559
return V(fieldRead);
560560
}
561561

562+
// a member of Array reading a union of tuples (`x.slice(1)`): of the array of the member it holds
563+
if (isArrayReadMember(name))
564+
{
565+
auto arrayValue = mlirGenUnionOfTuplesAsArray(location, objectValue, unionType, genContext);
566+
if (arrayValue.failed())
567+
{
568+
return mlir::Value();
569+
}
570+
571+
if (arrayValue.value)
572+
{
573+
return mlirGenPropertyAccessExpression(location, V(arrayValue), name, false, genContext);
574+
}
575+
}
576+
562577
// the same field in every member (or a method, dispatched where it is called): read as the first
563578
auto frontType = mth.getFirstNonNullUnionType(unionType);
564579
//auto casted = cast(location, frontType, objectValue, genContext);
@@ -704,6 +719,27 @@ namespace mlirgen
704719

705720
LLVM_DEBUG(llvm::dbgs() << "!! this type of function is : " << thisTypeFromFunc << "\n";);
706721

722+
// -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
723+
// uncounted, and nothing gave it back: about 100 bytes a call. It gets the standing a new string has
724+
// (markFreshBlockOwned): a reference of its own, marked so, given back where nothing takes it (§9.30)
725+
if (compileOptions.isRefCounted() && isa<mlir_ts::ArrayType>(thisValue.getType()))
726+
{
727+
auto source = thisValue;
728+
while (auto castOp = source.getDefiningOp<mlir_ts::CastOp>())
729+
{
730+
source = castOp.getIn();
731+
}
732+
733+
auto *definingOp = source.getDefiningOp();
734+
auto isNewArray = isa_and_nonnull<mlir_ts::CreateArrayOp>(definingOp)
735+
|| (isa_and_nonnull<mlir_ts::LoadOp>(definingOp) && definingOp->hasAttr(SPREAD_ARRAY_LITERAL_ATTR_NAME));
736+
if (isNewArray && !definingOp->hasAttr(OWNED_RESULT_ATTR_NAME) && isa<mlir_ts::ArrayType>(source.getType()))
737+
{
738+
builder.create<mlir_ts::RetainOp>(location, source);
739+
definingOp->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr());
740+
}
741+
}
742+
707743
// a key of an `any` is read at run time: a function of the same name found in some namespace is no member
708744
// of it unless it takes an `any` (`foo.get = class {}` with `foo: any` found the library's generic
709745
// `Reflect.get<T, K>(target: T, ...)`, whose `T` takes anything, and assigned to it)
@@ -1763,6 +1799,60 @@ namespace mlirgen
17631799
return lookup(0);
17641800
}
17651801

1802+
// The first member of a union of tuples, all of elements only, when each has the element at the constant index
1803+
// `index` holds and the same element types up to it: one laid out alike there, whichever member a value holds.
1804+
// No type otherwise.
1805+
mlir::Type MLIRGenImpl::unionTuplesCommonPrefixMember(mlir_ts::UnionType unionType, mlir::Value index)
1806+
{
1807+
auto constantOp = index.getDefiningOp<mlir_ts::ConstantOp>();
1808+
if (!constantOp)
1809+
{
1810+
return mlir::Type();
1811+
}
1812+
1813+
int64_t position = -1;
1814+
if (auto intAttr = dyn_cast<mlir::IntegerAttr>(constantOp.getValue()))
1815+
{
1816+
position = intAttr.getValue().getSExtValue();
1817+
}
1818+
else if (auto floatAttr = dyn_cast<mlir::FloatAttr>(constantOp.getValue());
1819+
floatAttr && floatAttr.getValueAsDouble() == (double)(int64_t)floatAttr.getValueAsDouble())
1820+
{
1821+
position = (int64_t)floatAttr.getValueAsDouble();
1822+
}
1823+
1824+
if (position < 0)
1825+
{
1826+
return mlir::Type();
1827+
}
1828+
1829+
SmallVector<mlir_ts::TupleType> tuples;
1830+
for (auto member : unionType.getTypes())
1831+
{
1832+
auto tupleType = dyn_cast<mlir_ts::TupleType>(mth.convertConstTupleTypeToTupleType(member));
1833+
if (!tupleType || (int64_t)tupleType.size() <= position
1834+
|| llvm::any_of(tupleType.getFields(), [](auto &field) { return !!field.id; }))
1835+
{
1836+
return mlir::Type();
1837+
}
1838+
1839+
tuples.push_back(tupleType);
1840+
}
1841+
1842+
for (auto tupleType : ArrayRef<mlir_ts::TupleType>(tuples).drop_front())
1843+
{
1844+
for (int64_t i = 0; i <= position; i++)
1845+
{
1846+
if (tupleType.getFieldInfo(i).type != tuples.front().getFieldInfo(i).type)
1847+
{
1848+
return mlir::Type();
1849+
}
1850+
}
1851+
}
1852+
1853+
return unionType.getTypes().front();
1854+
}
1855+
17661856
ValueOrLogicalResult MLIRGenImpl::mlirGenElementAccess(mlir::Location location, mlir::Value expression, mlir::Value argumentExpression, bool isConditionalAccess, const GenContext &genContext)
17671857
{
17681858
auto arrayType = expression.getType();
@@ -1792,6 +1882,20 @@ namespace mlirgen
17921882
expression = builder.create<mlir_ts::CastOp>(location, baseType, expression);
17931883
}
17941884
}
1885+
// `x[1]` of a union of tuples (`[number, string] | [number, string, string]`), each holding that element after
1886+
// the same elements: it is where the first member has it, whichever member the value holds (it was "access
1887+
// expression is not applicable")
1888+
else if (auto firstTuple = unionTuplesCommonPrefixMember(unionType, argumentExpression))
1889+
{
1890+
expression = builder.create<mlir_ts::GetValueFromUnionOp>(location, firstTuple, expression);
1891+
arrayType = firstTuple;
1892+
}
1893+
// `x[i]` of a run-time index: the element of the member the value holds (a value, as above: not a place
1894+
// to assign to)
1895+
else if (auto element = mlirGenUnionOfTuplesElementAt(location, expression, unionType, argumentExpression, genContext))
1896+
{
1897+
return *element;
1898+
}
17951899
}
17961900

17971901
if (isa<mlir_ts::LiteralType>(arrayType))
@@ -4119,12 +4223,21 @@ namespace mlirgen
41194223
mlir::Type MLIRGenImpl::instantiatedDictionaryType(mlir::Location location, mlir::Type type, const GenContext &genContext)
41204224
{
41214225
auto classInfo = dictionaryClassInfoOf(type, genContext);
4122-
if (!classInfo || classInfo->typeParamsWithArgs.size() != 1)
4226+
auto genericClassInfo = classInfo ? getGenericClassInfoByFullName(OBJECT_DICTIONARY_CLASS_NAME) : GenericClassInfo::TypePtr();
4227+
if (!genericClassInfo || genericClassInfo->typeParams.size() != 1)
41234228
{
41244229
return type;
41254230
}
41264231

4127-
auto valueType = std::get<1>(classInfo->typeParamsWithArgs.begin()->getValue());
4232+
// its value type, by the name of the class's type parameter: one instantiated inside a generic alias
4233+
// (`Record<string, T>`, the mapped type `{ [P in K]: T }`) carries the alias's type arguments as well
4234+
auto found = classInfo->typeParamsWithArgs.find(genericClassInfo->typeParams.front()->getName());
4235+
if (found == classInfo->typeParamsWithArgs.end())
4236+
{
4237+
return type;
4238+
}
4239+
4240+
auto valueType = std::get<1>(found->getValue());
41284241
auto instantiated = getObjectDictionaryType(location, valueType, genContext);
41294242
return instantiated ? instantiated : type;
41304243
}
@@ -4191,6 +4304,11 @@ namespace mlirgen
41914304
ValueOrLogicalResult MLIRGenImpl::mlirGenDictionaryCall(mlir::Location location, mlir::Value dictionary, StringRef method,
41924305
SmallVector<mlir::Value, 4> &operands, const GenContext &genContext)
41934306
{
4307+
// a dictionary whose type was found in an earlier pass (`f(): Record<string, T>`: the alias is read once) may
4308+
// have had its members generated nowhere: instantiated here, as for an entry read ("'ts.Call' op
4309+
// 'ObjectDictionary<!ts.number>.keys' does not reference a valid function" of `Object.keys(f())`)
4310+
instantiatedDictionaryType(location, dictionary.getType(), genContext);
4311+
41944312
auto methodResult = mlirGenPropertyAccessExpression(location, dictionary, method, genContext);
41954313
EXIT_IF_FAILED_OR_NO_VALUE(methodResult)
41964314
return mlirGenCall(location, V(methodResult), operands, genContext);

0 commit comments

Comments
 (0)