diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index d88da77eb..00398a423 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -698,9 +698,10 @@ a reference gives it back on every path out of a function. - The default library has an `-mm=own` build, and arrays, strings and their methods work. `Map` and `Set` work with number, boolean and string keys and values (`new Map()`, - `new Set([1, 2])`): their iterators borrow the container, and strings go in as copies. With - `any` or object keys or values they do not compile yet, which includes a `new Map()` with no - type arguments and nothing to infer them from. + `new Set([1, 2])`): their iterators borrow the container, and strings go in as copies. An + object goes in as a `Shared` handle (`new Map>()`); a plain object or + `any` key or value is a compile error that points at `Shared`, which includes a `new Map()` + with no type arguments and nothing to infer them from. - Array methods that keep elements of the source in a new array (`filter` over class instances) give each such element a second owner, which is an error by design. Use `Shared` elements, or build the result from copies. diff --git a/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md b/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md index b3dddb9af..452f62dca 100644 --- a/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md +++ b/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md @@ -79,7 +79,7 @@ kinds: ## 4. Not here -- `any` or object keys and values. The constructor from an array (`new Map([[k, v]])`) cannot take +- `any` or object keys and values (settled in section 6: through `Shared`). The constructor from an array (`new Map([[k, v]])`) cannot take the elements out of the caller's array, and moving an object parameter into a tuple (`Retain` of a tuple made of kept parameters) is "takes a second reference". This waits on the ruling on containers of owned values (two sets sharing an element by `union` is two owners). @@ -103,3 +103,39 @@ Positive, under own (AOT and JIT): `own_generator_method_this`, `own_string_copy `own_length_drops_elements`, `own_tuple_param_kept`; each also prints the same under gc, rc and none. Errors: `own_err_generator_method_reassigned`, `own_err_callback_method_overridden`. Retired: `own_err_param_kept_some_paths` (rule 5), `own_err_string_call_keeps_twice` (rule 4). + +## 6. Objects in `Map` and `Set`: `Shared` + +Ruling (2026-10-26): under own an object goes into a `Map` or `Set` as a `Shared` handle; a plain +object or `any` element is a compile error at the user's code that points at `Shared`. A container +keeps what it is given and hands out borrows of it (`get`, the iterators), and `union` or two maps +holding one value would be two owners of a block with one owner. A handle is counted (spec 23.2), +so it can be in any number of entries; values and strings (copied in, rule 4) need nothing. + +- **`@sharedElements`** (`SHARED_ELEMENTS_DECORATOR`), on a generic class: under own each type + argument has to be a value (owns no heap memory), a string, or a handle (`isSharedHandleType`, so + `Shared | null` too). `checkSharedElements` runs where the class is specialized + (`instantiateSpecializedClassType`, both overloads), with the location of the user's `new` or type + annotation, before the members are generated, whose errors would point into the library: + `-mm=own: 'Map' cannot hold 'Node' (its 'V'): an element has to be a value, a string or a Shared + handle; use 'Shared'`, and for `any` `give it one of those types`. Keys are checked as values + are. A `new` whose inferred type arguments were refused does not go on to the defaults + (`sharedElementsRefused`), which would report `any` too. The other models ignore it. DefaultLib puts + it on `Map` and `Set`; nothing in the compiler names them. +- **A handle in a tuple entry** (`copyIntoTuple`): a tuple made of a handle beside borrowed strings + retains the handle for the tuple, as it copies the strings (`>[hash, next, key, value]`). +- **A handle a yield takes out of the state.** A field read only to be yielded + (`OWN_YIELDED_FIELDS_ATTR_NAME`) gives its value to the caller, who owns the record `next` returns + and releases it; the state's release of the old value is erased. A handle's counting is rc's and + stays (spec 23.2), and that kept this release too: each step released the previous handle twice, + once in the state and once in the caller (a `Map` of two handles walked by `for...of` freed the + first). The release of a yielded field is now erased for a handle as for anything else. +- **The owned result of a virtual call** (`OwnedReturnConsumptionPass`): whether every method a + vtable call can reach returns its result owned was decided over every method of that name in the + module, so with the default library loaded `A.get` stood beside `Headers.get` and the like, the + call was not +1, and an rc handle it returned leaked. Now only methods of a class on the receiver's + chain (its bases and the classes extending it) count (`onReceiverChain`). + +Tests: `own_shared_elements` (a local `@sharedElements` container of numbers, strings and handles, +under every model), `own_shared_yield_count` (two entries walked, a pair yielded, a `break`; counts +under rc and own), `own_err_shared_elements_object`, `_any`, `_inferred`. diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 44626ac46..982905bcc 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -363,6 +363,11 @@ // `@value class C` / `@value interface R`: a type whose values are copied, not shared - no identity, // no vtable, no base (docs/superpowers/specs/2026-10-24-value-types-design.md) #define VALUE_DECORATOR "value" +// `@sharedElements class Map`: a container that keeps what it is given and hands out +// borrows of it. Under -mm=own each of its type arguments has to be a value, a string (copied) or +// a Shared handle (counted): an object, whose block has one owner, goes through Shared. +// The other memory models ignore it. +#define SHARED_ELEMENTS_DECORATOR "sharedElements" // On a `ts.ThisVirtualSymbolRef` (a method's) or a `ts.VirtualSymbolRef` (an accessor's): the // receiver's class is @final, but defined in another module, so the call still goes through the // vtable. The slot holds the method the reference names, which diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 6cb83f10f..478cede5d 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1309,6 +1309,8 @@ namespace mlirgen EXIT_IF_FAILED_OR_NO_VALUE(result) auto value = V(result); auto unspecialized = deferDefaults ? value : mlir::Value(); + MLIRValueGuard sharedElementsRefusedGuard(sharedElementsRefused); + sharedElementsRefused = false; // `new Set([2, 4, 6, 8])`: a generic class written without type arguments takes them from // its constructor's arguments (see inferClassTypeFromConstructorArguments). Ahead of the @@ -1341,6 +1343,12 @@ namespace mlirgen } } + // the inferred type arguments were refused (checkSharedElements): already reported + if (sharedElementsRefused) + { + return mlir::failure(); + } + // `const m: Map = new Map()`: a generic class written without type // arguments takes them from the type it is given to, when that is the same class. Its // type parameter defaults (`Map`) made Map otherwise, a diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index b7b20202d..0e729e0c1 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -1156,6 +1156,66 @@ namespace mlirgen return {mlir::success(), funcProto}; } + // A @sharedElements container (Map, Set) keeps what it is given and hands out borrows of it, so + // under -mm=own each type argument has to be a value, a string (copied in) or a Shared handle + // (counted in). Checked where the user names the type, before its members are generated: their + // errors would point into the library. + mlir::LogicalResult MLIRGenImpl::checkSharedElements(mlir::Location location, + GenericClassInfo::TypePtr genericClassInfo, + const GenContext &genericTypeGenContext, + const GenContext &genContext) + { + if (compileOptions.memoryModel != MemoryModelOwn) + { + return mlir::success(); + } + + auto sharedElements = false; + iterateDecorators(genericClassInfo->classDeclaration, genContext, [&](StringRef name, SmallVector args) { + sharedElements = sharedElements || name == SHARED_ELEMENTS_DECORATOR; + }); + if (!sharedElements) + { + return mlir::success(); + } + + MLIRTypeHelper mth(builder.getContext(), compileOptions); + auto result = mlir::success(); + for (auto &typeParam : genericClassInfo->typeParams) + { + auto found = genericTypeGenContext.typeParamsWithArgs.find(typeParam->getName()); + if (found == genericTypeGenContext.typeParamsWithArgs.end()) + { + continue; + } + + auto type = mth.stripLiteralType(std::get<1>(found->getValue())); + if (!type || mlir::isa(type) || mlir::isa(type) || + MLIRTypeHelper::isSharedHandleType(type) || !mth.ownsHeapMemory(location, type)) + { + continue; + } + + auto diag = emitError(location) << "-mm=own: '" << genericClassInfo->name << "' cannot hold '" << to_print(type) + << "' (its '" << typeParam->getName() + << "'): an element has to be a value, a string or a Shared handle; "; + if (mlir::isa(type)) + { + diag << "give it one of those types"; + } + else + { + diag << "use 'Shared<" << to_print(type) << ">'"; + } + + result = mlir::failure(); + } + + sharedElementsRefused = sharedElementsRefused || mlir::failed(result); + + return result; + } + std::pair MLIRGenImpl::instantiateSpecializedClassType(mlir::Location location, mlir_ts::ClassType genericClassType, NodeArray typeArguments, @@ -1205,6 +1265,11 @@ namespace mlirgen declarationMode = false; // create new instance of interface with TypeArguments + if (mlir::failed(checkSharedElements(location, genericClassInfo, genericTypeGenContext, genContext))) + { + return {mlir::failure(), mlir::Type()}; + } + auto ownLayout = suspendValueLayoutFrames(); if (mlir::failed(std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext)))) { @@ -1288,6 +1353,12 @@ namespace mlirgen MLIRValueGuard declarationModeGuard(declarationMode); declarationMode = false; + if (mlir::failed(checkSharedElements(location, genericClassInfo, genericTypeGenContext, genContext))) + { + count--; + return {mlir::failure(), mlir::Type()}; + } + auto ownLayout = suspendValueLayoutFrames(); auto res = std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext)); count--; diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 48760fd72..802f86b4d 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -1652,6 +1652,9 @@ class MLIRGenImpl const GenContext &genContext, bool allowNamedGenerics = false); + mlir::LogicalResult checkSharedElements(mlir::Location location, GenericClassInfo::TypePtr genericClassInfo, + const GenContext &genericTypeGenContext, const GenContext &genContext); + mlir_ts::ClassType inferClassTypeFromConstructorArguments(mlir::Location location, GenericClassInfo::TypePtr genericClassInfo, NodeArray arguments, @@ -15859,6 +15862,10 @@ class MLIRGenImpl // on it (mlirGenOptionalChain) llvm::DenseMap optionalChainObjects; + // set when checkSharedElements refuses a type argument: a `new` whose inferred type arguments + // were refused does not go on to the defaults (`any`), which would only be refused again + bool sharedElementsRefused = false; + // the declaration (no body) each declared function's full name came from, and the module it was // generated into - discovery's is thrown away, and a library's __decls is parsed again for the // next pass; see mlirGen(FunctionDeclaration) diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 17eae3895..0513705e6 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -82,9 +82,9 @@ class OwnedReturnConsumptionPass } llvm::DenseSet returnsOwned; - // Every method in the module, grouped by the name after the last dot: the candidate set - // for a virtual call, see virtualCallReturnsOwned. - llvm::StringMap> methodsByMemberName; + // Every method in the module, grouped by the name after the last dot, with the class it + // takes first: the candidate set for a virtual call, see virtualCallReturnsOwned. + llvm::StringMap>> methodsByMemberName; // Is there any function here at all that hands back a heap value without retaining it? // See callThroughValueReturnsOwned. auto anyUnclassifiedOwningReturn = false; @@ -121,7 +121,7 @@ class OwnedReturnConsumptionPass auto dot = name.rfind('.'); if (isClassMethod && dot != mlir::StringRef::npos && dot + 1 < name.size()) { - methodsByMemberName[name.substr(dot + 1)].push_back(name); + methodsByMemberName[name.substr(dot + 1)].push_back({name, inputs.front()}); } }); @@ -2274,7 +2274,7 @@ class OwnedReturnConsumptionPass // callee's return had added. See section 9.53. static bool virtualCallReturnsOwned(mlir_ts::CallIndirectOp callOp, const llvm::DenseSet &returnsOwned, - const llvm::StringMap> &methodsByMemberName) + const llvm::StringMap>> &methodsByMemberName) { if (callOp.getNumOperands() == 0) { @@ -2293,13 +2293,56 @@ class OwnedReturnConsumptionPass return false; } - return everyOverrideReturnsOwned(virtualRefOp.getIdentifier(), returnsOwned, methodsByMemberName); + return everyOverrideReturnsOwned(virtualRefOp.getIdentifier(), returnsOwned, methodsByMemberName, + virtualRefOp.getThisVal().getType()); + } + + // Is `classType` the class `receiverType` names, or on its chain of bases or derived classes? A + // method of another class shares the member name only: no object of the receiver's type has + // it in that slot. A base is the first field of a class's storage; a class whose storage this + // cannot see may be on the chain. + static bool onReceiverChain(mlir::Type classType, mlir::Type receiverType) + { + auto storageOf = [](mlir::Type type) { + if (auto refClass = mlir::dyn_cast(type)) + { + return mlir::dyn_cast(refClass.getStorageType()); + } + + return mlir::dyn_cast(type); + }; + + auto candidate = storageOf(classType); + auto receiver = storageOf(receiverType); + if (!candidate || !receiver) + { + return true; + } + + auto extends = [](mlir_ts::ClassStorageType derived, mlir_ts::ClassStorageType base) { + for (auto depth = 0; derived && depth < 64; ++depth) + { + if (derived.getName() == base.getName()) + { + return true; + } + + auto fields = derived.getFields(); + derived = fields.empty() ? mlir_ts::ClassStorageType() : mlir::dyn_cast(fields.front().type); + } + + return false; + }; + + return extends(candidate, receiver) || extends(receiver, candidate); } // Does every method that can be in the slot `identifier` was written against return owned? + // With the receiver's type, only methods of classes on its chain can be there. static bool everyOverrideReturnsOwned(mlir::StringRef identifier, const llvm::DenseSet &returnsOwned, - const llvm::StringMap> &methodsByMemberName) + const llvm::StringMap>> &methodsByMemberName, + mlir::Type receiverType = mlir::Type()) { auto dot = identifier.rfind('.'); if (dot == mlir::StringRef::npos || dot + 1 >= identifier.size()) @@ -2313,15 +2356,24 @@ class OwnedReturnConsumptionPass return false; } - for (auto candidate : candidates->second) + // none on the chain: the method is not one this module has, unclassified + auto any = false; + for (auto [candidate, classType] : candidates->second) { + if (receiverType && !onReceiverChain(classType, receiverType)) + { + continue; + } + if (!returnsOwned.contains(candidate)) { return false; } + + any = true; } - return true; + return any; } // The same question for a call through an interface, where the member name is not enough to @@ -2426,7 +2478,7 @@ class OwnedReturnConsumptionPass // name), or an interface slot (what the vtables put there). A getter given as anything // else - `ts.Undef` when there is only a setter - is unclassified. static bool getterReturnsOwned(mlir::Operation *op, const llvm::DenseSet &returnsOwned, - const llvm::StringMap> &methodsByMemberName, + const llvm::StringMap>> &methodsByMemberName, const llvm::StringMap> &vtableSlots) { auto named = [&](mlir::FlatSymbolRefAttr getter) { @@ -2459,7 +2511,7 @@ class OwnedReturnConsumptionPass if (auto thisVirtualSymbolRefOp = mlir::dyn_cast(definingOp)) { return everyOverrideReturnsOwned(thisVirtualSymbolRefOp.getIdentifier(), returnsOwned, - methodsByMemberName); + methodsByMemberName, thisVirtualSymbolRefOp.getThisVal().getType()); } if (auto interfaceRefOp = mlir::dyn_cast(definingOp)) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 3472d8dbe..635281b7a 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -115,8 +115,13 @@ namespace own_inference return failures == 0; } - // a handle's retains and releases are rc's, and stay (spec 23.2) - toErase.remove_if([](mlir::Operation *op) { return touchesHandle(op); }); + // a handle's retains and releases are rc's, and stay (spec 23.2); but not the release of a + // yielded field's old value: the yield gave the state's count to the caller, who owns the + // record `next` returns and releases it + toErase.remove_if([&](mlir::Operation *op) { + auto releaseSlotOp = mlir::dyn_cast(op); + return touchesHandle(op) && !(releaseSlotOp && isYieldedField(releaseSlotOp.getSlot())); + }); placeEdgeReleases(); // what owns nothing gives nothing back, wherever the moves put its releases (spec 36) dropUnboxedRecordCounts(toErase); @@ -668,8 +673,9 @@ namespace own_inference bool OwnershipInferencePass::copyIntoTuple(mlir_ts::RetainOp retainOp) { // `[s, n]` of a borrowed string: rc retains the tuple, which retains the string in it. The - // tuple starts from a copy instead, which is its own (spec 22). Only when strings are all it - // holds blocks of: a borrowed object in it cannot be copied. + // tuple starts from a copy instead, which is its own (spec 22). A handle in it takes a count + // of its own, which own leaves to rc (spec 23.2): `[key, shared]`. Only when strings and + // handles are all it holds blocks of: a borrowed object in it cannot be copied. auto createTupleOp = retainOp.getReference().getDefiningOp(); if (!createTupleOp || createTupleOp->getBlock() != retainOp->getBlock() || !createTupleOp->isBeforeInBlock(retainOp)) @@ -678,6 +684,7 @@ namespace own_inference } llvm::SmallVector borrowed; + llvm::SmallVector handles; for (auto &operand : createTupleOp->getOpOperands()) { auto field = operand.get(); @@ -686,6 +693,12 @@ namespace own_inference continue; } + if (isHandle(field)) + { + handles.push_back(field); + continue; + } + if (!isCopyableString(field.getType()) || borrowsKnownParam(field)) { return false; @@ -694,7 +707,7 @@ namespace own_inference borrowed.push_back(&operand); } - if (borrowed.empty()) + if (borrowed.empty() && handles.empty()) { return false; } @@ -705,6 +718,12 @@ namespace own_inference operand->set(builder.create(retainOp->getLoc(), operand->get().getType(), operand->get())); } + builder.setInsertionPoint(retainOp); + for (auto handle : handles) + { + builder.create(retainOp->getLoc(), handle); + } + retainOp->erase(); return true; } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 176374aed..76e0f77b5 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -172,8 +172,8 @@ class OwnershipInferencePass // without the twinReadAfter fallback: a retain whose value has no use of its own is not copied, // so its error stays. bool copyForRetain(mlir::Operation *retain); - // A retain of a tuple `ts.CreateTuple` made from borrowed strings (`[s, n]`): the strings are - // copied into it instead, and the retain goes. + // A retain of a tuple `ts.CreateTuple` made from borrowed strings and handles (`[s, shared]`): the + // strings are copied into it instead, each handle is retained alone, and the retain goes. bool copyIntoTuple(mlir_ts::RetainOp retainOp); // The parameter this function's result borrows (`__own_result_borrows`), or -1; and the diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 3e7c359bc..dbf90bb9e 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4241,7 +4241,8 @@ foreach(shared_mm ${shared_models}) foreach(shared_test own_shared_basic own_shared_user_named own_shared_graph own_shared_containers own_shared_cycle own_shared_union own_shared_global own_shared_unlink own_shared_global_init own_shared_place_two_uses own_shared_global_field own_shared_global_copy own_shared_argument_assigned - own_shared_global_argument own_shared_global_argument_throw own_shared_param_assigned) + own_shared_global_argument own_shared_global_argument_throw own_shared_param_assigned + own_shared_elements) tslang_add_test(NAME test-jit-${shared_mm}-${shared_test} COMMAND test-runner -jit -mm=${shared_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${shared_test}.ts") tslang_add_test(NAME test-compile-${shared_mm}-${shared_test} COMMAND test-runner -mm=${shared_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${shared_test}.ts") endforeach() @@ -4250,13 +4251,16 @@ endforeach() foreach(shared_count_mm rc own) tslang_add_test(NAME test-jit-${shared_count_mm}-own_shared_count COMMAND test-runner -jit -mm=${shared_count_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_shared_count.ts") tslang_add_test(NAME test-compile-${shared_count_mm}-own_shared_count COMMAND test-runner -mm=${shared_count_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_shared_count.ts") + tslang_add_test(NAME test-jit-${shared_count_mm}-own_shared_yield_count COMMAND test-runner -jit -mm=${shared_count_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_shared_yield_count.ts") + tslang_add_test(NAME test-compile-${shared_count_mm}-own_shared_yield_count COMMAND test-runner -mm=${shared_count_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_shared_yield_count.ts") endforeach() # --verify-ownership is quiet on every positive (spec 23.5): handles keep rc's pairing. foreach(shared_verify_mm own rc) foreach(shared_test own_shared_basic own_shared_graph own_shared_count own_shared_containers own_shared_cycle own_shared_union own_shared_global own_shared_unlink own_shared_global_init own_shared_place_two_uses own_shared_global_field own_shared_global_copy own_shared_argument_assigned - own_shared_global_argument own_shared_global_argument_throw own_shared_param_assigned) + own_shared_global_argument own_shared_global_argument_throw own_shared_param_assigned + own_shared_elements) add_test(NAME test-${shared_verify_mm}-verify-ownership-${shared_test} COMMAND $ --emit=mlir-affine --no-default-lib -mm=${shared_verify_mm} --verify-ownership "${PROJECT_SOURCE_DIR}/test/tester/own/${shared_test}.ts") @@ -4610,6 +4614,9 @@ set(own_error_cases "own_err_keeper_exported|:7:5: error: 'Registry[.]register' keeps '#1' for good, but -mm=own cannot tell its callers in other modules. '@immortalizes' would say it in its signature" "own_err_keeper_declared|:5:1: error: '@immortalizes' of 'keep' names 'a', but its body keeps for good 'b'" "own_err_keeper_called_through_value|:6:1: error: 'keep' keeps '#0' for good, but -mm=own cannot make every caller make it immortal: the function is called through a value" + "own_err_shared_elements_object|:13:21: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]: an element has to be a value, a string or a Shared handle. use 'Shared'" + "own_err_shared_elements_any|:8:21: error: -mm=own: 'Bag' cannot hold 'any' [(]its 'T'[)]: an element has to be a value, a string or a Shared handle. give it one of those types" + "own_err_shared_elements_inferred|:12:17: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]" "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) diff --git a/tslang/test/tester/own/own_err_shared_elements_any.ts b/tslang/test/tester/own/own_err_shared_elements_any.ts new file mode 100644 index 000000000..91d4d69f6 --- /dev/null +++ b/tslang/test/tester/own/own_err_shared_elements_any.ts @@ -0,0 +1,10 @@ +// -mm=own rejects: a @sharedElements container of `any`, which may hold an object. +@sharedElements +class Bag { + items: T[] = []; +} + +function main() { + const bag = new Bag(); + print(bag.items.length); +} diff --git a/tslang/test/tester/own/own_err_shared_elements_inferred.ts b/tslang/test/tester/own/own_err_shared_elements_inferred.ts new file mode 100644 index 000000000..4de6aff49 --- /dev/null +++ b/tslang/test/tester/own/own_err_shared_elements_inferred.ts @@ -0,0 +1,14 @@ +// -mm=own rejects: type arguments inferred from the constructor's arguments are checked too. +@sharedElements +class Bag { + constructor(public items: T[]) {} +} + +class Node { + constructor(public n: number) {} +} + +function main() { + const bag = new Bag([new Node(1)]); + print(bag.items.length); +} diff --git a/tslang/test/tester/own/own_err_shared_elements_object.ts b/tslang/test/tester/own/own_err_shared_elements_object.ts new file mode 100644 index 000000000..76146b523 --- /dev/null +++ b/tslang/test/tester/own/own_err_shared_elements_object.ts @@ -0,0 +1,15 @@ +// -mm=own rejects: a @sharedElements container cannot hold an object, whose block has one owner; +// the error names the type argument at the user's `new`, and points at Shared. +@sharedElements +class Bag { + items: T[] = []; +} + +class Node { + constructor(public n: number) {} +} + +function main() { + const bag = new Bag(); + print(bag.items.length); +} diff --git a/tslang/test/tester/own/own_shared_elements.ts b/tslang/test/tester/own/own_shared_elements.ts new file mode 100644 index 000000000..f24b036bd --- /dev/null +++ b/tslang/test/tester/own/own_shared_elements.ts @@ -0,0 +1,36 @@ +// A @sharedElements container holds values, strings and Shared handles under every memory model; +// under -mm=own an object goes in through Shared (own_err_shared_elements_*). +@sharedElements +class Bag { + items: T[] = []; + + add(item: T) { + this.items.push(item); + } + + get size() { + return this.items.length; + } +} + +class Node { + constructor(public n: number) {} +} + +function main() { + const numbers = new Bag(); + numbers.add(1); + numbers.add(2); + + const names = new Bag(); + names.add("a"); + + const node = new Shared(new Node(7)); + const nodes = new Bag>(); + nodes.add(node); + nodes.add(node); + + assert(numbers.size == 2 && names.size == 1 && nodes.size == 2); + assert(nodes.items[1].value.n == 7); + print("done."); +} diff --git a/tslang/test/tester/own/own_shared_yield_count.ts b/tslang/test/tester/own/own_shared_yield_count.ts new file mode 100644 index 000000000..9ed7b3583 --- /dev/null +++ b/tslang/test/tester/own/own_shared_yield_count.ts @@ -0,0 +1,72 @@ +// A generator over `this` yields a Shared it reads into a state field: the yield hands the +// state's count to the caller, who owns what `next` returns. Leaving the loop early, or walking two +// entries, gives every count back (Map's values(), entries()). +class Node { + constructor(public n: number) {} +} + +type Entry = [key: string, value: Shared]; + +class Store { + entries: Entry[] = []; + + put(key: string, value: Shared) { + this.entries.push([key, value]); + } + + @borrows("this") + *values() { + for (let i = 0; i < this.entries.length; i++) { + const value = this.entries[i].value; + yield value; + } + } + + @borrows("this") + *pairs() { + for (let i = 0; i < this.entries.length; i++) { + const key = this.entries[i].key; + const value = this.entries[i].value; + yield [key, value]; + } + } +} + +function walkValues(x: Shared, y: Shared) { + const store = new Store(); + store.put("a", x); + store.put("b", y); + let total = 0; + for (const v of store.values()) total += v.value.n; + assert(total == 15); +} + +function walkPairs(x: Shared, y: Shared) { + const store = new Store(); + store.put("a", x); + store.put("b", y); + let total = 0; + for (const [k, v] of store.pairs()) total += v.value.n; + assert(total == 15); +} + +function leaveEarly(x: Shared, y: Shared) { + const store = new Store(); + store.put("a", x); + store.put("b", y); + for (const v of store.values()) { + if (v.value.n == 7) break; + } +} + +function main() { + const x = new Shared(new Node(7)); + const y = new Shared(new Node(8)); + walkValues(x, y); + assert(Shared.count(x) == 1 && Shared.count(y) == 1); + walkPairs(x, y); + assert(Shared.count(x) == 1 && Shared.count(y) == 1); + leaveEarly(x, y); + assert(Shared.count(x) == 1 && Shared.count(y) == 1); + print("done."); +}