diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index faea9f2bf..6ab2de396 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3708,3 +3708,60 @@ array_class_splice.ts crashing in the debug JIT on Ubuntu 22.04/24.04 with no ou Tests `00rc_splice_result_owned.ts` (gc, rc, none; under own the test's re-insertion of the removed elements is refused). + +207. Leftovers of 195, 196, 198 and 205. Fixed: +- A literal given to a generic call whose function member returns an integer, where the type parameter is a number + from another argument (`takeG({ produce: () => 44 }, 1.5)` for `takeG(o: Options, d: D)`): "can't assign + '() => s32' to '() => number'", and with the arguments the other way round `D` was `1.5 | s32`. The literal is typed + by the parameter once the call's other arguments give D (inferObjectLiteralArgumentReceivers, as a literal whose + members' parameters wait for D already was); its members are read one by one for the inference, without making them - + a member made then kept the `() => s32` it was made with. +- An `any` holding an object literal written with integers (`{ code: 7 }`, an s32 field) cast to an object type of + numbers (`<{ code: number }>a`): it threw "the object's fields are not those of type". A layout with s32 in place of + some of the number fields (three at most) is read as itself and converted (castAnyToTupleOfNumbers). Not under + -mm=own, where the value merged from those reads is a second reference: there the cast still throws. +- Under -mm=own, an object literal leaving out an optional field of the tuple it is given to (`const o: { disc?: false; + cb } = { cb }`): "a value that borrows a field cannot be stored". The literal is made with the missing optional + fields, undefined, and so is the receiver's tuple as it is, where it was converted by reading its fields out of its + slot. +- The rest of a `T | null` (`const { a, ...rest } = u`, and `({ a, ...rest } = u)`): "the rest of a value of type + 'null | T' can't be taken". It is T's, read as the pattern's other names read T's fields. + +Not yet (both fixed in 208): +- Under -mm=own, a tuple literal given to a callee that keeps it (`k.keepOne(["a" + i, i])`): "this function does not + own it". The same tuple in a local first (`const t: [string, number] = ["a" + i, i]; k.keepOne(t)`) works. +- A literal held by a variable first (`const t = { produce: () => 45 }; const o: Options = t`): `t`'s member is + `() => s32`, which is not `() => number` (integer literals are s32, user ruling). + +Tests `00tslang_issue_207.ts` (all models) and `00tslang_issue_207_any.ts` (gc, rc, none). + +208. The "not yet" of 207. Fixed: +- A literal held by a variable first, whose function member returns an integer, given as an interface whose member + returns a number (`const t = { produce: () => 45 }; const o: Options = t`, a `let` as well, and + `readOptions(t)` for a parameter `o: Options`): "field "produce" not matching type: '() => number' and + '() => s32'". Integer literals stay s32 (user ruling); the function is adapted, as it already was given as a + `() => number` value (`let f: () => number = one`). The interface's slot calls the field through a thunk, as it calls + a closure field, and the thunk converts the result (isResultWideningFieldFunction): the object is given as it is, + with no copy, and no box for -mm=own to refuse. Where the object is copied for another field, the copy keeps the + function as it is for the same thunk; a field of a constant object read as a function value is its function, named + (fewerParametersThunk). +- Under -mm=own, a tuple or object literal given to a callee that keeps it (`k.keepOne(["a" + i, i])`, + `k.keepObj({ s: "b" + i, n: i })`): "this function does not own it". The literal is built in a slot nothing owns; as + an argument it now goes into a local of its own, as `const t = [...]; k.keepOne(t)` puts it (ownedLiteralArgument): + the local gives it to a callee that keeps it, and gives it back where the callee only reads it. 2M calls of either + stay at about 5 MB. Only a literal of new values or string constants (one holding what it borrows, or a closure, is a + borrowing record, as it was), and not inside `&&`/`?:`, whose region does not reach the scope's end. +- Under -mm=own, the same directly in a `try` body, and a declared local there (`try { const t = ["u" + n, 1]; + k.keepOne(t); }`): "an object literal that holds a value it owns is moved only into a local". The local is made in + front of the `try` and given its value by a store right before its retain; that retain is now the literal's, as an + initializer's is (recordRetainOf). + +Not yet: +- Under -mm=own, a value moved in a `try` body that other statements of the body can throw before + (`try { f(); const t = ["b" + i, i]; k.keepOne(t); g(); }`): "moved here on some paths only". The unwind leg reached + before the local is given its value is not known to find it empty. One statement per `try`, or a loop in it, works. +- Under -mm=own, a callee that keeps a parameter and throws before keeping it (`keep(c) { if (...) throw "no"; + this.items.push(c); }`) leaks the parameter: 1M throws of `k.keep(new C(i))` grow to about 60 MB. Not new here (a + class instance leaks the same way); the callee's unwind does not give back a kept parameter. + +Tests `00tslang_issue_208.ts` (all models). diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index 676dfc94a..5184984c3 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -1383,6 +1383,32 @@ class MLIRTypeHelper return false; } + // A function field without `this` (isObjectFieldFunctionWithoutThis) whose result is an integer where the + // interface's member returns a number (`{ produce: () => 45 }`, a `() => s32`, for `produce: () => number`): the + // slot's thunk calls it and converts the result (generateSynthMethodToCallField), as it calls a closure field. The + // parameters have to match (TSLANG 208) + bool isResultWideningFieldFunction(mlir::Location location, mlir::Type fieldType, mlir::Type memberType) + { + if (!isObjectFieldFunctionWithoutThis(fieldType) || isa(fieldType)) + { + return false; + } + + auto srcType = GetFunctionType(fieldType); + auto destType = dyn_cast(memberType); + if (!srcType || !destType || srcType.getNumResults() != 1 || destType.getNumResults() != 1 + || !isa(srcType.getResult(0)) || !isa(destType.getResult(0))) + { + return false; + } + + // the field as if it returned the member's number: then it has to match + mlir::Type aligned = isa(fieldType) + ? mlir::Type(mlir_ts::HybridFunctionType::get(context, srcType.getInputs(), destType.getResults(), srcType.isVarArg())) + : mlir::Type(mlir_ts::FunctionType::get(context, srcType.getInputs(), destType.getResults(), srcType.isVarArg())); + return TestFunctionTypesMatchWithObjectMethods(location, aligned, memberType).result == MatchResultType::Match; + } + // An object-literal method (`this` first) an interface's function member can call through a thunk that gives // it as many arguments as it takes: it takes fewer parameters than the member (`next()` for `next(value?)`, // the rest ignored, as JavaScript does), or more, each of them optional (`next(value?)` for `next()`). The @@ -1722,7 +1748,8 @@ class MLIRTypeHelper if (isa(fieldType) && fieldType != foundField.type && isObjectFieldFunctionWithoutThis(foundField.type)) { - if (TestFunctionTypesMatchWithObjectMethods(location, foundField.type, fieldType).result == MatchResultType::Match) + if (TestFunctionTypesMatchWithObjectMethods(location, foundField.type, fieldType).result == MatchResultType::Match + || isResultWideningFieldFunction(location, foundField.type, fieldType)) { return {mlir_ts::FieldInfo{id, fieldType, false, mlir_ts::AccessLevel::Public}, mlir::success()}; } diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index e96968f00..29f500688 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -60,9 +60,14 @@ namespace mlirgen // (a closure, see MLIRTypeHelper::isObjectFieldFunctionWithoutThis) keeps its // own type: cast to the interface's it would lose its captures. Its slot calls a // thunk reading the field instead (mlirGenObjectVirtualTableDefinitionForInterface). + // ...unless its type is not the member's, nor one the slot's thunk converts (`matches` says: an s32 result for a + // number, isResultWideningFieldFunction, TSLANG 208). Then the clone's field is a function value of the member's + // type, without its `this` (a type literal's field, as `{ produce: () => number }` has), which the cast into the + // clone adapts the function to (fewerParametersThunk, functionValueAdapter). static mlir::LogicalResult getInterfaceCloneFields(mlir::ArrayRef srcFields, InterfaceInfo::TypePtr interfaceInfo, mlir::MLIRContext *context, - SmallVector &fields) + SmallVector &fields, + llvm::function_ref matches) { // an interface not declared (yet) has no fields to clone if (!interfaceInfo) @@ -84,6 +89,21 @@ namespace mlirgen auto keepsOwnType = interfaceField != interfaceFields.end() && isa(interfaceField->type) && MLIRTypeHelper::isObjectFieldFunctionWithoutThis(origField.type); + if (keepsOwnType && !matches(origField.type, interfaceField->type)) + { + auto memberType = cast(interfaceField->type); + mlir::ArrayRef inputs = memberType.getInputs(); + if (!inputs.empty() && isa(inputs.front())) + { + inputs = inputs.drop_front(); + } + + auto valueType = + mlir_ts::HybridFunctionType::get(context, inputs, memberType.getResults(), memberType.isVarArg()); + fields.push_back(mlir_ts::FieldInfo{origField.id, valueType, origField.isConditional, origField.accessLevel}); + continue; + } + fields.push_back(interfaceField != interfaceFields.end() && !keepsOwnType ? *interfaceField : origField); } @@ -3703,7 +3723,7 @@ namespace mlirgen if (isa(type) && !genContext.allowPartialResolve) { - return castAnyToTuple(location, type, value, genContext); + return castAnyToTupleOfNumbers(location, type, value, genContext); } // a union of object shapes (`a`): the shape whose layout the box's tuple has, the last @@ -4124,6 +4144,32 @@ namespace mlirgen mlir::Value MLIRGenImpl::fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type, const GenContext &genContext) { + // a field of a constant object (`const t = { produce: () => 45 }` folds to a constant of the functions' + // names) is that function, named (TSLANG 208): read as a value, it would be boxed (functionValueAdapter), + // which -mm=own takes for a second reference of the box where the object holding it is stored + if (auto extractOp = value.getDefiningOp(); extractOp && extractOp.getPosition().size() == 1) + { + if (auto constantOp = extractOp.getObject().getDefiningOp()) + { + auto elements = dyn_cast(constantOp.getValue()); + auto position = extractOp.getPosition().front(); + auto symbol = elements && position >= 0 && position < (int64_t)elements.size() + ? dyn_cast(elements[position]) + : mlir::FlatSymbolRefAttr(); + if (symbol && isa(value.getType())) + { + auto symbolValue = builder.create(location, value.getType(), symbol); + if (auto thunk = fewerParametersThunk(location, symbolValue, type, genContext)) + { + return thunk; + } + + symbolValue->erase(); + return mlir::Value(); + } + } + } + auto boundOp = value.getDefiningOp(); auto symbolRefOp = boundOp ? boundOp.getFunc().getDefiningOp() : value.getDefiningOp(); @@ -5418,6 +5464,85 @@ namespace mlirgen return V(builder.create(location, type, value)); } + // `any` to an object type with number fields (`<{ code: number }>a`): an object literal boxed as it is holds the s32 + // of an integer it was written with (`{ code: 7 }`), a layout of its own, and the cast threw "the object's fields + // are not those of type". Each layout with s32 in place of some of the number fields (three of them at most) is + // read as itself and converted, as the literal given to the type is. Anything else is castAnyToTuple's, and so is + // every cast under -mm=own. + ValueOrLogicalResult MLIRGenImpl::castAnyToTupleOfNumbers(mlir::Location location, mlir::Type type, mlir::Value value, + const GenContext &genContext) + { + auto tupleType = dyn_cast(type); + SmallVector numberFields; + if (tupleType) + { + for (auto [index, field] : enumerate(tupleType.getFields())) + { + if (isa(field.type)) + { + numberFields.push_back(index); + } + } + } + + // (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) + if (numberFields.empty() || numberFields.size() > 3 || compileOptions.memoryModel == MemoryModelOwn) + { + return castAnyToTuple(location, type, value, genContext); + } + + // the type's own layout first: it is the one a value of the type has + SmallVector layouts{type}; + auto s32Type = builder.getIntegerType(32, true); + for (unsigned mask = 1; mask < (1u << numberFields.size()); ++mask) + { + SmallVector fields(tupleType.getFields().begin(), tupleType.getFields().end()); + for (auto [bit, fieldIndex] : enumerate(numberFields)) + { + if (mask & (1u << bit)) + { + fields[fieldIndex].type = s32Type; + } + } + + layouts.push_back(getTupleType(fields)); + } + + std::function castOf = [&](size_t index) -> ValueOrLogicalResult { + if (index == layouts.size()) + { + // none of them: the checked read, which says what the box holds + return castAnyToTuple(location, type, value, genContext); + } + + auto holds = builder.create(location, getBooleanType(), value, + mlir::TypeAttr::get(layouts[index])); + auto ifOp = builder.create(location, mlir::TypeRange{type}, holds, true); + + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + mlir::Value thenValue = builder.create(location, layouts[index], value); + if (index > 0) + { + auto converted = cast(location, type, thenValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(converted) + thenValue = V(converted); + } + + builder.create(location, mlir::ValueRange{thenValue}); + + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + auto elseValue = castOf(index + 1); + EXIT_IF_FAILED_OR_NO_VALUE(elseValue) + builder.create(location, mlir::ValueRange{V(elseValue)}); + + builder.setInsertionPointAfter(ifOp); + return V(ifOp.getResults().front()); + }; + + return castOf(0); + } + ValueOrLogicalResult MLIRGenImpl::castAnyToUnionOfTuples(mlir::Location location, mlir_ts::UnionType unionType, mlir::Value value, const GenContext &genContext) { @@ -6002,7 +6127,11 @@ namespace mlirgen if (mlir::failed(mth.canCastTupleToInterface(location, srcTuple, interfaceInfo, true))) { SmallVector fields; - if (mlir::failed(getInterfaceCloneFields(srcTuple.getFields(), interfaceInfo, builder.getContext(), fields))) + if (mlir::failed(getInterfaceCloneFields(srcTuple.getFields(), interfaceInfo, builder.getContext(), fields, + [&](mlir::Type src, mlir::Type dest) { + return mth.TestFunctionTypesMatchWithObjectMethods(location, src, dest).result == MatchResultType::Match + || mth.isResultWideningFieldFunction(location, src, dest); + }))) { return mlir::failure(); } @@ -6130,7 +6259,11 @@ namespace mlirgen if (mlir::failed(mth.canCastTupleToInterface(location, storageTuple, interfaceInfo, true))) { SmallVector fields; - if (mlir::failed(getInterfaceCloneFields(storageTuple.getFields(), interfaceInfo, builder.getContext(), fields))) + if (mlir::failed(getInterfaceCloneFields(storageTuple.getFields(), interfaceInfo, builder.getContext(), fields, + [&](mlir::Type src, mlir::Type dest) { + return mth.TestFunctionTypesMatchWithObjectMethods(location, src, dest).result == MatchResultType::Match + || mth.isResultWideningFieldFunction(location, src, dest); + }))) { return mlir::failure(); } diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index d6b79dc9a..5be8e82f1 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -2655,6 +2655,37 @@ namespace mlirgen return llvm::any_of(expression.as()->properties, isContextSensitiveMember); } + // ...or one with a function member whose result is not declared (`{ produce: () => 44 }`): made on its own it + // returns the s32 of its integer, while the parameter it is given to may be `() => number` once the call's other + // arguments give the type parameter a number (`takeG({ produce: () => 44 }, 1.5)` was "can't assign '() => s32' + // to '() => number'"). Typed by its receiver, it returns what the receiver says, as it does for a known type. + static bool isResultInferredMember(ObjectLiteralElementLike item) + { + if (item != SyntaxKind::PropertyAssignment) + { + return false; + } + + auto initializer = item.as()->initializer; + if (initializer != SyntaxKind::ArrowFunction && initializer != SyntaxKind::FunctionExpression) + { + return false; + } + + return !initializer.as()->type; + } + + static bool isReceiverTypedObjectLiteral(Expression expression) + { + if (expression != SyntaxKind::ObjectLiteralExpression) + { + return false; + } + + return isContextSensitiveObjectLiteral(expression) + || llvm::any_of(expression.as()->properties, isResultInferredMember); + } + // A generic call with such a literal for an argument: `foo({ read: () => s, write: value => s = value })` for // `foo(x: Computed)`. The members' parameters are of T, which the rest of the call gives - the other // arguments, and the literal's other members. Inferred from their types first (no code is made), the @@ -2667,7 +2698,7 @@ namespace mlirgen { auto symbolOp = funcResult.getDefiningOp(); if (!symbolOp || !symbolOp->hasAttrOfType(GENERIC_ATTR_NAME) - || llvm::none_of(arguments, isContextSensitiveObjectLiteral) || !genContext.postponedMessages) + || llvm::none_of(arguments, isReceiverTypedObjectLiteral) || !genContext.postponedMessages) { return; } @@ -2706,7 +2737,10 @@ namespace mlirgen continue; } - if (!isContextSensitiveObjectLiteral(argument)) + // (not a literal with a function member whose result is not declared: evaluating it makes the function, + // whose type - the `() => s32` of `() => 44` - then stays the function's when the literal is made for + // its receiver; its members are read one by one below, without making them) + if (!isReceiverTypedObjectLiteral(argument)) { // widened, as an inference from a literal is (`5` gives s32, not the literal type 5) if (auto type = evaluate(argument, genContext)) @@ -2803,7 +2837,7 @@ namespace mlirgen for (auto [index, argument] : enumerate(arguments)) { if (index >= declarationParams.size() || !declarationParams[index]->type - || !isContextSensitiveObjectLiteral(argument)) + || !isReceiverTypedObjectLiteral(argument)) { continue; } @@ -4467,6 +4501,36 @@ namespace mlirgen return *earlyResult; } + // A tuple receiver's optional fields the literal leaves out (`const o: { disc?: false; cb: Cb } = { cb }`) are + // its own, undefined, when it has every other one: it is then laid out as the receiver below and is the value. + // Built without them, it was converted by reading its fields out of its slot into a new tuple - under -mm=own + // a borrow of the slot, which can't be stored ("a value that borrows a field cannot be stored"). + if (auto receiverTuple = dyn_cast_or_null(oli.receiverType)) + { + auto hasField = [&](mlir::Attribute id) { + return llvm::any_of(oli.fieldInfos, [&](const mlir_ts::FieldInfo &fieldInfo) { return fieldInfo.id == id; }); + }; + + auto missingOnlyOptional = llvm::all_of(receiverTuple.getFields(), [&](const mlir_ts::FieldInfo &field) { + return hasField(field.id) || isa(field.type); + }); + auto anyMissing = llvm::any_of(receiverTuple.getFields(), [&](const mlir_ts::FieldInfo &field) { return !hasField(field.id); }); + if (missingOnlyOptional && anyMissing && oli.methodInfos.empty() && oli.methodInfosWithCaptures.empty()) + { + for (auto &field : receiverTuple.getFields()) + { + if (!hasField(field.id)) + { + auto undefinedValue = builder.create(location, field.type); + if (mlir::failed(addObjectFieldInfo(location, oli, field.id, undefinedValue, field.type, genContext))) + { + return mlir::failure(); + } + } + } + } + } + // update after processing all fields objectStorageType.setFields(oli.fieldInfos); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 184ed0a97..81569010b 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -11171,6 +11171,21 @@ class MLIRGenImpl restSource = ifOp.getResult(0); } + // ...and of a `T | null`: T's (as a declaration) + if (auto unionType = dyn_cast(restSource.getType())) + { + auto nonNullish = getNonNullishType(unionType); + // (read as T, as a field of it is - a cast is refused in strict null mode: one pointer as it is, the + // member's value out of a tagged union) + if (nonNullish != restSource.getType() && !isa(nonNullish)) + { + mlir::Type actualType; + restSource = mth.isUnionTypeNeedsTag(location, unionType, actualType) + ? mlir::Value(builder.create(location, nonNullish, restSource)) + : mlir::Value(builder.create(location, nonNullish, restSource)); + } + } + llvm::SmallVector sourceFields; llvm::SmallVector restFields; if (mlir::failed(mth.getFields(restSource.getType(), sourceFields))) @@ -14743,6 +14758,126 @@ class MLIRGenImpl mlir::LogicalResult processOperandSpreadElement(mlir::Location location, mlir::Value source, OperandsProcessingInfo &operandsProcessingInfo, const GenContext &genContext); + // -mm=own: an object or tuple literal given to a call (`k.keep(["a" + i, i])`, `k.keep({ s: "a" + i })`) is built in + // a slot nothing owns (createTupleInSlot, mlirGenCreateTuple), read whole once here: given to a callee that keeps + // it, there was nothing to move it from ("this function does not own it", TSLANG 208). It goes into a local of its + // own, as `const t = ["a" + i, i]; k.keep(t)` puts it: the local owns the literal, gives it to a callee that keeps + // it as its last use, and gives it back at the end of its scope where the callee only borrows it. Directly in a + // `try` body the local is made in front of the `try` and given the literal by a store, as a declared one is + // (createLocalVariable), so the cleanup sees it. Not in a generator, whose locals are fields of its object: there + // the literal stays as it was. + 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)) + { + return value; + } + + auto literal = stripParentheses(expression); + if (literal != SyntaxKind::ArrayLiteralExpression && literal != SyntaxKind::ObjectLiteralExpression) + { + return value; + } + + auto loadOp = value.getDefiningOp(); + auto slotOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (!slotOp || slotOp->hasAttr(OWNED_LOCAL_ATTR_NAME) || !slotOp.getInitializer() + || !slotOp.getInitializer().getDefiningOp() + || !isa(value.getType()) || !mth.ownsHeapMemory(location, value.getType())) + { + return value; + } + + // only a literal of new values (`"a" + i`, `new V(1)`) or constants: one holding what it borrows (`{ start: pos }`, + // a borrowing record, spec 32) stays one + auto onlyNewValues = llvm::all_of(slotOp->getUsers(), [&](mlir::Operation *user) { + if (user == loadOp.getOperation()) + { + return true; + } + + auto fieldRefOp = dyn_cast(user); + return fieldRefOp && llvm::all_of(fieldRefOp->getUsers(), [&](mlir::Operation *fieldUser) { + if (isa(fieldUser)) + { + return true; + } + + auto storeOp = dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != fieldRefOp.getResult()) + { + return false; + } + + auto stored = storeOp.getValue(); + if (!mth.ownsHeapMemory(location, stored.getType())) + { + return true; + } + + // a string constant is immortal: the local's release of it does nothing. Another constant (`{}`, + // read-only data) is no block a release may free + auto root = stored; + while (root.getDefiningOp() || root.getDefiningOp()) + { + root = root.getDefiningOp()->getOperand(0); + } + + if (auto constantOp = root.getDefiningOp()) + { + return isa(constantOp.getValue()); + } + + // a new value, made by an op of its own - not a constant seen as one (isLiteral); a closure is new but + // holds what it captures (`{ w: (x) => x + item.n }`) + auto *def = stored.getDefiningOp(); + return def && own_facts::isFresh(stored) && !own_facts::isLiteral(def) + && !mth.isAnyFunctionType(stored.getType()); + }); + }); + if (!onlyNewValues) + { + 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 + for (auto *parentOp = builder.getInsertionBlock()->getParentOp(); parentOp && !isa(parentOp); + parentOp = parentOp->getParentOp()) + { + if (parentOp->getNumResults() > 0) + { + return value; + } + } + + mlir_ts::VariableOp localOp; + if (genContext.allocateScopeOwnedVarsOutsideOfOperation) + { + { + mlir::OpBuilder::InsertionGuard insertGuard(builder); + builder.setInsertionPoint(genContext.currentOperation); + localOp = builder.create(location, mlir_ts::RefType::get(value.getType()), mlir::Value(), + builder.getBoolAttr(false), builder.getIndexAttr(0)); + } + + builder.create(location, value, localOp); + } + else + { + localOp = builder.create(location, mlir_ts::RefType::get(value.getType()), value, + builder.getBoolAttr(false), builder.getIndexAttr(0)); + } + + localOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + builder.create(location, localOp); + genContext.ownedVars->push_back(localOp); + return builder.create(location, value.getType(), localOp); + } + mlir::LogicalResult mlirGenOperand(Expression expression, OperandsProcessingInfo &operandsProcessingInfo, const GenContext &genContext, mlir::Type receiverType = mlir::Type()) { @@ -14760,6 +14895,7 @@ class MLIRGenImpl auto result = mlirGen(expression, argGenContext); EXIT_IF_FAILED_OR_NO_VALUE(result) auto value = V(result); + value = ownedLiteralArgument(loc(expression), expression, value, genContext); // A `@stdcall` function of another library given to C (a parameter of a C function type, @cdecl), on // 32-bit Windows: C calls it as __stdcall, so it is the function itself, not the C function the @@ -20516,6 +20652,8 @@ class MLIRGenImpl const GenContext &genContext); ValueOrLogicalResult castAnyToTuple(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext); + ValueOrLogicalResult castAnyToTupleOfNumbers(mlir::Location location, mlir::Type type, mlir::Value value, + const GenContext &genContext); // TODO: remove using typeof for Union types as it can't handle types such as 2 tuples in union etc ValueOrLogicalResult castFromUnion(mlir::Location location, mlir::Type type, mlir::Value value, const GenContext &genContext); diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index cba8b8e06..9283b4d8f 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -1247,6 +1247,22 @@ namespace mlirgen init = ifOp.getResult(0); } + // ...and of a `T | null`: T's, as the pattern's other names read T's fields (destructuring a null throws in + // JavaScript). It was "the rest of a value of type 'null | T' can't be taken". + if (auto unionType = dyn_cast(init.getType())) + { + auto nonNullish = getNonNullishType(unionType); + // (read as T, as a field of it is - a cast is refused in strict null mode: one pointer as it is, the + // member's value out of a tagged union) + if (nonNullish != init.getType() && !isa(nonNullish)) + { + mlir::Type actualType; + init = mth.isUnionTypeNeedsTag(location, unionType, actualType) + ? mlir::Value(builder.create(location, nonNullish, init)) + : mlir::Value(builder.create(location, nonNullish, init)); + } + } + SmallVector names; // take all used fields diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index 28e102c46..ffce5955e 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -457,6 +457,20 @@ namespace own_inference // stored into the result slot, or into an owning local (`a = { item: new C() }`) auto slot = storeOp && storeOp.getValue() == used ? storeOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + // ...declared with it in a `try` body (`try { const t = ["a" + i, i]; k.keep(t); }`): the local is made in + // front of the `try` and given its value by this store, right before its `ts.RetainSlot` + // (slotDeclarationStore) - that retain is the record's, as an initializer's is (TSLANG 208) + if (slot && isOwningVariable(slot) && !slot.getInitializer()) + { + auto *slotRetain = onlyRetainSlotOf(slot); + if (slotRetain && slotDeclarationStore(slotRetain) == storeOp) + { + bad = retain != nullptr; + retain = slotRetain; + return; + } + } + bad = !slot || !(isResultSlot(slot) || isOwningVariable(slot)); }; forEachUse(read.getResult(), visit); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 5481902e9..22b6b890d 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2544,6 +2544,22 @@ foreach(issues_mm gc rc none) tslang_add_test(NAME test-compile-${issue_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_test}.ts") endforeach() endforeach() +# TSLANG 207: leftovers of 195, 196, 198 and 205 (the `any` casts and the rest of a `T | null` not under own: the test file +# says why) +foreach(issue207_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_207-${issue207_mm} COMMAND test-runner -jit -mm=${issue207_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_207.ts") + tslang_add_test(NAME test-compile-00tslang_issue_207-${issue207_mm} COMMAND test-runner -mm=${issue207_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_207.ts") +endforeach() +foreach(issue207_mm gc rc none) + tslang_add_test(NAME test-jit-00tslang_issue_207_any-${issue207_mm} COMMAND test-runner -jit -mm=${issue207_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_207_any.ts") + tslang_add_test(NAME test-compile-00tslang_issue_207_any-${issue207_mm} COMMAND test-runner -mm=${issue207_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_207_any.ts") +endforeach() +# TSLANG 208: the "not yet" of 207 (a literal's integer function member given as an interface's number one, a tuple or +# object literal given to a callee that keeps it under own) +foreach(issue208_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_208-${issue208_mm} COMMAND test-runner -jit -mm=${issue208_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_208.ts") + tslang_add_test(NAME test-compile-00tslang_issue_208-${issue208_mm} COMMAND test-runner -mm=${issue208_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_208.ts") +endforeach() # 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/00any_to_tuple.ts b/tslang/test/tester/tests/00any_to_tuple.ts index 239841616..e63e408d9 100644 --- a/tslang/test/tester/tests/00any_to_tuple.ts +++ b/tslang/test/tester/tests/00any_to_tuple.ts @@ -33,17 +33,9 @@ function main() { assert(thrown); - // a tuple of other fields throws too: `{ n: 5 }` holds an s32, which was read as a number, and - // `{ m: 1.5 }` was read as if its field were `n` - thrown = false; - try { - const s: any = { n: 5 }; - asTuple(s); - } catch (e) { - thrown = true; - } + // (`{ n: 5 }`, an s32 field, is converted under gc, rc and none and still throws under own: 00tslang_issue_207_any.ts) - assert(thrown); + // a tuple of other fields throws: `{ m: 1.5 }` was read as if its field were `n` thrown = false; try { diff --git a/tslang/test/tester/tests/00tslang_issue_207.ts b/tslang/test/tester/tests/00tslang_issue_207.ts new file mode 100644 index 000000000..21ac9718f --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_207.ts @@ -0,0 +1,38 @@ +// TSLANG 207 (leftovers of 195, 196 and 205), every model. + +// 205: a literal given to a generic call whose function member returns an integer, where the type parameter is a +// number from another argument: the member returns the number its receiver says ("can't assign '() => s32' to +// '() => number'"), in either order of the arguments +interface Options { + produce: () => Data; +} + +function takeG(o: Options, d: D): D { + return o.produce(); +} + +function takeG2(d: D, o: Options): D { + return o.produce(); +} + +// 196: a literal that leaves out an optional field of a tuple it is given to, holding a function (under -mm=own "a +// value that borrows a field cannot be stored") +type Cb = () => number; + +function main() { + assert(takeG({ produce: () => 44 }, 1.5) / 8 == 5.5); + assert(takeG2(1.5, { produce: () => 44 }) / 8 == 5.5); + assert(takeG({ produce: () => 4 }, 1) == 4); + + const cb: Cb = () => 3; + const o: { disc?: false; cb: Cb } = { cb }; + assert(o.cb() == 3 && o.disc === undefined); + + const p: { n?: number; cb: Cb; m?: string } = { cb: cb }; + assert(p.cb() == 3 && p.n === undefined && p.m === undefined); + + const q: { n?: number; s: string } = { s: "s" + 1 }; + assert(q.s == "s1" && q.n === undefined); + + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_207_any.ts b/tslang/test/tester/tests/00tslang_issue_207_any.ts new file mode 100644 index 000000000..94fe29f73 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_207_any.ts @@ -0,0 +1,49 @@ +// TSLANG 207 (leftovers of 195 and 198), gc, rc and none: under -mm=own the cast of an `any` reads no converted +// layout, and the rest of a tuple holding a string is refused. + +// 195: an `any` holding an object literal written with integers (`{ code: 7 }`, s32 fields) cast to an object type +// of numbers: it threw "the object's fields are not those of type" +function castAny() { + const a: any = { code: 7 }; + const c = <{ code: number }>a; + assert(c.code + 0.5 == 7.5); + + const m: any = { x: 1, y: 2.5, name: "p" }; + const p = <{ x: number; y: number; name: string }>m; + assert(p.x / 4 == 0.25 && p.y == 2.5 && p.name == "p"); + + const n: any = { x: 1.5 }; + assert((<{ x: number }>n).x == 1.5); + + let caught = false; + try { + const bad = <{ x: number }>{ y: "s" }; + print(bad.x); + } catch (e) { + caught = true; + } + + assert(caught, "a layout of other fields still throws"); +} + +// 198: the rest of a `T | null` ("the rest of a value of type 'null | T' can't be taken"), declared and assigned +type T = { a: number; b: string; c: number }; + +function restOf(u: T | null) { + const { a, ...rest } = u; + assert(a == 1 && rest.b == "x" && rest.c == 3); +} + +function restAssigned(u: T | null) { + let a: number = 0; + let rest = { b: "", c: 0 }; + ({ a, ...rest } = u); + assert(a == 2 && rest.b == "y" && rest.c == 4); +} + +function main() { + castAny(); + restOf({ a: 1, b: "x", c: 3 }); + restAssigned({ a: 2, b: "y", c: 4 }); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_208.ts b/tslang/test/tester/tests/00tslang_issue_208.ts new file mode 100644 index 000000000..71d500eb2 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_208.ts @@ -0,0 +1,81 @@ +// TSLANG 208 (the "not yet" of 207), every model. + +// a literal held by a variable first, whose function member returns an integer, given as an interface whose member +// returns a number: "field "produce" not matching type" (`() => s32` is not `() => number`) +interface Options { + produce: () => Data; +} + +function one() { + return 1; +} + +function readOptions(o: Options) { + return o.produce(); +} + +// a tuple or object literal given to a callee that keeps it: under -mm=own "this function does not own it" +class K { + items: [string, number][] = []; + objs: { s: string; n: number }[] = []; + + keepOne(t: [string, number]) { + this.items.push(t); + } + + keepObj(t: { s: string; n: number }) { + this.objs.push(t); + } +} + +function lengthOf(t: [string, number]) { + return t[0].length + t[1]; +} + +function main() { + const t = { produce: () => 45 }; + const o: Options = t; + assert(o.produce() / 2 == 22.5); + assert(readOptions(t) / 2 == 22.5); + + const named = { produce: one }; + const p: Options = named; + assert(p.produce() / 2 == 0.5); + + // ...and one in a `let`, whose function is read at run time + let held = { produce: () => 46 }; + const q: Options = held; + assert(q.produce() / 4 == 11.5 && readOptions(held) / 4 == 11.5); + + const k = new K(); + for (let i = 0; i < 3; i++) { + k.keepOne(["a" + i, i]); + k.keepObj({ s: "b" + i, n: i }); + k.keepOne((["c" + i, i + 10])); + } + + assert(k.items.length == 6 && k.items[4][0] == "a2" && k.items[5][0] == "c2" && k.items[5][1] == 12); + assert(k.objs.length == 3 && k.objs[2].s == "b2" && k.objs[2].n == 2); + + // directly in a `try` body, as an argument and in a local + try { + k.keepOne(["t" + k.items.length, 0]); + } catch (e) {} + + try { + const kept: [string, number] = ["u" + k.items.length, 1]; + k.keepOne(kept); + } catch (e) {} + + assert(k.items.length == 8 && k.items[6][0] == "t6" && k.items[7][0] == "u7" && k.items[7][1] == 1); + + // a callee that only reads it + let sum: number = 0; + for (let i = 0; i < 3; i++) { + sum += lengthOf(["x" + i, 1]); + } + + assert(sum == 9); + + print("done."); +}