diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 509e366a3..dca9ca990 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3477,7 +3477,8 @@ Tests `00tslang_issue_192.ts` (all models), `accessor_failed_getter_error.ts`, ` { method(a) { return a.length } }`): its parameter took the signature's `this` ("Can't resolve property 'length' of type Opaque"). Given to a union of such shapes told apart by a literal field (`{ kind: "a", method(a) {...} }`), the literal is typed by the member its literal fields name, and cast to it ("can't be stored"). Not yet: a - discriminant read from a module `const` (widened to string), a template literal or a missing one. + discriminant read from a module `const` (widened to string), a template literal or a missing one. (The module + `const` and the template literal work since 211; an exported `const` was the one widened.) - An array literal given to a union with a tuple in it (`f(["a"])` for `["a"] | I`): "can't be stored"; the union's array takes it. - A negated test narrowed neither branch: `if (!Array.isArray(d)) d.v`, `if (!(typeof d === "array"))`, `if (!(d @@ -3516,7 +3517,8 @@ Tests `00tslang_issue_193.ts` (all models), `00never_array_union.ts`, `00unknown - A function returning a union and then a value of one of its members: "failed statement" alone. Not yet: such a function returning a union and then a value of no member (`{ valid: true }` after a `U` of shapes with `msg`); reading a field some member has not (`v.msg` of `{ valid } | { valid; msg }`, an error in TypeScript) reads - the value as the first member that has it. + the value as the first member that has it. (Both settled in 211: the first works; the second reads the member the + value holds.) Tests `00tslang_issue_194.ts` (all models). @@ -3691,7 +3693,7 @@ Not yet: from elsewhere (`takeG({ produce: () => 44 }, 1.5)`): "can't assign '() => s32' to '() => number'", as is a literal variable given to the interface (`const o2: Options = t`). - `{ x: string } & any` is `never` ("'Never' can't be used as parameter type"); TypeScript has `any`. Making it `any` - sends `conditionalTypeDoesntSpinForever.ts` (tsc) into a loop, so it stays for now. + sends `conditionalTypeDoesntSpinForever.ts` (tsc) into a loop, so it stays for now. (Fixed in 211, no loop.) - The debug JIT crashes in LLVM translation on any program (local debug build, 11-26); release is fine. Tests `00tslang_issue_205.ts` and `00tslang_issue_205_this.ts` (gc, rc, none: under -mm=own the returned closure over a parameter is refused by design). @@ -3789,3 +3791,59 @@ unwind gives it back, 209); the empty slot was refused for a call taker before. after the moves stay at about 6 MB. Tests `00tslang_issue_210.ts` (all models). + +211. Leftovers of 193, 194 and 205, and old "still open" notes a triage re-ran (2026-11-27; repros and the full table +in the triage report). Fixed: +- 193: a discriminant read from an exported module `const` (`export const KA = "a"; run({ kind: KA, method(a) {...} })` + for a union told apart by `kind`): "can't be stored". An exported `const` is stored as a `let` (user ruling 09-13), + and its type was widened to `string` with it; never assigned, it keeps its string literal type, as in TypeScript. +- 194: `v.msg` of `{ valid } | { valid; msg }` read the value as the first member that has `msg`, whichever member it + was - past the end of a smaller one. It is read from the member the value holds, and is the type's empty value for + one that has not the field (TypeScript has `undefined`, and makes the read an error; tslang reads it where it is + narrowed in ways it does not follow yet - `switch (true)` clauses, a truthy discriminant - which tsc-clean tests do, so + making it an error failed three of them). `"msg" in v`, which tells the members apart, works for a union of object + shapes (it was "only a union of interfaces is"), narrowing as for interfaces. A function returning a union and then + a value of no member works already. +- 205: `{ x: string } & any` is `any` (`never & any` stays `never`, `X & unknown` is X). The tsc test that looped with + the first attempt (`conditionalTypeDoesntSpinForever.ts`) stops at once on an unrelated error. +- Under -mm=own, a variable holding a string converted to another object type (`const u = { n: 1, name: "x" + i }; + const p: { n: number; name: string } = u`, `n` an s32): "a value that borrows a field cannot be stored". The new + object takes a copy of each string read out of the source (strings are values), is built in a slot as an own literal + of new values is, and goes into a local of its own, so it can be stored, kept, or only read. Only when every other + field holding a block is new or constant: one with an object, a nested object or an optional string read out of the + source stays a borrow, refused where it is stored as before. 2M conversions stay at about 6 MB. +- 137: under -mm=own, `for (const o of [new A(), new B()])`: "an object literal that holds a value it owns is moved + only into a local". The literal goes into a local of its own, as `const items = [...]; for (const o of items)`. +- 152, -mm=own: an element stored past the end through a local over a parameter's array (`let src = order; src[n] = v`) + or through a handle's payload (`s.value[i] = v`) did not grow the array (deliberately, as -mm=own refuses the growth + there) and was written past the end of its block: a corrupted heap, crashing later. It is a RangeError now (an assert + without the default library); a store inside the array is unchanged. Not JavaScript's behaviour, which grows the + array: growing through such a local needs -mm=own to take it for a borrower of the parameter that changes it in place, + as it does for a field's (`const model = this.model; model.push(0)`, TSLANG 62) - a push through it is refused too. + +Not yet: +- Under -mm=own, `<{ code: number }>a` of an `any` holding `{ code: 7 }` (an s32 field) still throws. Each layout is a + cast of the `any` of its own, and -mm=own takes a named `any` cast to a tuple more than once for a second reference + of its box: `const c = a; const d = a` is refused as well, before this. +- `{ x: string } & T` of a generic function is `never` ("'Never' can't be used as parameter type"), even given T. + Leaving it to be resolved once T is given made inference fail elsewhere (`SetupImageRefs & {...}`, tsc + objectRestBindingContextualInference and others: "can't instantiate function"), so it was taken out again. +- 131 `Record` is a record of no fields (a warning), and a literal given to it loses its own. Made a + dictionary, as `{ [key: string]: number }` is, the tsc tests using `T extends Record` as a constraint + failed (an object literal does not meet a dictionary), so it was taken out again: it needs the constraint check to + take a literal for a dictionary. +- 140 overloads in a declared class: "redefinition of symbol named 'DC.constructor'" for constructors; an error for + every declared method overload failed tsc-clean tests whose method overloads compiled, so it was taken out. +- Still failing from the triage, not taken here: 132 a generic class given for a constructor type (`fruitFactory1(Banana)` + of `Banana`: "Can't find class Banana", T to be instantiated from its constraint); 152 a record + spread into a dictionary under -mm=own; 117 a primitive's method as a value (`let f = n.toFixed`); 131 `Object.keys` + of `object`, `Object.assign({a: 1}, {b: 2})`, `Object.defineProperty`, `Object.create`; 191 `x.slice(1) as readonly + string[]` and callable interfaces naming each other; 139 a constructor type of an interface; 140 `await` in + `finally`; 108 `class X extends k` of a `let`; the built-in `Symbol` as a value; recursive conditional types; the + tsc tests genericFunctionsAndConditionalInference and contextualParamTypeVsNestedReturnTypeInference1; and under + -mm=own 56 (a loop shape), 128 (a `for` body assigning its `let`), 144 (a closure capturing a later const holding a + closure), 164 (an interface narrowed to a class), 153 (an object sent by `next()`), 159 (`yield* this.range()`). + Design questions without a ruling: overloads of a declared function (136) and of a declared class's + constructor (140). + +Tests `00tslang_issue_211.ts` (all models), `own_grow_past_end_check.ts` (-mm=own). diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 0cd5c4cea..c074b3c7a 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -118,6 +118,9 @@ struct VariableClass StringRef dllName; // a module `const` the root's code stores once (WRITTEN_ONCE_GLOBAL_ATTR_NAME) bool writtenOnce = false; + // an exported module `const`, stored as a `let` (a global other modules read): never assigned, so it keeps the + // string literal type it is given (`export const KA = "a"` is `"a"`, as in TypeScript) + bool exportedConst = false; inline VariableClass& operator=(VariableType type_) { type = type_; return *this; } diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 29f500688..2f68a044e 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -409,8 +409,60 @@ namespace mlirgen SmallVector<::mlir::typescript::FieldInfo> fieldsForTuple; fieldsForTuple.append(fields.begin(), fields.end()); + + // -mm=own: a string read out of the source's fields (`const p: { n: number; name: string } = u`, where `u`'s + // `n` is an s32) is the source's, and the new tuple would hold a borrow of it: "a value that borrows a field + // cannot be stored". Strings are values: the new tuple takes a copy of each (TSLANG 211), is built in a slot, as an + // own tuple literal of new values is (createTupleInSlot), and goes into a local of its own (ownedTemporaryLocal), + // so it can be stored and moved, or only read (`take(u)` of a callee that borrows it). Another field that holds a + // block - an object, an array - cannot be copied, and stays a borrow, refused where it is stored. + // (not of a literal being made - a constant, a tuple just made (`[key, value]`), or one built in its slot + // 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) + 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)) + { + // 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 + auto isStringRead = [](mlir::Value value) { + return isa(value.getType()) + && isa_and_nonnull(value.getDefiningOp()); + }; + auto ownable = llvm::all_of(values, [&](mlir::Value value) { + return isStringRead(value) || !mth.ownsHeapMemory(location, value.getType()) + || own_facts::isConstantData(value) + || (value.getDefiningOp() && own_facts::isFresh(value) && !own_facts::isLiteral(value.getDefiningOp()) + && !mth.isAnyFunctionType(value.getType())); + }); + + auto copied = false; + for (auto &value : values) + { + if (ownable && isStringRead(value)) + { + auto copy = builder.create(location, value.getType(), value); + copy->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + value = copy; + copied = true; + } + } + + if (copied) + { + auto built = createTupleInSlot(location, fieldsForTuple, values, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(built) + return ownedTemporaryLocal(location, V(built), genContext); + } + } + return V(builder.create(location, getTupleType(fieldsForTuple), values)); - } + } ValueOrLogicalResult MLIRGenImpl::NewClassInstanceWithSettingFields(mlir::Location location, mlir_ts::ClassType classType, ArrayRef fields, ArrayRef values, const GenContext &genContext) @@ -5485,8 +5537,8 @@ namespace mlirgen } } - // (not under -mm=own: a value merged from the branches is a second reference it can't classify yet, and the - // plain read is refused with it) + // (not under -mm=own: each layout is a cast of the `any` of its own, and -mm=own takes a named `any` cast to a + // tuple more than once for a second reference of its box - `const c = a; const d = a` is refused as well) if (numberFields.empty() || numberFields.size() > 3 || compileOptions.memoryModel == MemoryModelOwn) { return castAnyToTuple(location, type, value, genContext); diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index c20f0e5b5..705918f66 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -6996,10 +6996,26 @@ genContext); std::stable_sort(members.begin(), members.end(), [&](mlir::Type a, mlir::Type b) { return depthOf(a) > depthOf(b); }); + // a field some shapes have and another has not (`v.msg` of `{ valid } | { valid; msg }`, read where the value is + // narrowed to one that has it in ways not followed here - `switch (true)` clauses, a truthy discriminant): read + // from the members that have it, and the type's empty value for one that has not (TypeScript has `undefined`). + // It was read as the first member that has it, whichever the value was: past the end of a smaller one (TSLANG 194) + auto hasField = [&](mlir::Type member) { + auto tuple = dyn_cast(member); + return !tuple || tuple.getIndex(nameAttr) >= 0; + }; + auto someLack = llvm::any_of(members, [&](mlir::Type member) { return !hasField(member); }) + && llvm::any_of(members, [&](mlir::Type member) { return isa(member) && hasField(member); }); + // the field's type in each member: a field every member has, not a method SmallVector fieldTypes; for (auto member : members) { + if (someLack && !hasField(member)) + { + continue; + } + auto memberValue = builder.create(location, member, unionValue); auto fieldType = evaluateProperty(location, memberValue, name.str(), genContext); // (nor an array method of a tuple, `x.slice(1)` of `[number, string] | [number, string, string]`: an @@ -7030,6 +7046,11 @@ genContext); }; auto readOfMember = [&](mlir::Type member) -> ValueOrLogicalResult { + if (someLack && !hasField(member)) + { + return V(builder.create(location, resultType)); + } + auto memberValue = builder.create(location, member, unionValue); auto value = mlirGenPropertyAccessExpression(location, memberValue, name, false, genContext); EXIT_IF_FAILED_OR_NO_VALUE(value) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 81569010b..c15747f2c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3026,6 +3026,16 @@ class MLIRGenImpl auto actualType = variableDeclarationInfo.typeProvided == TypeProvided::Yes ? type : mth.wideStorageType(type); + // an exported `const` is stored as a `let` but never assigned: a string literal keeps its literal type, as in + // TypeScript - `{ kind: KA, method(a) {...} }` for a union told apart by `kind` picks the member it names (TSLANG 193) + if (variableDeclarationInfo.varClass.exportedConst && variableDeclarationInfo.typeProvided != TypeProvided::Yes) + { + if (auto literalType = dyn_cast(type); literalType && isa(literalType.getElementType())) + { + actualType = type; + } + } + // A global other modules reach holds a function the way a local `let` does // (adjustLocalVariableType): as a hybrid function. Its declaration in __decls, // `let f : (p0: number) => number`, reads back as one, so a library inferring a plain @@ -8637,6 +8647,18 @@ class MLIRGenImpl for (auto member : unionType.getTypes()) { + // ...or an object shape (`"msg" in v` of `{ valid } | { valid; msg }`), told apart by the tag too: it has the + // key when it has the field (TSLANG 194) + if (auto tupleType = dyn_cast(member)) + { + if (tupleType.getIndex(key) >= 0) + { + withKey.push_back(member); + } + + continue; + } + auto interfaceType = dyn_cast(member); if (!interfaceType) { @@ -9997,7 +10019,7 @@ class MLIRGenImpl mlir::Value heldArray; if (auto elementRefOp = storeReference.getDefiningOp()) { - heldArray = mlirGenGrowArrayForWrite(location, elementRefOp); + heldArray = mlirGenGrowArrayForWrite(location, elementRefOp, genContext); storeReference = builder.clone(*elementRefOp)->getResult(0); } @@ -14769,9 +14791,7 @@ class MLIRGenImpl mlir::Value ownedLiteralArgument(mlir::Location location, Expression expression, mlir::Value value, const GenContext &genContext) { - if (compileOptions.memoryModel != MemoryModelOwn || genContext.ownedVars == nullptr - || genContext.generatorSwitchOperation - || (genContext.allocateScopeOwnedVarsOutsideOfOperation && !genContext.currentOperation)) + if (!canMakeOwnedTemporaryLocal(genContext)) { return value; } @@ -14843,17 +14863,39 @@ class MLIRGenImpl return value; } - // ...and not inside an expression (`a && k.keep([...])`, `c ? k.keep([...]) : 0`): a local made in its region does - // not reach the scope's end, where it is given back + return ownedTemporaryLocal(location, value, genContext); + } + + // -mm=own: can a value made here go into an owned local of its own (ownedTemporaryLocal)? A scope that owns + // locals, not a generator's (whose locals are fields of its object), and not inside an expression (`a && k.keep(...)`, + // `c ? k.keep(...) : 0`): a local made in its region does not reach the scope's end, where it is given back + bool canMakeOwnedTemporaryLocal(const GenContext &genContext) + { + if (compileOptions.memoryModel != MemoryModelOwn || genContext.ownedVars == nullptr + || genContext.generatorSwitchOperation + || (genContext.allocateScopeOwnedVarsOutsideOfOperation && !genContext.currentOperation)) + { + return false; + } + for (auto *parentOp = builder.getInsertionBlock()->getParentOp(); parentOp && !isa(parentOp); parentOp = parentOp->getParentOp()) { if (parentOp->getNumResults() > 0) { - return value; + return false; } } + return true; + } + + // -mm=own: `value` put into an owned local of its own, as `const t = value` puts it, and read back: the local owns + // it, moves it into what keeps it as its last use, and gives it back at the end of its scope otherwise. Directly in a + // `try` body the local is made in front of the `try` and given the value by a store, as a declared one is + // (createLocalVariable), so the cleanup sees it. Only where canMakeOwnedTemporaryLocal says. + mlir::Value ownedTemporaryLocal(mlir::Location location, mlir::Value value, const GenContext &genContext) + { mlir_ts::VariableOp localOp; if (genContext.allocateScopeOwnedVarsOutsideOfOperation) { @@ -22353,7 +22395,8 @@ class MLIRGenImpl // Under -mm=rc, the array the left side read when the right side may give its place another one: retained // until the store, which releases it (the caller) - else the right side's store released it, and the write // and the growth went into a freed block. - mlir::Value mlirGenGrowArrayForWrite(mlir::Location location, mlir_ts::ElementRefOp elementRefOp) + mlir::Value mlirGenGrowArrayForWrite(mlir::Location location, mlir_ts::ElementRefOp elementRefOp, + const GenContext &genContext) { auto array = elementRefOp.getArray(); if (!isa(array.getType())) @@ -22438,6 +22481,24 @@ class MLIRGenImpl // read this as a push (growsOnly). if (compileOptions.memoryModel == MemoryModelOwn) { + // ...but the store is checked where the array cannot grow (TSLANG 152): past its end it was written past the + // end of the block, and the heap was corrupted. A RangeError there, which JavaScript does not throw (it + // grows the array): -mm=own does not grow an array through these yet + auto checkInside = [&]() -> mlir::Value { + auto length = builder.create(location, builder.getIndexType(), array); + auto length32 = builder.create(location, i32Type, length); + auto inside = builder.create( + location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::LessThanToken), index32, length32); + if (mlir::failed(mlirGenRangeCheck(location, inside, + "-mm=own does not grow an array here: an element stored past its end", + genContext))) + { + return mlir::Value(); + } + + return held; + }; + // Not through a local over a parameter's array (`let src = order; src[i] = v`): changed in place through // it - a push too - the local owns what it holds, and the parameter is kept, which the callers can't be // made to give up; every write through it, past the end or not, was refused. As before there (TSLANG 152). @@ -22446,7 +22507,7 @@ class MLIRGenImpl if (auto loadOp = varOp->getOperand(0).getDefiningOp(); loadOp && loadOp.getReference().getDefiningOp()) { - return held; + return checkInside(); } } @@ -22455,7 +22516,7 @@ class MLIRGenImpl // element would be taken for one that releases what its callers borrow. As before there. if (own_facts::reachesSharedValue(arrayRef)) { - return held; + return checkInside(); } auto one = builder.create(location, i32Type, builder.getI32IntegerAttr(1)); diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index d19af4122..a0c87b423 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -2224,7 +2224,24 @@ namespace mlirgen EXIT_IF_FAILED_OR_NO_VALUE(result) auto exprValue = V(result); - auto skip = isa(exprValue.getType()) + // -mm=own: a literal iterated straight (`for (const o of [new A(), new B()])`, a tuple built in its slot) is held by + // a local of its own, as `const items = [...]; for (const o of items)` holds it: read from its slot, it held the + // objects it was given and nothing owned it ("an object literal that holds a value it owns is moved only into a + // local", TSLANG 137) + if (compileOptions.memoryModel == MemoryModelOwn && stripParentheses(forOfStatementAST->expression) == SyntaxKind::ArrayLiteralExpression + && isa(exprValue.getType()) && mth.ownsHeapMemory(location, exprValue.getType()) + && canMakeOwnedTemporaryLocal(genContext)) + { + auto loadOp = exprValue.getDefiningOp(); + auto slotOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (slotOp && !slotOp->hasAttr(OWNED_LOCAL_ATTR_NAME) && slotOp.getInitializer() + && slotOp.getInitializer().getDefiningOp()) + { + exprValue = ownedTemporaryLocal(location, exprValue, genContext); + } + } + + 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 if (!skip) diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index a5a53dfee..6b48a0f55 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -3667,6 +3667,7 @@ namespace mlirgen mlir::SmallVector typesForUnion; auto allTupleTypesConst = true; auto unionTypes = false; + auto anyWritten = false; for (auto typeItem : intersectionTypeNode->types) { // an interface of one call signature is that signature's function type (callSignatureOnlyType), but with @@ -3706,6 +3707,23 @@ namespace mlirgen } types.push_back(type); + anyWritten |= typeItem == SyntaxKind::AnyKeyword; + } + + // `X & any` is `any` (`never & any` stays `never`), and `X & unknown` is X, as in TypeScript: it was `never` ("'Never' + // can't be used as parameter type", TSLANG 205). Only `any` written here: a type parameter standing for `any` while + // a call's arguments are inferred (`T & ((arg: string) => any)`) leaves the other members to infer from + if (llvm::none_of(types, [](mlir::Type type) { return isa(type); })) + { + if (anyWritten) + { + return getAnyType(); + } + + if (llvm::any_of(types, [](mlir::Type type) { return !isa(type); })) + { + llvm::erase_if(types, [](mlir::Type type) { return isa(type); }); + } } if (types.size() == 0) diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index 9283b4d8f..157846447 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -1870,6 +1870,7 @@ namespace mlirgen && (!genContext.funcOp || genContext.rootFunctionConst && genContext.funcOp == genContext.rootStatementsFuncOp)) { itemVarClass.type = VariableType::Let; + itemVarClass.exportedConst = true; } // a `var` in a function belongs to the function (MDN `var`): declared before the body, assigned here diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 8c944b5b9..f8265b47e 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2570,6 +2570,19 @@ foreach(issue210_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_210-${issue210_mm} COMMAND test-runner -jit -mm=${issue210_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_210.ts") tslang_add_test(NAME test-compile-00tslang_issue_210-${issue210_mm} COMMAND test-runner -mm=${issue210_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_210.ts") endforeach() +# TSLANG 211: leftovers of 193, 194, 205 and old notes (137 for...of a literal, own conversions) +foreach(issue211_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_211-${issue211_mm} COMMAND test-runner -jit -mm=${issue211_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_211.ts") + tslang_add_test(NAME test-compile-00tslang_issue_211-${issue211_mm} COMMAND test-runner -mm=${issue211_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_211.ts") +endforeach() +# TSLANG 152, -mm=own: a store past the end through a parameter's alias stops with a check, not a write past the block +add_test(NAME test-jit-own-grow-past-end-check + COMMAND $ --emit=jit --no-default-lib -mm=own + --shared-libs=$ + "${PROJECT_SOURCE_DIR}/test/tester/tests/own_grow_past_end_check.ts") +set_tests_properties(test-jit-own-grow-past-end-check + PROPERTIES PASS_REGULAR_EXPRESSION "inside done.*assertion failed: -mm=own does not grow an array here" + FAIL_REGULAR_EXPRESSION "Stack dump|Exception Code|PLEASE submit|unreachable") # the array `splice` gives back, kept in a local and returned: under rc its header is born owned (it was freed on # the way out) foreach(splice_mm gc rc none) diff --git a/tslang/test/tester/tests/00tslang_issue_211.ts b/tslang/test/tester/tests/00tslang_issue_211.ts new file mode 100644 index 000000000..8b6bebd4a --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_211.ts @@ -0,0 +1,108 @@ +// TSLANG 211, every model: leftovers of 193, 194, 205 and old "still open" notes (137, own conversions). + +// 193: a discriminant read from an exported module `const` (stored as a `let`, user ruling) kept its string literal +// type only as a string, and a literal told apart by it matched no member ("can't be stored") +type KindA = { kind: "a"; method(x: string): number }; +type KindB = { kind: "b"; method(x: number): number }; +export const KA = "a"; + +function run(o: KindA | KindB) { + return o.kind == "a" ? o.method("xyz") : o.method(5); +} + +// 194: `"msg" in v` of a union of object shapes (it was "only a union of interfaces is"), and `v.msg` read from the +// member the value holds (it was read as the first member that has it, past the end of a smaller one) +type Validated = { valid: boolean } | { valid: boolean; msg: string }; + +function makeValidated(b: boolean): Validated { + if (b) { + return { valid: true }; + } + + return { valid: false, msg: "m" + 1 }; +} + +function msgOf(v: Validated) { + if ("msg" in v) { + return v.msg; + } + + return "none"; +} + +// 205: `X & any` is `any` (it was `never`) +type WithAny = { x: string } & any; + +function passAny(w: WithAny) { + return w; +} + +// own: a variable holding a string converted to another object type (`n` an s32 for a number), stored, read by a +// callee and kept by one +function nameLength(p: { n: number; name: string }) { + return p.name.length + p.n; +} + +class Keeper { + all: { n: number; name: string }[] = []; + + keep(p: { n: number; name: string }) { + this.all.push(p); + } +} + +function converted(i: number) { + const u = { n: i, name: "m" + i }; + const p: { n: number; name: string } = u; + return p; +} + +class ObjA { + constructor(public k: number) {} + + n(): number { + return 1 + this.k; + } +} + +class ObjB { + constructor(public s: string) {} + + n(): number { + return this.s.length; + } +} + +function main() { + assert(run({ kind: KA, method(a) { return a.length; } }) == 3, "exported const discriminant"); + + assert(msgOf(makeValidated(false)) == "m1" && msgOf(makeValidated(true)) == "none", "in of shapes"); + const withMsg: Validated = makeValidated(false); + assert(withMsg.valid == false, "a field every member has"); + + const anyValue: any = { x: "s" }; + passAny(anyValue); + + const k = new Keeper(); + let total: number = 0; + for (let i = 0; i < 3; i++) { + const u = { n: i, name: "x" + i }; + const p: { n: number; name: string } = u; + total += p.name.length; + total += nameLength(u); + k.keep(u); + assert(u.name == "x" + i, "source kept its string"); + } + + assert(total == 15 && k.all.length == 3 && k.all[2].name == "x2" && converted(4).name == "m4", "conversion"); + + // 137: for...of straight over a literal of objects (under -mm=own "moved only into a local") + let s: number = 0; + for (let i = 0; i < 3; i++) { + for (const o of [new ObjA(i), new ObjB("b" + i)]) s += o.n(); + } + + assert(s == 12, "for of literal"); + + print("done."); +} diff --git a/tslang/test/tester/tests/own_grow_past_end_check.ts b/tslang/test/tester/tests/own_grow_past_end_check.ts new file mode 100644 index 000000000..3d25c83a3 --- /dev/null +++ b/tslang/test/tester/tests/own_grow_past_end_check.ts @@ -0,0 +1,16 @@ +// TSLANG 152, -mm=own: an element stored past the end through a local over a parameter's array (`let src = order; +// src[n] = v`) is not grown under -mm=own yet; it was written past the end of the block (a corrupted heap). Now a +// RangeError (an assert without the default library); a store inside the array is unchanged. +function fill(order: number[], n: number) { + let src = order; + src[n] = 7; +} + +function main() { + const a: number[] = [1, 2]; + fill(a, 1); + assert(a[1] == 7, "inside"); + print("inside done."); + fill(a, 3); + print("unreachable"); +}