diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 7744952bb..7abfaa675 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -79,6 +79,7 @@ #define OWNED_LOCAL_CONSUMED_ATTR_NAME "__owned_consumed" // -mm=rc: the slot of the frame that owns a parameter's default value while it is taken (processOptionalParam) #define DEFAULT_VALUE_SLOT_ATTR_NAME "__default_value_slot" +#define PATTERN_DEFAULT_SLOT_ATTR_NAME "__pattern_default_slot" // the owning slot that holds the fresh values a `let` borrowing a field is given (TSLANG 66) #define OWN_LET_HOLDER_ATTR_NAME "__own_let_holder" diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index 23fce1978..b18076e21 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -136,6 +136,7 @@ struct GenContext generatorSwitchOperation = nullptr; allocateVarsOutsideOfOperation = false; allocateScopeOwnedVarsOutsideOfOperation = false; + bindingParamPatterns = false; } void clearReceiverTypes() @@ -219,6 +220,10 @@ struct GenContext // a catch clause's variable is being declared: the landing pad writes it, not an initializer, so it // starts with nothing in it (MLIRGenImpl::adjustLocalVariableType) bool declaringCatchVariable = false; + // a function's prologue is destructuring a parameter (`function f([a = mk(1)]: N[])`): no scope owns anything yet + // (ownedVars is null), and -mm=own's slot for a pattern default that makes a new value is the frame's, given back + // at the function's exit (MLIRGenImpl::ownPatternDefaultSlot, mlirGenFunctionBody) + bool bindingParamPatterns = false; bool forceDiscover = false; bool discoverParamsOnly = false; bool insertIntoParentScope = false; diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 9d556a9d3..9a6a087dd 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -2623,11 +2623,13 @@ namespace mlirgen assert(val); auto initFunc = [&](mlir::Location, const GenContext &) { return std::make_tuple(val.getType(), val, TypeProvided::No); }; + GenContext bindingGenContext(genContext); + bindingGenContext.bindingParamPatterns = true; if (bindingPattern == SyntaxKind::ArrayBindingPattern) { auto arrayBindingPattern = bindingPattern.as(); if (mlir::failed(processDeclarationArrayBindingPattern(location, arrayBindingPattern, VariableType::Let, - initFunc, genContext))) + initFunc, bindingGenContext))) { return mlir::failure(); } @@ -2636,7 +2638,7 @@ namespace mlirgen { auto objectBindingPattern = bindingPattern.as(); if (mlir::failed(processDeclarationObjectBindingPattern(location, objectBindingPattern, VariableType::Let, - initFunc, genContext))) + initFunc, bindingGenContext))) { return mlir::failure(); } @@ -2898,8 +2900,10 @@ namespace mlirgen { paramCells->push_back(prologueOp.getResult(0)); } - // ...and the slot owning a parameter's default value (processOptionalParam), given back at exit - else if (isa(prologueOp) && prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME)) + // ...and the slot owning a parameter's default value (processOptionalParam), or, under own, a default in a + // destructured parameter (ownPatternDefaultSlot), given back at exit + else if (isa(prologueOp) && + (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME))) { paramCells->push_back(prologueOp.getResult(0)); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index d5c9ab1d7..8276147c8 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -1061,6 +1061,13 @@ class MLIRGenImpl // `onlyOnAttr` names the copies of a hand-written finally the releases are kept in - // UNWIND_ONLY_ATTR_NAME or RETURN_ONLY_ATTR_NAME - or is empty for an ordinary release + bool isPatternDefaultSlotOutOfReach(mlir::Value storage) + { + auto varOp = storage.getDefiningOp(); + return varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && + !varOp->getParentRegion()->isAncestor(builder.getInsertionBlock()->getParent()); + } + void releaseScopeOwnedVars(mlir::Location location, const SmallVector &ownedVars, StringRef onlyOnAttr = {}) { @@ -1079,6 +1086,14 @@ class MLIRGenImpl } else if (isOwnedLocalSlot(storage)) { + // (a pattern default's slot made inside an expression does not reach the scope's end: + // ownPatternDefaultSlot) + if (isPatternDefaultSlotOutOfReach(storage)) + { + continue; + } + + releaseOp = builder.create(location, storage); // a closure written further on may still capture it (releaseCapturedSlotsAsCells) releaseOp->setAttr(SCOPE_EXIT_RELEASE_ATTR_NAME, builder.getUnitAttr()); @@ -2187,12 +2202,25 @@ class MLIRGenImpl } // A value read out of an element, through any casts: what `a[0]` is in `const c = a[0]`, and - // what `b` is in `const [b] = a`, read there only when `a` is long enough (the `then` of an if). + // what `b` is in `const [b] = a`, read there only when `a` is long enough (the `then` of an if; of a reference + // type, `T | undefined`, the element wrapped as an optional: readsUndefinedPastEnd). static bool readsElement(mlir::Value value) { - while (auto castOp = value ? value.getDefiningOp() : mlir_ts::CastOp()) + while (value) { - value = castOp.getIn(); + if (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + continue; + } + + if (auto optionalValueOp = value.getDefiningOp()) + { + value = optionalValueOp.getIn(); + continue; + } + + break; } if (auto ifOp = value ? value.getDefiningOp() : mlir_ts::IfOp()) @@ -3507,7 +3535,25 @@ class MLIRGenImpl // TODO: to support '...' u need to use 'processOperandSpreadElement' and instead of "index" param use "next" logic ValueOrLogicalResult processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, - bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, const GenContext &genContext); + bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, + Expression defaultValue, bool bindsName, const GenContext &genContext); + + // An element of an array value past its end is undefined (`const [a, b] = [mk(5)] as N[]`: b, as node has it). + // A reference element type (a class, an interface, an object, an array, a tuple, a union with one of those or + // null) is read as `T | undefined` then - its own type has only null for "nothing", and the element read as null. + // A primitive one (number, boolean, string, a union of those) keeps its type and reads as its type's default: the + // variable could not hold undefined. + static bool readsUndefinedPastEnd(mlir::Type elementType) + { + if (isa(elementType)) + { + return true; + } + + auto unionType = dyn_cast(elementType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { return readsUndefinedPastEnd(type); }); + } mlir::LogicalResult processDeclarationArrayBindingPattern(mlir::Location location, ArrayBindingPattern arrayBindingPattern, VariableClass varClass, @@ -4913,8 +4959,55 @@ class MLIRGenImpl return mclh.conditionalValue(condValue, trueValue, falseValue); } + // -mm=own: the slot a pattern's default that makes a new value is held by (optionalValueOrDefault), a slot of the + // scope, released when the scope ends. Made where the scope's owned locals are: in a `try` body or a `switch` case, + // in front of the TryOp/SwitchOp, as an owned local is hoisted (mlirGen(VariableDeclaration)) - made in the region, + // it did not dominate the release on the unwind leg or at the switch's end ("operand #0 does not dominate this + // use"). None in a generator, whose locals are fields of the generator object kept between turns: the default is + // what it was before, refused where it was refused. A slot made inside an expression (a destructuring assignment in + // `?:`) does not dominate the scope's end either: it is not released there (releaseScopeOwnedVars), and + // settleOwnPatternDefaults takes such a slot out again. + mlir::Value ownPatternDefaultSlot(mlir::Location location, mlir::Type dataType, const GenContext &genContext) + { + // (a destructured parameter's default: the frame's, listed when the prologue is done, mlirGenFunctionBody) + if (compileOptions.memoryModel != MemoryModelOwn || !(genContext.ownedVars || genContext.bindingParamPatterns) || + genContext.generatorSwitchOperation || !mth.ownsHeapMemory(location, dataType)) + { + return mlir::Value(); + } + + mlir::OpBuilder::InsertionGuard insertGuard(builder); + if ((genContext.allocateScopeOwnedVarsOutsideOfOperation || genContext.allocateVarsOutsideOfOperation) && + genContext.currentOperation) + { + builder.setInsertionPoint(genContext.currentOperation); + } + + mlir::Value defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), + builder.getBoolAttr(false), builder.getIndexAttr(0)); + auto empty = builder.create(location, dataType); + builder.create(location, empty, defaultSlot); + auto varOp = defaultSlot.getDefiningOp(); + varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); + if (genContext.ownedVars) + { + genContext.ownedVars->push_back(defaultSlot); + } + + return defaultSlot; + } + ValueOrLogicalResult optionalValueOrDefault(mlir::Location location, mlir::Type dataType, mlir::Value value, Expression defaultExpr, const GenContext &genContext) { + // -mm=own: a default that makes a new value (`const { p = mk(1) } = r`, `"q" + i`) is held by a slot of the scope, + // empty unless the default is taken, given back when the scope ends, as a local is; the value read borrows it, as + // it borrows the field otherwise. Nothing owned the new value: every evaluation that ran the default leaked it. + // A borrowed default (`p = e`) is not stored (settleOwnPatternDefaults). + // (rc settles the op in OwnedReturnConsumptionPass, consumeValueOrDefaultResults.) + auto defaultSlot = ownPatternDefaultSlot(location, dataType, genContext); + auto optionalValueOrDefaultOp = builder.create( location, dataType, value); @@ -4937,6 +5030,14 @@ class MLIRGenImpl CAST(defaultValue, location, dataType, defaultValue, genContext); } + // (whether the default is a new value is known once calls are settled: OwnedReturnConsumptionPass, + // settleOwnPatternDefaults, keeps the store of one and drops it for a borrowed default) + if (defaultSlot) + { + builder.create(location, defaultValue, defaultSlot); + defaultValue = builder.create(location, dataType, defaultSlot); + } + builder.create(location, defaultValue); builder.setInsertionPointAfter(optionalValueOrDefaultOp); @@ -4951,8 +5052,11 @@ class MLIRGenImpl // printed 0). A function gives back none of its parameters (the caller owns what it passes), so the value is // owned by a slot of the frame, empty unless the default is taken, given back at the function's exit // (mlirGenFunctionBody lists it with the parameters' storage); the parameter borrows it. + // -mm=own the same: the slot owns a new default value, moved in (settleOwnPatternDefaults keeps the store of one + // and drops it for a borrowed default, which the parameter then borrows as before) + auto ownSlot = compileOptions.memoryModel == MemoryModelOwn; mlir::Value defaultSlot; - if (compileOptions.isRefCounted() && mth.ownsHeapMemory(location, dataType)) + if ((compileOptions.isRefCounted() || ownSlot) && mth.ownsHeapMemory(location, dataType)) { defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), builder.getBoolAttr(false), builder.getIndexAttr(0)); @@ -4962,6 +5066,10 @@ class MLIRGenImpl varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(DEFAULT_VALUE_SLOT_ATTR_NAME, builder.getUnitAttr()); + if (ownSlot) + { + varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); + } } auto paramOptionalOp = builder.create( @@ -4989,8 +5097,11 @@ class MLIRGenImpl if (defaultSlot) { // as an awaited result's slot takes it (mlirGen(AwaitExpression)): a value that carries a reference - // hands it over, anything else is retained - if (producesOwnedReference(defaultValue)) + // hands it over, anything else is retained (own: settled later, no retain) + if (ownSlot) + { + } + else if (producesOwnedReference(defaultValue)) { consumeOwnedReference(defaultValue); } @@ -10071,6 +10182,51 @@ class MLIRGenImpl continue; } + // An element past the end is undefined (as node has it): a target that can hold undefined (`let b: N | + // undefined; [a, b] = xs`) is given undefined there, not null - the element is read as `T | undefined` + // behind a bounds test (readsUndefinedPastEnd). A target that cannot hold it keeps the read below. + auto targetHoldsUndefined = [&]() { + if (!leftExpressionValue || !readsUndefinedPastEnd(elementType)) + { + return false; + } + + auto targetType = leftExpressionValue.getType(); + if (isa(targetType)) + { + return true; + } + + auto unionType = dyn_cast(targetType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { + return isa(type); + }); + }; + if (!defaultValue && targetHoldsUndefined()) + { + auto lengthValue = builder.create(location, builder.getIndexType(), rightExpressionValue); + auto boundValue = builder.create(location, mth.getIndexType(), mth.getIndexAttrValue(index)); + auto inBounds = V(builder.create(location, getBooleanType(), + builder.getI32IntegerAttr((int)SyntaxKind::GreaterThanToken), lengthValue, boundValue)); + auto optionalType = mlir_ts::OptionalType::get(elementType); + auto conditional = conditionalValue(location, inBounds, + [&]() -> ValueOrLogicalResult { + auto element = readElement(); + CAST_A(optionalElement, location, optionalType, element, genContext); + return ValueOrLogicalResult(optionalElement); + }, + [&](mlir::Type trueValueType) { + return ValueOrLogicalResult(V(builder.create(location, trueValueType))); + }); + EXIT_IF_FAILED_OR_NO_VALUE(conditional) + if (mlir::failed(saveTo(V(conditional)))) + { + return mlir::failure(); + } + + continue; + } + // without a default the element is read as it was (an owned element moved out of a fresh array literal // under -mm=own is that read) if (!defaultValue) diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index b41f2d83a..2b1a336f9 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -507,8 +507,35 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, - bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, const GenContext &genContext) + bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, + Expression defaultValue, bool bindsName, const GenContext &genContext) { + // An element's default (`const [a = mk(1), b = mk(2)] = [mk(i)]`) is its value where the element is missing - past + // the end of the source, or undefined there - as in TypeScript. It was not applied: an element past the end of a + // literal was undefined (the compiler crashed reading it) or the default of its type (`[a = 1, b = 2] = [5]` gave + // b 0). `castTo`: the element type the value must have, where the other way gives one of that type. + auto makeDefault = [&](mlir::Type castTo) -> mlir::Value { + auto result = mlirGen(defaultValue, genContext); + if (result.failed_or_no_value()) + { + return mlir::Value(); + } + + auto value = V(result); + if (castTo && value.getType() != castTo) + { + auto castResult = cast(location, castTo, value, genContext); + if (castResult.failed_or_no_value()) + { + return mlir::Value(); + } + + value = V(castResult); + } + + return value; + }; + MLIRPropertyAccessCodeLogic cl(compileOptions, builder, location, init, builder.getI32IntegerAttr(index)); mlir::Value subInit = mlir::TypeSwitch(type) @@ -545,7 +572,7 @@ namespace mlirgen // as the element of an array is; read, it was no value and the statement failed with nothing said if (index >= (int)constTupleType.size()) { - return V(builder.create(location, getUndefinedType())); + return defaultValue ? makeDefault(mlir::Type()) : V(builder.create(location, getUndefinedType())); } return cl.Tuple(constTupleType, true); @@ -583,7 +610,7 @@ namespace mlirgen // as the element of an array is; read, it was no value and the statement failed with nothing said if (index >= (int)tupleType.size()) { - return V(builder.create(location, getUndefinedType())); + return defaultValue ? makeDefault(mlir::Type()) : V(builder.create(location, getUndefinedType())); } return cl.Tuple(tupleType, true); @@ -605,7 +632,8 @@ namespace mlirgen // past the end: the default of the element type, null for a reference (see below) if (static_cast(index) >= constArrayType.getSize()) { - return V(builder.create(location, constArrayType.getElementType())); + return defaultValue ? makeDefault(mlir::Type()) + : V(builder.create(location, constArrayType.getElementType())); } // TODO: unify it with ElementAccess @@ -632,6 +660,87 @@ namespace mlirgen auto inBoundsValue = V(builder.create(location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::GreaterThanToken), lengthValue, indexValue)); + // (a literal that has the element - `[[k = mk(1)] = []] = [[mk(i)]]` - always gives it: the default + // never applies, as for a constant array) + // (unless the element may be undefined: `[u = 3] = [undefined]`) + auto elementMayBeUndefined = [&](mlir::Type elementType) { + if (isa(elementType)) + { + return true; + } + + auto unionType = dyn_cast(elementType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { + return isa(type); + }); + }; + // (also an inner literal read out of an outer one: `[[b = mk(1)] = [mk(2)]] = [[mk(i)]]`) + auto literalOf = [](mlir::Value value) { + while (auto loadOp = value.getDefiningOp()) + { + auto elementRefOp = loadOp.getReference().getDefiningOp(); + auto outer = elementRefOp ? elementRefOp->getOperand(0).getDefiningOp() + : mlir_ts::CreateArrayOp(); + auto indexOp = elementRefOp ? elementRefOp->getOperand(1).getDefiningOp() + : mlir_ts::ConstantOp(); + auto indexAttr = indexOp ? dyn_cast(indexOp.getValue()) : mlir::IntegerAttr(); + if (!outer || !indexAttr || indexAttr.getInt() < 0 || + indexAttr.getInt() >= (int64_t)outer->getNumOperands()) + { + break; + } + + value = outer->getOperand(indexAttr.getInt()); + } + + return value.getDefiningOp(); + }; + if (auto createArrayOp = literalOf(init); + defaultValue && createArrayOp && static_cast(index) < createArrayOp->getNumOperands() && + !elementMayBeUndefined(arrayType.getElementType())) + { + // the element, read as out of a constant array: no bounds test (an inner pattern reads it on) + auto constIndex = builder.create(location, builder.getI32Type(), + builder.getI32IntegerAttr(index)); + auto elemRef = builder.create( + location, mlir_ts::RefType::get(arrayType.getElementType()), init, constIndex); + return V(builder.create(location, arrayType.getElementType(), elemRef)); + } + + // (with a default of another type, `const [a, b = "q"] = numbers`, the element is of both) + mlir::Type valueType = arrayType.getElementType(); + if (defaultValue) + { + if (auto defaultType = evaluate(defaultValue, genContext)) + { + defaultType = mth.wideStorageType(defaultType); + llvm::StringMap> typeParamsWithArgs; + // (an array default of an array element - `[[k = mk(1)] = []]` - is of the element's type) + auto bothArrays = isa(defaultType) && + isa(valueType); + if (defaultType != valueType && !bothArrays && + mth.extendsType(location, defaultType, valueType, typeParamsWithArgs) != ExtendsResult::True) + { + valueType = getUnionType(location, valueType, defaultType); + } + } + } + + // (without a default, an element past the end is undefined: a name bound to an element of a reference + // type is `T | undefined` - readsUndefinedPastEnd; it read as null. Not where a literal has the element, + // nor for an inner pattern, which reads the element on) + auto createArrayOfInit = literalOf(init); + if (!defaultValue && !isDotDotDot && bindsName && readsUndefinedPastEnd(valueType) && + !(createArrayOfInit && static_cast(index) < createArrayOfInit->getNumOperands())) + { + valueType = mlir_ts::OptionalType::get(valueType); + } + + // -mm=own: a default that makes a new value is held by a slot of the scope, as an object pattern's is + // (optionalValueOrDefault); the element read borrows the slot or the source's element. A new value + // merged with a borrow of the element had no owner: own refused the pattern. + auto defaultSlot = defaultValue ? ownPatternDefaultSlot(location, valueType, genContext) : mlir::Value(); + auto result = conditionalValue(location, inBoundsValue, [&]() { // TODO: unify it with ElementAccess @@ -639,10 +748,40 @@ namespace mlirgen builder.getI32IntegerAttr(index)); auto elemRef = builder.create( location, mlir_ts::RefType::get(arrayType.getElementType()), init, constIndex); - return ValueOrLogicalResult( - V(builder.create(location, arrayType.getElementType(), elemRef))); + mlir::Value element = V(builder.create(location, arrayType.getElementType(), elemRef)); + if (element.getType() != valueType) + { + auto castResult = cast(location, valueType, element, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(castResult) + element = V(castResult); + } + + return ValueOrLogicalResult(element); }, [&](mlir::Type elementType) { + if (defaultValue) + { + auto value = makeDefault(elementType); + if (!value) + { + return ValueOrLogicalResult(mlir::failure()); + } + + // (kept only for a new value: settleOwnPatternDefaults) + if (defaultSlot && value.getType() == valueType) + { + builder.create(location, value, defaultSlot); + value = builder.create(location, valueType, defaultSlot); + } + + return ValueOrLogicalResult(value); + } + + if (isa(elementType)) + { + return ValueOrLogicalResult(V(builder.create(location, elementType))); + } + return ValueOrLogicalResult(V(builder.create(location, elementType))); }); return result.failed_or_no_value() ? mlir::Value() : V(result); @@ -699,6 +838,22 @@ namespace mlirgen return mlir::failure(); } + // ...and where the element read is undefined, or may be (`[a = 1] = [undefined]`, an optional element) + if (defaultValue && !isDotDotDot) + { + if (isa(subInit.getType())) + { + return makeDefault(mlir::Type()); + } + + if (auto optionalType = dyn_cast(subInit.getType())) + { + auto result = optionalValueOrDefault(location, optionalType.getElementType(), subInit, defaultValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + return V(result); + } + } + return subInit; } @@ -792,7 +947,8 @@ namespace mlirgen auto subValueFunc = [&](mlir::Location location, const GenContext &genContext) { auto result = processDeclarationArrayBindingPatternSubPath( - location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, genContext); + location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, + arrayBindingElement->initializer, arrayBindingElement->name == SyntaxKind::Identifier, genContext); if (result.failed_or_no_value()) { return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 75baafcc1..3c2445e86 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -306,6 +306,8 @@ class OwnedReturnConsumptionPass ownNewArrayArguments(mth, module); + settleOwnPatternDefaults(module); + consumeConditionalResults(mth, module); claimGlobalInitializers(mth, module); @@ -994,7 +996,7 @@ class OwnedReturnConsumptionPass // Does `value` stay in `block` but for its terminator? Seen through the casts that only widen it, and through a // conditional expression in `block` (or in a statement of it) whose branch yields it: that conditional's result // is the value then. `leaves` is set when `block`'s terminator takes it; false for any other terminator. - static bool leavesBlockBy(mlir::Value value, mlir::Block *block, bool &leaves, int depth = 0) + bool leavesBlockBy(mlir::Value value, mlir::Block *block, bool &leaves, int depth = 0) { if (depth > 64) { @@ -1077,7 +1079,7 @@ class OwnedReturnConsumptionPass // through the casts that only widen it). The conditional's result may be yielded on by a branch of another // (`c ? (d ? [mk(i)][0] : null) : null`), and so on: `levels` is how many conditionals the literal is held past, // to the end of the block the outermost one is in. - static bool yieldedByBranch(mlir::Operation *op, const std::function &leavesUncounted, int &levels) + bool yieldedByBranch(mlir::Operation *op, const std::function &leavesUncounted, int &levels) { auto ifOp = conditionalOf(op->getBlock()); if (!ifOp || !op->getParentOfType()) @@ -2819,6 +2821,192 @@ class OwnedReturnConsumptionPass consumeValueOrDefaultResults(mth, module); } + // -mm=own: a pattern's default stores what it yields into a slot of the scope (MLIRGenImpl::optionalValueOrDefault), + // which owns it and gives it back when the scope ends; the pattern's value borrows the slot. Only a new value is the + // slot's to own - a call's result, a new object, a fresh string, as settled here, once calls are marked: it moves in. + // A default that borrows (`p = e`, a field, a literal's element) is not stored: what the region yields is that + // value, as before, and the slot stays empty. (An array pattern's element default is the else branch of the bounds + // test, a `ts.If`: MLIRGenImpl::processDeclarationArrayBindingPatternSubPath.) + void settleOwnPatternDefaults(mlir::ModuleOp module) + { + if (compileOptions.memoryModel != MemoryModelOwn) + { + return; + } + + llvm::SmallVector stores; + module.walk([&](mlir_ts::StoreOp storeOp) { + auto varOp = storeOp.getReference().getDefiningOp(); + if (varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && + mlir::isa_and_nonnull( + storeOp->getParentOp())) + { + stores.push_back(storeOp); + } + }); + + // the new value a region yields, where it is made: at its own `ts.Result`, or in a branch of a conditional + // there (`p = e ?? mk(1)`: only the branch that makes one stores it, the other yields its borrow) + std::function storeNewValue = [&](mlir::Operation *resultOp, unsigned index, + mlir::Value slot) { + auto yielded = resultOp->getOperand(index); + auto slotType = mlir::cast(slot.getType()).getElementType(); + auto produced = yielded; + while (true) + { + // (an element of an array of `T | undefined`: the default wrapped as an optional, `ts.OptionalValue`) + if (auto optionalValueOp = produced.getDefiningOp()) + { + produced = optionalValueOp.getIn(); + continue; + } + + auto castOp = produced.getDefiningOp(); + if (!castOp || !mlir::isa(castOp.getType())) + { + break; + } + + produced = castOp.getIn(); + } + + auto *producer = produced.getDefiningOp(); + if (producer && ::typescript::mayTakeOverReference(produced) && yielded.getType() == slotType) + { + producer->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + mlir::OpBuilder builder(resultOp); + builder.create(resultOp->getLoc(), yielded, slot); + auto loadOp = builder.create(resultOp->getLoc(), slotType, slot); + resultOp->setOperand(index, loadOp.getResult()); + return; + } + + // (the one element of a literal made there only to read it, `p = [mk(1)][0]`: that element is the value; the + // literal is not made - it held the element and was never given back) + if (auto loadOp = mlir::dyn_cast_or_null(producer); loadOp && produced == yielded) + { + auto elementRefOp = loadOp.getReference().getDefiningOp(); + auto literal = elementRefOp ? elementRefOp->getOperand(0).getDefiningOp() + : mlir_ts::CreateArrayOp(); + if (literal && literal->getNumOperands() == 1 && literal->getParentRegion() == resultOp->getParentRegion() && + literal->getResult(0).hasOneUse() && elementRefOp->getResult(0).hasOneUse() && loadOp->getResult(0).hasOneUse() && + literal->getOperand(0).getType() == yielded.getType() && literal->getOperand(0).getDefiningOp() && + literal->getOperand(0).getDefiningOp()->hasAttr(OWNED_RESULT_ATTR_NAME) && + !literal->getOperand(0).getDefiningOp()->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME)) + { + auto element = literal->getOperand(0); + resultOp->setOperand(index, element); + loadOp->erase(); + elementRefOp->erase(); + literal->erase(); + if (auto *elementProducer = element.getDefiningOp()) + { + elementProducer->removeAttr(OWNED_RESULT_CONSUMED_ATTR_NAME); + } + + storeNewValue(resultOp, index, slot); + return; + } + } + + if (auto ifOp = mlir::dyn_cast_or_null(producer); + ifOp && produced == yielded && resultOp->getParentRegion()->isAncestor(ifOp->getParentRegion())) + { + auto resultIndex = mlir::cast(produced).getResultNumber(); + for (auto ®ion : ifOp->getRegions()) + { + auto innerResult = region.empty() ? nullptr : region.back().getTerminator(); + if (mlir::isa_and_nonnull(innerResult) && innerResult->getNumOperands() > resultIndex) + { + storeNewValue(innerResult, resultIndex, slot); + } + } + } + }; + + for (auto storeOp : stores) + { + // the store MLIRGen made at the region's end, and the read that follows it: put back to what the region + // yields, then stored where a new value is made + // (a parameter's default ends with `ts.ParamDefaultValue`, processOptionalParam) + auto loadOp = mlir::dyn_cast_or_null(storeOp->getNextNode()); + auto *resultOp = loadOp ? loadOp->getNextNode() : nullptr; + if (!loadOp || loadOp.getReference() != storeOp.getReference() || + !mlir::isa_and_nonnull(resultOp) || + resultOp->getNumOperands() != 1 || resultOp->getOperand(0) != loadOp.getResult()) + { + continue; + } + + auto slot = storeOp.getReference(); + resultOp->setOperand(0, storeOp.getValue()); + loadOp->erase(); + storeOp->erase(); + + // a slot no scope exit releases - made inside an expression (a destructuring assignment in `?:`), which + // does not reach the scope's end (MLIRGenImpl::releaseScopeOwnedVars): taken out, the default is what it + // was without one + if (llvm::none_of(slot.getUsers(), [](mlir::Operation *user) { return mlir::isa(user); })) + { + for (auto *user : llvm::make_early_inc_range(slot.getUsers())) + { + auto emptyStore = mlir::dyn_cast(user); + if (!emptyStore) + { + continue; + } + + auto *emptyValue = emptyStore.getValue().getDefiningOp(); + emptyStore->erase(); + if (mlir::isa_and_nonnull(emptyValue) && emptyValue->use_empty()) + { + emptyValue->erase(); + } + } + + if (slot.use_empty()) + { + slot.getDefiningOp()->erase(); + } + + continue; + } + + // A parameter that may be kept - stored, returned, given to a call or a new literal (`constructor(public + // a = new C())`) - holds its default as it holds an argument: own keeps it, the default moving out with + // it (own_param_default_kept). Only a parameter that is only read borrows the slot. + if (auto paramOptionalOp = mlir::dyn_cast(resultOp->getParentOp())) + { + auto mayKeep = llvm::any_of(paramOptionalOp->getResult(0).getUsers(), [&](mlir::Operation *user) { + auto readOp = mlir::dyn_cast(user); + if (!readOp) + { + return !mlir::isa(user); + } + + std::function handedOn = [&](mlir::Value value) { + return llvm::any_of(value.getUsers(), [&](mlir::Operation *reader) { + if (mlir::isa(reader)) + { + return handedOn(reader->getResult(0)); + } + + return !mlir::isa(reader); + }); + }; + return handedOn(readOp.getResult()); + }); + if (mayKeep) + { + continue; + } + } + + storeNewValue(resultOp, 0, slot); + } + } + // The same disagreement in a default of a destructuring pattern (`const { p = mk(1) } = { p: c ? mk(i) : // undefined }`): `ts.OptValueOrDefault` hands back the value the optional holds - a borrow of the field - or // what its default region makes - a +1 nobody took, so every evaluation that ran the default leaked it. Under rc @@ -3373,7 +3561,7 @@ class OwnedReturnConsumptionPass // at the end of the `if`, and `finally { let n = mk(); for (..) { use(n); n = mk(); } }` at the // end of the loop body; the local then read a freed block. Such a value is left with no one to // give it back - a leak - which is the side the whole arc keeps the uncertain case on. - static bool storedIntoUnownedLocalOutside(mlir::Operation *op) + bool storedIntoUnownedLocalOutside(mlir::Operation *op) { llvm::SmallVector values{op->getResult(0)}; while (!values.empty()) @@ -3432,7 +3620,7 @@ class OwnedReturnConsumptionPass // - what is loaded from a local of the block it is stored into: every use of that local is a load or a // store, or the local is one it can't follow. // A store anywhere else, or a terminator handing it on otherwise (a loop's), is a use it can't follow. - static mlir::Operation *lastUseInBlock(mlir::Operation *op) + mlir::Operation *lastUseInBlock(mlir::Operation *op) { auto *block = op->getBlock(); mlir::Operation *last = op; @@ -3571,11 +3759,16 @@ class OwnedReturnConsumptionPass // What a branch of a conditional expression hands `value` on as: the result of the `ts.If` whose branch this // `ts.Result` ends, at each position the branch yields `value` in - a conditional may yield more than one value // (holdPastConditional adds the literal its branch holds). None for any other user. - static llvm::SmallVector handedOnByConditional(mlir::Operation *user, mlir::Value value) + // (under rc and own also the default of a value-or-default - `const { p = e } = r` hands `e` on as the op's result; + // gc and none keep their IR) + llvm::SmallVector handedOnByConditional(mlir::Operation *user, mlir::Value value) { llvm::SmallVector handedOn; - auto ifOp = mlir::isa(user) ? mlir::dyn_cast_or_null(user->getParentOp()) : mlir_ts::IfOp(); - if (!ifOp || ifOp.getNumResults() != user->getNumOperands()) + auto *conditional = mlir::isa(user) ? user->getParentOp() : nullptr; + if (!conditional || + !(mlir::isa(conditional) || + (compileOptions.tracksOwnership() && mlir::isa(conditional))) || + conditional->getNumResults() != user->getNumOperands()) { return handedOn; } @@ -3584,7 +3777,7 @@ class OwnedReturnConsumptionPass { if (operand.get() == value) { - handedOn.push_back(ifOp.getResult(operand.getOperandNumber())); + handedOn.push_back(conditional->getResult(operand.getOperandNumber())); } } @@ -3703,7 +3896,7 @@ class OwnedReturnConsumptionPass // was born with, and a release before the yield would free what the caller reads. Any store // is treated that way, rather than telling the record apart from a place that does count. // Under rc the record takes a reference of its own (retainYieldedRecords). - static bool escapesThroughStore(mlir::Value value) + bool escapesThroughStore(mlir::Value value) { for (auto *user : value.getUsers()) { @@ -3724,7 +3917,7 @@ class OwnedReturnConsumptionPass } // `yield b ? h : h2` stores what the branch hands on - if (llvm::any_of(handedOnByConditional(user, value), [](mlir::Value handedOn) { return escapesThroughStore(handedOn); })) + if (llvm::any_of(handedOnByConditional(user, value), [&](mlir::Value handedOn) { return escapesThroughStore(handedOn); })) { return true; } diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 1ff0ba24b..62d104acf 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1525,7 +1525,10 @@ inline bool mayWriteField(mlir::Operation *op, mlir_ts::PropertyRefOp field, mli } else if (auto releaseSlotOp = mlir::dyn_cast(inner)) { - writes = writesPlace(releaseSlotOp.getSlot()); + // (a slot owning a default value - a parameter's or a pattern's - frees what a parameter or local + // reading its field may be: `m(p = mk(1)) { return p.x; }` read it after the release) + auto slotOp = releaseSlotOp.getSlot().getDefiningOp(); + writes = writesPlace(releaseSlotOp.getSlot()) || (slotOp && slotOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME)); } else if (auto swapOp = mlir::dyn_cast(inner)) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 31a55db36..fd7530842 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5586,6 +5586,91 @@ foreach(getter_mm rc gc none) tslang_add_test(NAME test-jit-${getter_mm}-getter-temporary COMMAND test-runner -jit -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") tslang_add_test(NAME test-compile-${getter_mm}-getter-temporary COMMAND test-runner -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") endforeach() +# -mm=own: a parameter's default that makes a new value (a function's, a method's, a constructor's, an arrow's, a +# closure's) is owned by the frame's slot (#1015's, for rc) and given back at exit (it leaked); the same program under +# rc and gc. IR: the default stores the new value into the slot and gives a read of it (none before). +foreach(param_default_mm gc rc own) + tslang_add_test(NAME test-jit-${param_default_mm}-own-param-default-new-value COMMAND test-runner -jit -mm=${param_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") + tslang_add_test(NAME test-compile-${param_default_mm}-own-param-default-new-value COMMAND test-runner -mm=${param_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") +endforeach() +add_test(NAME test-own-param-default-slot + COMMAND $ --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") +set_tests_properties(test-own-param-default-slot + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Store\"[(]%[0-9]+, %[0-9]+[)] : [(]!ts[.]class<@N[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[(]%[0-9]+[)] : [(]!ts[.]ref --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_new_value.ts") +set_tests_properties(test-own-pattern-default-slot + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Store\"[(]%[0-9]+, %[0-9]+[)] : [(]!ts[.]class<@N[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[(]%[0-9]+[)] : [(]!ts[.]ref --emit=mlir --no-default-lib -mm=gc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined.ts") +set_tests_properties(test-destructuring-past-end-undefined-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]OptionalUndef\"[(][)] : [(][)] -> !ts[.]optional`), an optional chain out of a literal (`c ? [[mk(i)]][0]?.[0] : null`), or an element of a diff --git a/tslang/test/tester/own/own_array_pattern_default_new_value.ts b/tslang/test/tester/own/own_array_pattern_default_new_value.ts new file mode 100644 index 000000000..3f27283a8 --- /dev/null +++ b/tslang/test/tester/own/own_array_pattern_default_new_value.ts @@ -0,0 +1,81 @@ +// -mm=own: an array pattern's element default that makes a new value (`const [a = mk(1)] = xs`) is held by a slot of +// the scope, as an object pattern's default is, and the element read borrows that slot or the source's element. Own +// refused these patterns once the default was applied (a new value merged with a borrow of the element had no owner): +// an array source, an array of `T | null` and of `T | undefined`, in a `try` body, a nested pattern of a field, a +// destructured parameter of a function (whose slot is the frame's, given back at exit). The same program under rc +// and gc. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +class R { + p?: N; +} + +function v(o: N | undefined | null): number { + return o === undefined ? 1 : o === null ? 2 : o.x + o.s.length; +} + +function param([a = mk(1), b = mk(2)]: N[]): number { + return v(a) + v(b); +} + +function paramOptional([a = mk(3)]: (N | undefined)[], i: number): number { + return v(a) + i; +} + +function paramObject({ p = mk(4) }: R): number { + return v(p); +} + +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const xs: N[] = i % 3 == 0 ? [] : i % 3 == 1 ? [mk(i)] : [mk(i), mk(i + 1)]; + const [a = mk(1), b = mk(2)] = xs; + total += v(a) + v(b); + + const ns: (N | null)[] = i % 2 == 0 ? [null] : []; + const [c = mk(5)] = ns; + total += v(c); + + const us: (N | undefined)[] = i % 2 == 0 ? [undefined, mk(i)] : [mk(i)]; + const [d = mk(6), e = mk(7)] = us; + total += v(d) + v(e); + + try { + const [f = mk(8)] = i % 4 == 0 ? [] : [mk(i)]; + if (i % 5 == 4) throw "x"; + total += v(f); + } catch (err) { + total += 3; + } + + const o = { arr: [mk(i)] }; + const { arr: [g = mk(9), h = mk(10)] } = o; + total += v(g) + v(h); + + const none: N[] = []; + total += param(xs) + param(none); + const noneOptional: (N | undefined)[] = []; + const undefinedOnly: (N | undefined)[] = [undefined]; + total += paramOptional(noneOptional, i) + paramOptional([mk(i)], i) + paramOptional(undefinedOnly, i); + + const r = new R(); + if (i % 2 == 0) r.p = mk(i); + total += paramObject(r); + } + + print(total); + assert(total == 432003, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/own_param_default_new_value.ts b/tslang/test/tester/own/own_param_default_new_value.ts new file mode 100644 index 000000000..8ad1b5f56 --- /dev/null +++ b/tslang/test/tester/own/own_param_default_new_value.ts @@ -0,0 +1,73 @@ +// -mm=own: a parameter's default that makes a new value (`function f(p: N = mk(1))`, a method's, a constructor's, an +// arrow's, a closure's, one reading another parameter) leaked it every call that took the default (main too; rc was +// fixed by #1015's frame slot). Under own the same slot owns it, empty unless the default is taken, given back when +// the function exits; the parameter borrows it. A default that borrows (a global, another parameter) is not stored. +// The same program under rc and gc. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +const G = mk(100); + +@noinline function f(p: N = mk(1)): number { + return p.x + p.s.length; +} + +@noinline function fromParam(a: N, p: N = mk(a.x + 1)): number { + return a.x + p.x; +} + +@noinline function borrows(e: N, p: N = e, q: N = G): number { + return p.x + q.x; +} + +class K { + v: number; + constructor(p: N = mk(2)) { + this.v = p.x; + } + + m(p: N = mk(3)): number { + return p.x; + } +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + const arrow = (p: N = mk(4)): number => p.x; + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const base = i; + const closure = (p: N = mk(base)): number => { + return p.x; + }; + + total += f(c ? mk(i) : undefined); + total += fromParam(mk(i), c ? mk(i) : undefined); + total += borrows(mk(i), c ? mk(i) : undefined, c ? mk(i) : undefined); + total += new K(c ? mk(i) : undefined).v + new K().m(c ? mk(i) : undefined); + total += arrow(c ? mk(i) : undefined) + closure(c ? mk(i) : undefined); + + churn(); + } + + print(total); + assert(total == 541545, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/own_pattern_default_new_value.ts b/tslang/test/tester/own/own_pattern_default_new_value.ts new file mode 100644 index 000000000..7c94ec754 --- /dev/null +++ b/tslang/test/tester/own/own_pattern_default_new_value.ts @@ -0,0 +1,64 @@ +// -mm=own: a pattern's default that makes a new value (`const { p = mk(1) } = r`, `p = e ?? mk(1)`, `p = [mk(1)][0]`, +// `p = "q" + i`) leaked it every evaluation that ran the default (main too): the pattern's value borrows the field +// or the default, and nothing owned the new value. It is now held by a slot of the scope, given back when the scope +// ends, as a local is (a default that borrows, `p = e`, is not). Named records; the same program under rc and gc. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +interface R { + p?: N; +} + +interface RS { + p?: string; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const r: R = c ? { p: mk(i) } : {}; + const rs: RS = c ? { p: "s" + i } : {}; + const e: N | null = i % 4 == 0 ? mk(9) : null; + + const { p = mk(1) } = r; + total += p.x + p.s.length; + + const { p: q = e ?? mk(2) } = r; + total += q.x; + + const { p: w = [mk(3)][0] } = r; + total += w.x + w.s.length; + + const { p: t = "q" + i } = rs; + total += t.length; + + const { p: u = e ?? undefined } = r; + if (u) { + total += u.x; + } + + churn(); + } + + print(total); + assert(total == 164180, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/own_pattern_default_try_switch.ts b/tslang/test/tester/own/own_pattern_default_try_switch.ts new file mode 100644 index 000000000..a9768bfaf --- /dev/null +++ b/tslang/test/tester/own/own_pattern_default_try_switch.ts @@ -0,0 +1,105 @@ +// -mm=own: a pattern's default that makes a new value, in a `try` body or a `switch` case (`try { const { p = mk(9) } +// = r; }`, `case 1: { const { p = mk(9) } = r; }`, a case without a block), failed to compile: its slot was made in +// the TryOp's or SwitchOp's region and released where that region does not reach ("operand #0 does not dominate this +// use"). It is made in front of the TryOp/SwitchOp now, as an owned local is. In a loop too, and with a throw out of +// the try body. The same program under rc and gc. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +class R { + p?: N; + q?: string; +} + +@noinline function mk(i: number): N { + return new N(i); +} + +function mr(i: number, c: boolean): R { + const r = new R(); + if (c) { + r.p = mk(i); + r.q = "q" + i; + } + + return r; +} + +function inTry(i: number): number { + const r = mr(i, i % 2 == 0); + try { + const { p = mk(9) } = r; + if (i % 5 == 4) throw "x"; + return p.x + p.s.length; + } catch (e) { + return 100; + } +} + +function inCaseBlock(i: number): number { + const r = mr(i, i % 3 == 0); + switch (i % 4) { + case 1: { + const { p = mk(7) } = r; + return p.x; + } + case 2: { + const { q = "d" + i } = r; + return q.length; + } + default: + return 1; + } +} + +function inCase(i: number): number { + const r = mr(i, i % 2 == 1); + let n: number = 0; + switch (i % 2) { + case 0: + const { p = mk(5) } = r; + n = p.x; + break; + case 1: + n = 2; + break; + } + + return n; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + total += inTry(i) + inCaseBlock(i) + inCase(i); + + const r = mr(i, i % 2 == 0); + try { + const { p = mk(i + 1) } = r; + if (i % 7 == 3) throw "y"; + total += p.x; + } catch (e) { + total += 1; + } + + switch (i % 3) { + case 0: { + const { p = mk(3) } = r; + total += p.x; + break; + } + default: + total += 2; + } + } + + print(total); + assert(total == 77755, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/rc_destructuring_default_local.ts b/tslang/test/tester/own/rc_destructuring_default_local.ts new file mode 100644 index 000000000..ef438058d --- /dev/null +++ b/tslang/test/tester/own/rc_destructuring_default_local.ts @@ -0,0 +1,55 @@ +// -mm=rc, -mm=own: a pattern's default that is a local (`const e = mk(i + 1); const { p = e } = r`): the default hands +// the local on as the value-or-default's result, which only a conditional's branch was known to do, so the local's +// release took that for an escape and the local leaked every evaluation (+17.5 MB per 400 runs of this loop's shape, +// main too; own too). The local is now given back at the end of its block. A named record, a `let` local, an array +// pattern; the same program under gc. (A record literal source and the assignment form, which own refuses, are in +// rc_destructuring_default_local_literal.) +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +interface R { + p?: N; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const r: R = c ? { p: mk(i) } : {}; + + const e = mk(i + 1); + const { p = e } = r; + total += p.x + p.s.length; + + let f = mk(i + 2); + const { p: q = f } = r; + total += q.x; + + const g = mk(i + 3); + const [a = g] = c ? [mk(i)] : []; + total += a.x; + + churn(); + } + + print(total); + assert(total == 242092, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/rc_destructuring_default_local_literal.ts b/tslang/test/tester/own/rc_destructuring_default_local_literal.ts new file mode 100644 index 000000000..6268bfc2d --- /dev/null +++ b/tslang/test/tester/own/rc_destructuring_default_local_literal.ts @@ -0,0 +1,52 @@ +// -mm=rc: a pattern's default that is a local, from a record literal (`const { p = e } = { p: c ? mk(i) : undefined +// }`) and in the assignment form (`({ p: p2 = e ?? mk(1) } = ...)`, `({ p: p3 = e } = r)`): the local is given back +// at the end of its block (it leaked every evaluation, main too). The same program under gc (own refuses these). +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +interface R { + p?: N; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const r: R = c ? { p: mk(i) } : {}; + + const e = mk(i + 1); + const { p = e } = { p: c ? mk(i) : undefined }; + total += p.x + p.s.length; + + let p2: N = mk(0); + ({ p: p2 = e ?? mk(1) } = { p: c ? mk(i) : undefined }); + total += p2.x; + + let p3: N = mk(0); + ({ p: p3 = e } = r); + total += p3.x; + + churn(); + } + + print(total); + assert(total == 241492, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00const_element_read.ts b/tslang/test/tester/tests/00const_element_read.ts index 376c6cba7..6ca34ff05 100644 --- a/tslang/test/tester/tests/00const_element_read.ts +++ b/tslang/test/tester/tests/00const_element_read.ts @@ -1,8 +1,8 @@ // A `const` read out of an element keeps what it read alive when the element is given a new value. // Folded, the const was the read itself and held no reference of its own: under rc the overwrite // freed the block it still read. Allocations of the same size reuse anything freed before each -// read. A destructuring past the end of an array gives the element type's default (null for a -// reference), not whatever follows the array's data. +// read. A destructuring past the end of an array gives undefined for a reference (== null) and the +// element type's default for a number or a string, not whatever follows the array's data. class C { constructor(public x: number) {} } @@ -49,7 +49,7 @@ function pastTheEnd() { const [a, b, c] = pair; let [d, e, f] = pair; assert(a.x == 1 && b.x == 2 && d.x == 1 && e.x == 2, "in bounds"); - assert(c == null && f == null, "a class element past the end is null"); + assert(c === undefined && f === undefined, "a class element past the end is undefined"); const words: string[] = ["a", "b"]; const [w0, w1, w2] = words; diff --git a/tslang/test/tester/tests/00destructuring_default_past_end.ts b/tslang/test/tester/tests/00destructuring_default_past_end.ts new file mode 100644 index 000000000..645ab13e4 --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_default_past_end.ts @@ -0,0 +1,39 @@ +// Array destructuring past the end of its source: an element's default is its value where the element is missing +// (`const [a = 1, b = 2] = [5]`: b is 2, as in TypeScript). It was not applied: the default of the element type was +// used (b was 0, a string null), and with objects (`const [a = mk(1), b = mk(2)] = [mk(5)]`, a typed tuple, a nested +// pattern, a for...of pattern) the compiler crashed. Numbers, strings, a typed array, an undefined element, a +// parameter pattern of numbers; every memory model. (Objects: 00destructuring_default_past_end_objects.ts.) +function sum([a = 1, b = 2]: number[]): number { + return a + b; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const [a = 1, b = 2] = [i]; + total += a + b; + + const [s = "x", t = "y"] = ["s" + i]; + total += s.length + t.length; + + const xs: number[] = []; + if (i % 2 == 0) { + xs.push(i); + } + + const [p = 1, q = 2] = xs; + total += p + q; + + const [u = 3] = [undefined]; + total += u; + + const [v, w = "q"] = [i]; + total += v + w.length; + + total += sum([i]) + sum([]); + } + + print(total); + assert(total == 19040, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts b/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts new file mode 100644 index 000000000..088035337 --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts @@ -0,0 +1,48 @@ +// Array destructuring past the end of its source, with objects: an element's default is its value where the element +// is missing (`const [a = mk(1), b = mk(2)] = [mk(i)]`: b is mk(2)). The compiler crashed on these (the element read +// past the end of the literal was an undefined value read as an object): a literal, a typed tuple, a nested pattern, +// a for...of pattern, a parameter pattern, an assignment. Under gc and rc (own refuses a borrow of the literal's +// element beside a new default). +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +function mk(i: number): N { + return new N(i); +} + +function pick([a = mk(1), b = mk(2)]: N[]): number { + return a.x + b.x; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const [a = mk(1), b = mk(2)] = [mk(i)]; + total += a.x + b.x; + + const t: [N] = [mk(i)]; + const [e, f = mk(3)] = t; + total += e.x + f.x; + + const [[g, h = mk(4)]] = [[mk(i)]]; + total += g.x + h.x; + + for (const [p, q = mk(10)] of [[mk(i)]]) { + total += p.x + q.x; + } + + let k: N, m: N; + [k, m = mk(8)] = [mk(i)]; + total += k.x + m.x; + + total += pick([mk(i)]) + pick([]); + } + + print(total); + assert(total == 32900, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00destructuring_past_end_undefined.ts b/tslang/test/tester/tests/00destructuring_past_end_undefined.ts new file mode 100644 index 000000000..04ac26524 --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_past_end_undefined.ts @@ -0,0 +1,57 @@ +// An element past the end of an array value, without a default, is undefined, as node has it (`const [a, b] = [mk(5)] +// as N[]`: b). Of an array of a reference type (a class, `N | null`, an array) the name is `T | undefined` and reads +// undefined; it read null. Nested patterns, for-of, parameters, in a loop. A +// primitive element (number[], string[]) keeps its type, which cannot hold undefined: it reads as the type's default, +// as before (node: undefined). Every memory model. +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +function sh(o: N | undefined | null): string { + return o === undefined ? "u" : o === null ? "null" : "N" + o.x; +} + +function param([a, b]: N[]): string { + return sh(a) + "," + sh(b); +} + +function main() { + let out = ""; + for (let i = 0; i < 50; i++) { + const [a, b] = [mk(i)] as N[]; + assert(b === undefined, "b undefined"); + out = sh(a) + " " + sh(b); + + const nullable: (N | null)[] = i % 2 == 0 ? [null] : [mk(i)]; + const [c, d] = nullable; + out += " " + sh(c) + " " + sh(d); + + const nested: N[][] = [[mk(i)]]; + const [[k, l], m] = nested; + assert(m === undefined, "m undefined"); + out += " " + sh(k) + " " + sh(l); + + const pairs: N[][] = [[mk(1)], [mk(2), mk(3)]]; + for (const [q, r] of pairs) { + out += " " + sh(q) + sh(r); + } + + out += " " + param([mk(4)]) + " " + param([]); + } + + print(out); + assert(out == "N49 u N49 u N49 u N1u N2N3 N4,u u,u", "objects"); + + // primitives keep their type's value + const ns: number[] = [1]; + const [e, f] = ns; + assert(e == 1 && f == 0, "number"); + print("done."); +} diff --git a/tslang/test/tester/tests/00destructuring_past_end_undefined_assign.ts b/tslang/test/tester/tests/00destructuring_past_end_undefined_assign.ts new file mode 100644 index 000000000..3ff3aa7bf --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_past_end_undefined_assign.ts @@ -0,0 +1,34 @@ +// The assignment form: an element past the end of an array value, without a default, gives a target that can hold +// undefined (`let t: N | undefined; [s, t] = xs`) undefined, as node has it (it read whatever followed the array's +// data). gc, rc and none (own refuses storing a borrowed element into an outer `let`, as before). +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +function sh(o: N | undefined | null): string { + return o === undefined ? "u" : o === null ? "null" : "N" + o.x; +} + +function main() { + let out = ""; + for (let i = 0; i < 50; i++) { + let s: N | undefined = mk(9); + let t: N | undefined = mk(9); + [s, t] = [mk(i)] as N[]; + let w: N | null | undefined = mk(9); + const none: N[] = []; + [w] = none; + out = sh(s) + " " + sh(t) + " " + sh(w); + } + + print(out); + assert(out == "N49 u u", "assign"); + print("done."); +} diff --git a/tslang/test/tester/tests/00own_pattern_default_in_expression_error.ts b/tslang/test/tester/tests/00own_pattern_default_in_expression_error.ts new file mode 100644 index 000000000..06c6fdac9 --- /dev/null +++ b/tslang/test/tester/tests/00own_pattern_default_in_expression_error.ts @@ -0,0 +1,28 @@ +// -mm=own: a destructuring assignment with a default that makes a new value, inside an expression (`c ? ({ p = +// mk(9) } = r) : ...`), is refused as before, with the ownership error - it failed with an internal one ("operand #0 +// does not dominate this use"): the default's slot, made inside the conditional, is not the scope's. +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +class R { + p?: N; +} + +function mk(i: number): N { + return new N(i); +} + +function main() { + const r = new R(); + let p: N = mk(0); + for (let i = 0; i < 4; i++) { + const v = i % 3 == 0 ? (({ p = mk(9) } = r), p.x) : 0; + print(v); + } + + print("done."); +}