From 8e430fe1ff45e173fcbe69876b3aba75a89bcd15 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 5 Dec 2026 11:57:25 +0000 Subject: [PATCH] -mm=own: own facts carry fresh results of functions that may free anything, result places and private functions; named call results survive the canonicalizer; throwing stubs stay internal (TSLANG 236-246) - 236: a result that borrows one argument says in the facts which places of it it reads (`name\t@ `), so an overwrite of another place of that type two modules away (Map.set, an int[] field reassigned) leaves the borrow alone. - 240: a function that may free anything still says its result is fresh (`name\tany\tfresh`), and private functions whose declarations an importer re-parses say so too (`name\tlocal\tfresh`, never shadowing an exported line); ORC's closed world no longer turns off on them. - ORC: a virtual call names an unclassified method only when that method's class is on the receiver's chain (JsonValue.at is not Part.at); taken as one, the call's owned result became a borrow and leaked (golden_line_loco.ts once the closed world held). - 238: the "named const" mark of a call result survives SimplifyIndirectCallWithKnownCallee and the call lowering (OWNED_RESULT_NAMED_CALL_ATTR_NAME). - 245: rc's release of a merge of borrowing calls is bookkeeping, not a keeper. - 243: a @value class's throwing `..missing` stub has internal linkage, so two objects link. Tests: own-facts-246 (own and gc, two objects), own-facts-246-virtual (mimalloc stats show no leak), 00tslang_issue_245, 00tslang_issue_246_named_call, own_err_merged_borrowing_calls_reset. Co-Authored-By: Claude Opus 5.5 --- docs/own-memory-model.md | 6 +- tslang/include/TypeScript/Defines.h | 23 ++++ tslang/lib/TypeScript/LowerToAffineLoops.cpp | 18 ++- tslang/lib/TypeScript/MLIRGenInterfaces.cpp | 3 + tslang/lib/TypeScript/MLIRGenModule.cpp | 78 +++++++++++- .../TypeScript/OwnedReturnConsumptionPass.cpp | 27 ++++- .../OwnershipInferenceBorrowers.cpp | 3 +- .../TypeScript/OwnershipInferenceClosures.cpp | 4 +- .../lib/TypeScript/OwnershipInferencePass.h | 4 + .../OwnershipInferencePlaceReads.cpp | 8 ++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 59 +++++++++- .../lib/TypeScript/OwnershipSignaturePass.h | 19 ++- tslang/lib/TypeScript/TypeScriptOps.cpp | 29 +++-- tslang/test/tester/CMakeLists.txt | 32 +++++ .../test/tester/own-facts-246-virtual.cmake | 91 ++++++++++++++ tslang/test/tester/own-facts-246.cmake | 76 ++++++++++++ .../own_err_merged_borrowing_calls_reset.ts | 13 ++ .../test/tester/tests/00tslang_issue_245.ts | 57 +++++++++ .../tests/00tslang_issue_246_named_call.ts | 56 +++++++++ tslang/test/tester/tests/own_facts246_lib.ts | 111 ++++++++++++++++++ tslang/test/tester/tests/own_facts246_main.ts | 75 ++++++++++++ .../tester/tests/own_facts246_virtual_lib.ts | 22 ++++ .../tester/tests/own_facts246_virtual_main.ts | 26 ++++ tslang/test/tester/verify-ownership.cmake | 2 + 24 files changed, 816 insertions(+), 26 deletions(-) create mode 100644 tslang/test/tester/own-facts-246-virtual.cmake create mode 100644 tslang/test/tester/own-facts-246.cmake create mode 100644 tslang/test/tester/own/own_err_merged_borrowing_calls_reset.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_245.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_246_named_call.ts create mode 100644 tslang/test/tester/tests/own_facts246_lib.ts create mode 100644 tslang/test/tester/tests/own_facts246_main.ts create mode 100644 tslang/test/tester/tests/own_facts246_virtual_lib.ts create mode 100644 tslang/test/tester/tests/own_facts246_virtual_main.ts diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index d56b5342c..b5563ee3b 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -1019,7 +1019,11 @@ decorators above, and nothing of the bodies. Everything else about another modul unknown, so a call of one may free anything. A module compiled under `-mm=own` also records, in its object file, what each exported function -frees: nothing, or only certain fields, and whether its result is fresh. Give the objects of the +frees: nothing, or only certain fields, and whether its result is fresh. A function that may free +anything (it runs a callback) still says whether its result is fresh. A result that borrows one +argument also says which places of that argument it reads, so a call that overwrites another place +of the same type leaves that borrow alone. Functions the module does not export, but whose +declarations an importer sees, say whether their result is fresh. Give the objects of the modules a program imports to `--own-facts`, and calls into them keep the caller's borrows they do not touch: diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index c8353c652..7ef6e8aec 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -123,6 +123,10 @@ // still takes it over, on every path it appears on: nothing after either reads the name. See // MLIROwnedReference.h. #define OWNED_RESULT_NAMED_ATTR_NAME "__owned_result_named" +// ...kept, under its own name, on the direct call the canonicalizer and the lowering make of a call that had it +// (`const B = mk()`): only -mm=own's rule that a closure which does not escape borrows a named `const` reads it +// (TSLANG 246, the loop form of 238). The other rules keep seeing such a call as they did. +#define OWNED_RESULT_NAMED_CALL_ATTR_NAME "__owned_result_named_call" // On a read through an interface's field that is owned under rc (MLIRGenImpl::InterfaceFieldAccess): a number // of its own. A `ts.Load` only reads memory, so CSE would fold two reads of the same field into one - one @@ -491,6 +495,25 @@ // a line's last field is OWN_OBJECT_FACTS_FRESH_RESULT #define SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME "ts.own_imported_fresh_results" #define OWN_OBJECT_FACTS_FRESH_RESULT "fresh" +// ...and a line `\tany\tfresh` is a function that may destroy anything (it calls a callback, say) but +// whose result is still its caller's to own (TSLANG 246: `surface(fn, ...)` of another module, whose result +// was taken to hold the closure it was given). A reader that does not know the field finds no place in it, +// so gives the function no facts, which is what it had before. +#define OWN_OBJECT_FACTS_DROPS_ANY "any" +// ...and a field `@ ` per place the result of a function whose result is a plain borrow of one +// argument (`@lends("this") near(z)`) is read through from it (TSLANG 236, own's OWN_RESULT_PLACES_ATTR_NAME): an +// importer's call then knows that a later overwrite of another place of that type leaves the borrow alone. A reader +// that does not know the field finds no place in it, so gives the function no facts. +#define OWN_OBJECT_FACTS_RESULT_PLACE "@" +// ...and ` local fresh` a function the module does not export, whose result its caller owns: an importer +// re-parses its declaration, and a call through a value there may reach it (OwnedReturnConsumptionPass). Said of no +// call by name, and never over another module's exported line of the same name. +#define OWN_OBJECT_FACTS_LOCAL "local" +// a module attribute: [name...] of those +#define SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME "ts.own_imported_local_fresh_results" +// a module attribute: { name -> [[position, slot type]...] } of the functions --own-facts says read their result +// through those places +#define SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME "ts.own_imported_result_places" // `@nodrops declare function strncmp(...)`: a function defined outside TypeScript, a C function, // that destroys nothing a TypeScript caller can reach. -mm=own calls it the way it calls an // imported function in SHARED_LIB_OWN_NO_DROPS_ATTR_NAME, so a borrow of a field can be given to diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index b699e7285..13127bb95 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -2900,6 +2900,16 @@ struct CallOpLowering : public TsPattern LogicalResult matchAndRewrite(mlir_ts::CallOp op, PatternRewriter &rewriter) const final { + // a `const` holding the result as its value (`const B = mk()`) stays one for -mm=own, which runs on what + // this makes (TSLANG 246); read before the call is replaced, which erases it + auto named = op->getAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME); + auto keepNamed = [&](mlir::Operation *call) { + if (named) + { + call->setAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME, named); + } + }; + if (auto unwind = tsContext->unwind.lookup(op)) { { @@ -2912,9 +2922,9 @@ struct CallOpLowering : public TsPattern : op.getOperands()) llvm::dbgs() << "!! ...call -> invoke operands: " << opit << "\n";); - rewriter.replaceOpWithNewOp(op, op.getResultTypes(), op.getCalleeAttr(), + keepNamed(rewriter.replaceOpWithNewOp(op, op.getResultTypes(), op.getCalleeAttr(), op.getArgOperands(), continuationBlock, ValueRange{}, - unwind, ValueRange{}); + unwind, ValueRange{})); return success(); } @@ -2923,8 +2933,8 @@ struct CallOpLowering : public TsPattern } // just replace - rewriter.replaceOpWithNewOp(op, op.getResultTypes(), op.getCalleeAttr(), - op.getArgOperands()); + keepNamed(rewriter.replaceOpWithNewOp(op, op.getResultTypes(), op.getCalleeAttr(), + op.getArgOperands())); return success(); } }; diff --git a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp index 4a4a7c101..6ca8214ad 100644 --- a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp +++ b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp @@ -625,6 +625,9 @@ namespace mlirgen if (auto stubOp = lookupModuleSymbol(stubName)) { stubOp->setAttr(NULL_INTERFACE_VTABLE_ATTR_NAME, builder.getUnitAttr()); + // each module makes its own (`BindingSet..missing` of an imported @value class, `.function_value.missing`), + // so it is the module's alone: two modules defining it failed to link with LNK2005 (TSLANG 243) + stubOp->setAttr("internal_linkage", builder.getUnitAttr()); } return result; diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index 0a5a78db8..401b13aa0 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -1708,13 +1708,34 @@ namespace mlirgen std::string noDrops; llvm::SmallVector dropFields; llvm::SmallVector freshResults; + llvm::SmallVector resultPlaces; llvm::StringSet<> seen; + llvm::StringSet<> localFresh; + // ` `, or null when it does not parse here + auto placeOf = [&](StringRef part) -> mlir::Attribute { + auto [positionText, typeText] = part.split(' '); + int64_t position; + auto type = typeText.empty() ? mlir::Type() : mlir::parseType(typeText, builder.getContext()); + if (positionText.getAsInteger(10, position) || !type) + { + return {}; + } + + return builder.getArrayAttr({builder.getI64IntegerAttr(position), mlir::TypeAttr::get(type)}); + }; llvm::SmallVector lines; factsText.split(lines, '\n', -1, false); for (auto line : lines) { llvm::SmallVector parts; line.trim().split(parts, '\t', -1, false); + // a function a module does not export (OWN_OBJECT_FACTS_LOCAL): kept apart, below every exported line + if (parts.size() == 3 && parts[1] == OWN_OBJECT_FACTS_LOCAL && parts[2] == OWN_OBJECT_FACTS_FRESH_RESULT) + { + localFresh.insert(parts.front()); + continue; + } + if (parts.empty() || !seen.insert(parts.front()).second) { continue; @@ -1726,25 +1747,45 @@ namespace mlirgen parts.pop_back(); } + // the places its result is read through (OWN_OBJECT_FACTS_RESULT_PLACE), all or none + llvm::SmallVector readThrough; + auto placesParse = true; + while (parts.size() > 1 && parts.back().starts_with(OWN_OBJECT_FACTS_RESULT_PLACE)) + { + auto place = placeOf(parts.back().drop_front(StringRef(OWN_OBJECT_FACTS_RESULT_PLACE).size())); + placesParse = placesParse && place; + readThrough.insert(readThrough.begin(), place); + parts.pop_back(); + } + + if (placesParse && !readThrough.empty()) + { + resultPlaces.push_back(builder.getNamedAttr(parts.front(), builder.getArrayAttr(readThrough))); + } + if (parts.size() == 1) { noDrops += parts.front().str() + "\n"; continue; } + // it may destroy anything: only its fresh result, if any, is known + if (parts.size() == 2 && parts.back() == OWN_OBJECT_FACTS_DROPS_ANY) + { + continue; + } + llvm::SmallVector places; for (auto part : llvm::drop_begin(parts)) { - auto [positionText, typeText] = part.split(' '); - int64_t position; - auto type = typeText.empty() ? mlir::Type() : mlir::parseType(typeText, builder.getContext()); - if (positionText.getAsInteger(10, position) || !type) + auto place = placeOf(part); + if (!place) { places.clear(); break; } - places.push_back(builder.getArrayAttr({builder.getI64IntegerAttr(position), mlir::TypeAttr::get(type)})); + places.push_back(place); } if (!places.empty()) @@ -1763,6 +1804,33 @@ namespace mlirgen { theModule->setAttr(SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME, builder.getArrayAttr(freshResults)); } + + if (!resultPlaces.empty()) + { + theModule->setAttr(SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME, builder.getDictionaryAttr(resultPlaces)); + } + + // (a name another module exports is that function's, whatever a module that does not export it says) + llvm::SmallVector localNames; + for (auto &entry : localFresh) + { + if (!seen.contains(entry.getKey())) + { + localNames.push_back(entry.getKey()); + } + } + + llvm::sort(localNames); + if (!localNames.empty()) + { + llvm::SmallVector names; + for (auto name : localNames) + { + names.push_back(builder.getStringAttr(name)); + } + + theModule->setAttr(SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME, builder.getArrayAttr(names)); + } } // The module's exported declarations, as a global the passes can read (the ownership signature diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index def7f222a..d1d08075d 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -100,6 +100,24 @@ class OwnedReturnConsumptionPass // default library's Map iterators' `next` (lending a key of the `{ value, done }` they return), there in every // module with a dictionary, made every call through a function value returning a string keep its result llvm::DenseSet unclassifiedNotLendingResults; + // -mm=own: the declarations another own module's object says return a value their caller owns (--own-facts, + // SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME): what a call through a value reaches of them is the caller's too + // (TSLANG 246: golden_line_extrude's functions, imported by golden_line_traingeo, turned this off there) + llvm::StringSet<> importedFresh; + if (compileOptions.memoryModel == MemoryModelOwn) + { + for (auto *attrName : {SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME, SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME}) + { + if (auto names = module->getAttrOfType(attrName)) + { + for (auto name : names.getAsRange()) + { + importedFresh.insert(name.getValue()); + } + } + } + } + module.walk([&](mlir_ts::FuncOp funcOp) { // a method of an interface's null vtable throws, and returns nothing to anyone // (mlirGenNullInterfaceVTable) @@ -116,7 +134,7 @@ class OwnedReturnConsumptionPass returnsOwned.insert(name); } - if (!classified) + if (!classified && !(funcOp.getBody().empty() && importedFresh.contains(name))) { for (auto resultType : funcOp.getFunctionType().getResults()) { @@ -5145,9 +5163,14 @@ class OwnedReturnConsumptionPass auto dot = name.rfind('.'); if (dot != mlir::StringRef::npos) { + // only a method of a class on the receiver's chain can be in its slot (`Part.at` is not + // `JsonValue.at`), as everyOverrideReturnsOwned reads it + auto receiverType = thisVirtualSymbolRefOp.getThisVal().getType(); auto it = methodsByMemberName.find(name.substr(dot + 1)); if (it != methodsByMemberName.end() && - llvm::any_of(it->second, [&](const auto &method) { return names.contains(method.first); })) + llvm::any_of(it->second, [&](const auto &method) { + return names.contains(method.first) && onReceiverChain(method.second, receiverType); + })) { return true; } diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 43ed8a425..44db6d652 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -1198,7 +1198,8 @@ namespace own_inference { auto *user = use.getOwner(); if (pending.borrowed && keeping.bookkeeping && - ((mlir::isa(user) && borrowingCall(rootOf(pending.value))) || + ((mlir::isa(user) && + (borrowingCall(rootOf(pending.value)) || mergeOfBorrowingCalls(pending.value))) || (keeping.returns && mlir::isa(user)))) { keeping.bookkeeping->push_back(user); diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 24a7a4668..cfe028539 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -112,7 +112,9 @@ namespace own_inference auto ownedByNamedConst = [&](mlir::Value value) { auto root = rootOf(value); auto *def = root.getDefiningOp(); - return def && isFresh(root) && def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME); + // (a call made direct keeps it as OWNED_RESULT_NAMED_CALL_ATTR_NAME: `const B = mk()`, TSLANG 246) + return def && isFresh(root) && + (def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME) || def->hasAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME)); }; auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) { auto value = fill.second.getValue(); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 22d658917..478f168d3 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -1090,6 +1090,10 @@ class OwnershipInferencePass // record (spec 32) is not one: the caller owns the box (checkRecordResults). static mlir::Operation *borrowingCall(mlir::Value value); + // A merge every way into which brings such a call's result: `c ? t.a() : t.b()` of two methods that each + // return a borrow (TSLANG 245). rc's release of the merge is its bookkeeping, as one of the call's is. + static bool mergeOfBorrowingCalls(mlir::Value value); + // The places from a read up to its roots, and the roots: the values the function reached the // first container through. A container reached through a merge (`(c ? a : b).x`) has a root // on each way in. diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index ab0e81b6b..68f605d27 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -513,6 +513,14 @@ namespace own_inference return llvm::all_of(indices, [&](int index) { return static_cast(index) < args.size(); }) ? def : nullptr; } + bool OwnershipInferencePass::mergeOfBorrowingCalls(mlir::Value value) + { + auto argument = mlir::dyn_cast(rootOf(value)); + llvm::SmallVector merged; + return argument && mergedInto(argument, merged) && !merged.empty() && + llvm::all_of(merged, [](mlir::Value incoming) { return borrowingCall(incoming) != nullptr; }); + } + // A plain borrow of one argument that says the places it is read through (OWN_RESULT_PLACES_ATTR_NAME): those go on // the chain, as if read here. False for any other call's result. bool OwnershipInferencePass::knownResultPlaces(mlir::Operation *call, Chain &chain) diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 3e2a1b220..9fc47d1a9 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -331,6 +331,18 @@ namespace own_signature } } + if (auto functionsReading = module->getAttrOfType(SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME)) + { + for (auto entry : functionsReading) + { + auto &places = importedResultPlaces[entry.getName().getValue()]; + for (auto place : mlir::cast(entry.getValue()).getAsRange()) + { + places.push_back({mlir::cast(place[0]).getInt(), mlir::cast(place[1]).getValue()}); + } + } + } + findImmortalGlobals(module); moveIntoGlobals(module); rejectBorrowedGlobalInitializers(module); @@ -1698,6 +1710,15 @@ namespace own_signature facts.record = calleesDeclare(call.callees, OWN_DECLARED_RECORD_ATTR_NAME); facts.itself = lends.size() == 1 && !facts.record && calleesDeclare(call.callees, OWN_DECLARED_RETURNS_THIS_ATTR_NAME); + // ...and the places another own module's object says its result is read through (TSLANG 236) + if (lends.size() == 1 && !facts.record && call.callees.named.size() == 1) + { + if (auto found = importedResultPlaces.find(call.callees.named.front().getValue()); + found != importedResultPlaces.end()) + { + facts.places = found->second; + } + } } } @@ -2636,22 +2657,46 @@ namespace own_signature for (auto &entry : functions) { auto funcOp = entry.second; - if (funcOp.isDeclaration() || funcOp.isPrivate()) + if (funcOp.isDeclaration()) + { + continue; + } + + // a function the module does not export, whose result its caller owns: an importer re-parses its + // declaration (`EarPool..new`, a module function), and a call through a value there may reach it - only + // that is said of it (OwnedReturnConsumptionPass, TSLANG 246) + if (funcOp.isPrivate()) { + if (returnsFresh(funcOp) && !funcOp.getSymName().starts_with(".")) + { + lines.push_back({funcOp.getSymName(), std::string("\t") + OWN_OBJECT_FACTS_LOCAL + "\t" + + OWN_OBJECT_FACTS_FRESH_RESULT}); + } + continue; } auto found = fieldDrops.find(funcOp); auto overwrites = !noDrops.contains(funcOp) && found != fieldDrops.end() && !found->second.any && !found->second.places.empty(); - if (!noDrops.contains(funcOp) && !overwrites) + auto dropsAny = !noDrops.contains(funcOp) && !overwrites; + // the places its result, a plain borrow of one argument, is read through (OWN_OBJECT_FACTS_RESULT_PLACE) + auto effective = factsEffective.lookup(funcOp); + auto places = effective.borrows.size() == 1 && !effective.record && effective.places && !effective.places->empty() + ? &*effective.places + : nullptr; + if (dropsAny && !returnsFresh(funcOp) && !places) { continue; } std::string line; llvm::raw_string_ostream os(line); - if (overwrites) + if (dropsAny) + { + os << '\t' << OWN_OBJECT_FACTS_DROPS_ANY; + } + else if (overwrites) { for (auto [position, type] : found->second.places) { @@ -2659,6 +2704,14 @@ namespace own_signature } } + if (places) + { + for (auto [position, type] : *places) + { + os << '\t' << OWN_OBJECT_FACTS_RESULT_PLACE << position << ' ' << type; + } + } + if (returnsFresh(funcOp)) { os << '\t' << OWN_OBJECT_FACTS_FRESH_RESULT; diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 6c3a96726..c1fab2034 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -677,6 +677,9 @@ class OwnershipSignaturePass : public mlir::PassWrapper importedFreshResults; + // ...and the places those whose result borrows one argument read it through (SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME) + llvm::StringMap>> importedResultPlaces; + // `new C()` of a class from a library built under own, or a call of a function another own // module's object says returns a value its caller owns (--own-facts): the caller owns the result bool isImportedFreshResult(const Call &call) @@ -684,7 +687,21 @@ class OwnershipSignaturePass : public mlir::PassWrappergetNumResults() == 1 && ((!call.callees.importedOverwrites && call.callees.importedName.ends_with("." NEW_METHOD_NAME)) || importedFreshResults.contains(call.callees.importedName))) || - isDeclaredOwnedResult(call); + isImportedFreshDroppingResult(call) || isDeclaredOwnedResult(call); + } + + // ...or a direct call of one the object says may destroy anything, but returns a value its caller + // owns (OWN_OBJECT_FACTS_DROPS_ANY): the callee is not known, as it may destroy anything + bool isImportedFreshDroppingResult(const Call &call) + { + auto callee = directCallee(call.op); + if (call.callees.known || !callee || call.op->getNumResults() != 1 || !importedFreshResults.contains(callee.getValue())) + { + return false; + } + + auto funcOp = functions.lookup(callee.getValue()); + return funcOp && funcOp.isDeclaration(); } // ...or a call of declarations that each say `@owned` (DECLARED_OWNED_RESULT_ATTR_NAME) - the default diff --git a/tslang/lib/TypeScript/TypeScriptOps.cpp b/tslang/lib/TypeScript/TypeScriptOps.cpp index 566bd3f57..a769eb0d2 100644 --- a/tslang/lib/TypeScript/TypeScriptOps.cpp +++ b/tslang/lib/TypeScript/TypeScriptOps.cpp @@ -1314,14 +1314,27 @@ struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern::OpRewritePattern; + // a `const` holding the call's result as its value (`const B = mk()`) stays one once the call is direct: + // -mm=own lets a closure that does not escape borrow such a const (TSLANG 246, the loop form of 238) + static void keepNamedResult(mlir::Attribute named, mlir_ts::CallOp callOp) + { + if (named) + { + callOp->setAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME, named); + } + } + LogicalResult matchAndRewrite(mlir_ts::CallIndirectOp indirectCall, PatternRewriter &rewriter) const override { + // (read before the call is replaced: the replacement erases it) + auto named = indirectCall->getAttr(OWNED_RESULT_NAMED_ATTR_NAME); + // Check that the callee is a constant callee. if (auto symbolRefOp = indirectCall.getCallee().getDefiningOp()) { // Replace with a direct call. - rewriter.replaceOpWithNewOp(indirectCall, symbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), - indirectCall.getArgOperands()); + keepNamedResult(named, rewriter.replaceOpWithNewOp(indirectCall, symbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), + indirectCall.getArgOperands())); return success(); } @@ -1332,8 +1345,8 @@ struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern(indirectCall, thisSymbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), - args); + keepNamedResult(named, rewriter.replaceOpWithNewOp(indirectCall, thisSymbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), + args)); return success(); } @@ -1390,8 +1403,8 @@ struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern(indirectCall, symbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), - args); + keepNamedResult(named, rewriter.replaceOpWithNewOp(indirectCall, symbolRefOp.getIdentifierAttr(), indirectCall.getResultTypes(), + args)); // LLVM_DEBUG(for (auto &arg : args) { llvm::dbgs() << "\n\n SimplifyIndirectCallWithKnownCallee arg: " << arg << "\n"; }); @@ -1431,8 +1444,8 @@ struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern args; args.push_back(thisVal); args.append(indirectCall.getArgOperands().begin() + 1, indirectCall.getArgOperands().end()); - rewriter.replaceOpWithNewOp(indirectCall, thisSymbolRef.getIdentifierAttr(), indirectCall.getResultTypes(), - args); + keepNamedResult(named, rewriter.replaceOpWithNewOp(indirectCall, thisSymbolRef.getIdentifierAttr(), indirectCall.getResultTypes(), + args)); // LLVM_DEBUG(for (auto &arg : args) { llvm::dbgs() << "\n\n SimplifyIndirectCallWithKnownCallee arg: " << arg << "\n"; }); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2e066e3e1..c55b8e0dc 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2816,6 +2816,14 @@ foreach(issue236_n 236 237 238 239 240 240_temps 240_fuzz) tslang_add_test(NAME test-compile-00tslang_issue_${issue236_n}-${issue236_mm} COMMAND test-runner -mm=${issue236_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue236_n}.ts") endforeach() endforeach() +# TSLANG 245: a ternary of two borrowing calls' results borrows each; TSLANG 246: a closure in a loop borrows a const +# holding a call's result (238's loop form); every model runs them +foreach(issue245_n 245 246_named_call) + foreach(issue245_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_${issue245_n}-${issue245_mm} COMMAND test-runner -jit -mm=${issue245_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue245_n}.ts") + tslang_add_test(NAME test-compile-00tslang_issue_${issue245_n}-${issue245_mm} COMMAND test-runner -mm=${issue245_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue245_n}.ts") + endforeach() +endforeach() add_test(NAME test-compile-declared-method-overloads-warning COMMAND $ --emit=obj --no-default-lib -mm=none "${PROJECT_SOURCE_DIR}/test/tester/tests/declared_method_overloads_warning.ts" @@ -3336,6 +3344,29 @@ if (WIN32) "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-facts-objects.cmake") + # ...and what TSLANG 246 added to those facts: fresh results of functions that may destroy anything, the places a + # lent result is read through, a module's own functions; and each module's own `V..missing` (TSLANG 243) + add_test(NAME test-own-facts-246 + COMMAND ${CMAKE_COMMAND} + "-DTSLANG=$" + "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-facts-246" + "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + "-DGC_LIB=${TEST_GC_LIBDIR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-facts-246.cmake") + # ...and a method returning owned, called through the vtable, with the real default library (TSLANG 246) + add_test(NAME test-own-facts-246-virtual + COMMAND ${CMAKE_COMMAND} + "-DTSLANG=$" + "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-facts-246-virtual" + "-DGC_LIB=${TEST_GC_LIBDIR}" + "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + "-DDEFAULT_LIB_CANDIDATES=${PROJECT_SOURCE_DIR}/../TypeScriptCompilerDefaultLib/__build;${PROJECT_SOURCE_DIR}/../../TypeScriptCompilerDefaultLib/__build" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-facts-246-virtual.cmake") + set_tests_properties(test-own-facts-246-virtual PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") # ...and a library's keeper: the importer makes what it gives `@immortalizes` immortal add_test(NAME test-own-keepers-objects COMMAND ${CMAKE_COMMAND} @@ -7893,6 +7924,7 @@ set(own_error_cases "own_err_result_places_holder_replaced|:6:67: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" "own_err_object_array_emptied|:5:76: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" "own_err_object_array_emptied_callee|:5:68: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" + "own_err_merged_borrowing_calls_reset|:11:29: error: a value that borrows the result of 'Terrain.tunnelSpan' is used here after it may be released or overwritten" "own_err_closure_param_returned_borrow|:5:31: error: a closure that escapes owns what it captures, but -mm=own cannot move 'p' into it: its value is the caller's" "own_err_param_moved_twice_one_call|:5:12: error: 'p' is used here after its value was moved" "own_err_object_literal_counted_read|:9:11: error: a value that borrows 'G[.]items[[][]]' is used here after it may be released or overwritten" diff --git a/tslang/test/tester/own-facts-246-virtual.cmake b/tslang/test/tester/own-facts-246-virtual.cmake new file mode 100644 index 000000000..4339f0cb3 --- /dev/null +++ b/tslang/test/tester/own-facts-246-virtual.cmake @@ -0,0 +1,91 @@ +# -mm=own across two modules with the real default library (TSLANG 246): own_facts246_virtual_main.ts calls +# Shape.at, a method of own_facts246_virtual_lib.ts that returns a value its caller owns, through the vtable. With +# every function the program can reach classified (the library's object says what each returns), a call through +# a value hands back a reference; the default library's JsonValue.at, which lends its result, has the same member +# name but is not a method of Shape. Taken as one of the call's candidates, the call's result was a borrow nobody +# gave back: the program leaked a Shape on every turn of its loop. +# +# The executable allocates from mimalloc, which prints its statistics at exit under MIMALLOC_SHOW_STATS: what is +# still committed then is a few KiB, not tens of MiB. Skipped when no own default library has been built. + +cmake_minimum_required(VERSION 3.17.3) + +foreach(var TSLANG SOURCE_DIR WORK_DIR GC_LIB LLVM_LIB TSLANG_LIB DEFAULT_LIB_CANDIDATES) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "${var} is required") + endif() +endforeach() + +set(opt --opt --opt_level=3) +execute_process(COMMAND "${TSLANG}" --print-default-lib-dir=lib ${opt} -mm=own + OUTPUT_VARIABLE default_lib_subdir + OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR default_lib_subdir STREQUAL "") + message(FATAL_ERROR "tslang --print-default-lib-dir=lib -mm=own: exit ${status}") +endif() + +set(default_lib "") +foreach(candidate "$ENV{DEFAULT_LIB_PATH}" ${DEFAULT_LIB_CANDIDATES}) + if(NOT candidate STREQUAL "" AND IS_DIRECTORY "${candidate}/${default_lib_subdir}") + set(default_lib "${candidate}") + break() + endif() +endforeach() + +if(default_lib STREQUAL "") + if("$ENV{TSLANG_REQUIRE_DEFAULT_LIB}" STREQUAL "1") + message(FATAL_ERROR "no own default library built in ${default_lib_subdir} under DEFAULT_LIB_PATH='$ENV{DEFAULT_LIB_PATH}'") + endif() + message("SKIPPED: no own default library built in ${default_lib_subdir} (set DEFAULT_LIB_PATH to the folder holding 'defaultlib')") + return() +endif() + +set(ENV{DEFAULT_LIB_PATH} "") +set(ENV{GC_LIB_PATH} "") +set(ENV{TSLANG_LIB_PATH} "") + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +foreach(file own_facts246_virtual_lib.ts own_facts246_virtual_main.ts) + file(COPY "${SOURCE_DIR}/${file}" DESTINATION "${WORK_DIR}") +endforeach() + +set(common ${opt} -mm=own --own-fallback=error "--default-lib-path=${default_lib}" "--llvm-lib-path=${LLVM_LIB}" + "--tslang-lib-path=${TSLANG_LIB}" "--gc-lib-path=${GC_LIB}") + +function(tslang_run what) + execute_process(COMMAND "${TSLANG}" ${ARGN} + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) + if(NOT status EQUAL 0 OR "${out}${err}" MATCHES "error:|Stack dump") + message(FATAL_ERROR "${what}: exit ${status}\n${out}${err}") + endif() +endfunction() + +tslang_run(lib --emit=obj ${common} own_facts246_virtual_lib.ts -o own_facts246_virtual_lib.obj) +tslang_run(main --emit=exe ${common} --own-facts=own_facts246_virtual_lib.obj --obj=own_facts246_virtual_lib.obj + own_facts246_virtual_main.ts -o own_facts246_virtual.exe) + +execute_process(COMMAND ${CMAKE_COMMAND} -E env "PATH=${default_lib}/${default_lib_subdir};$ENV{PATH}" MIMALLOC_SHOW_STATS=1 + "${WORK_DIR}/own_facts246_virtual.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "5 -3 2[\r\n]+done[.]") + message(FATAL_ERROR "own_facts246_virtual.exe: exit ${status}\n${out}${err}") +endif() + +# ` committed: `: current, at exit +string(REGEX MATCH "committed:[ \t]+[0-9.]+ [KMG]?i?B[ \t]+[0-9.]+ [KMG]?i?B[ \t]+([0-9.]+ [KMG]?i?B)" committed "${out}${err}") +if(committed STREQUAL "") + message(FATAL_ERROR "own_facts246_virtual.exe printed no mimalloc statistics\n${out}${err}") +endif() +set(current "${CMAKE_MATCH_1}") +if(current MATCHES "MiB|GiB") + message(FATAL_ERROR "own_facts246_virtual.exe still has ${current} committed at exit: a Shape leaked on each turn\n${out}${err}") +endif() +message(STATUS "committed at exit: ${current}") diff --git a/tslang/test/tester/own-facts-246.cmake b/tslang/test/tester/own-facts-246.cmake new file mode 100644 index 000000000..6e14ab05f --- /dev/null +++ b/tslang/test/tester/own-facts-246.cmake @@ -0,0 +1,76 @@ +# -mm=own across two modules compiled into objects of their own (TSLANG 246): own_facts246_main.ts, given +# own_facts246_lib.ts's object with --own-facts, relies on what the object now says - +# - a function that calls callbacks, so may destroy anything, still returns a value its caller owns (`surf`), +# - a result that borrows one argument is read through these places (`Ter.near`), so an overwrite of another place +# of that type (`Map.set`, an `int[]` field reassigned) leaves the borrow alone, +# - a function the library does not export returns a value its caller owns (`cross`, whose declaration the importer +# re-parses): a call through a value there still hands back a reference of its own (`const q = fn(i, 2.0)`). +# Each module makes its own `V..missing` for a @value class tested for null (TSLANG 243): the two objects link. + +cmake_minimum_required(VERSION 3.17.3) + +foreach(var TSLANG SOURCE_DIR WORK_DIR LLVM_LIB TSLANG_LIB GC_LIB) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "${var} is required") + endif() +endforeach() + +set(ENV{GC_LIB_PATH} "") +set(ENV{TSLANG_LIB_PATH} "") + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +foreach(file own_facts246_lib.ts own_facts246_main.ts) + file(COPY "${SOURCE_DIR}/${file}" DESTINATION "${WORK_DIR}") +endforeach() + +function(tslang_run what) + execute_process(COMMAND "${TSLANG}" ${ARGN} + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) + set(status "${status}" PARENT_SCOPE) + set(output "${out}${err}" PARENT_SCOPE) +endfunction() + +tslang_run(lib --emit=obj -mm=own own_facts246_lib.ts -o own_facts246_lib.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts246_lib: exit ${status}\n${output}") +endif() + +tslang_run(link --emit=exe -mm=own "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" + --own-facts=own_facts246_lib.obj --obj=own_facts246_lib.obj own_facts246_main.ts -o own_facts246.exe) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts246_main with --own-facts: exit ${status}\n${output}") +endif() + +execute_process(COMMAND "${WORK_DIR}/own_facts246.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "^2 3 2 6 7 1 -1 7 7[\r\n]+done[.]") + message(FATAL_ERROR "own_facts246.exe: exit ${status}\n${out}${err}") +endif() + +# The same two modules under gc: the `V..missing` stub each object makes must not clash at link time (TSLANG 243). +tslang_run(gclib --emit=obj own_facts246_lib.ts -o own_facts246_gclib.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts246_lib (gc): exit ${status}\n${output}") +endif() + +tslang_run(gclink --emit=exe "--gc-lib-path=${GC_LIB}" "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" + --obj=own_facts246_gclib.obj own_facts246_main.ts -o own_facts246_gc.exe) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts246_main (gc): exit ${status}\n${output}") +endif() + +execute_process(COMMAND "${WORK_DIR}/own_facts246_gc.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "^2 3 2 6 7 1 -1 7 7[\r\n]+done[.]") + message(FATAL_ERROR "own_facts246_gc.exe: exit ${status}\n${out}${err}") +endif() diff --git a/tslang/test/tester/own/own_err_merged_borrowing_calls_reset.ts b/tslang/test/tester/own/own_err_merged_borrowing_calls_reset.ts new file mode 100644 index 000000000..3ef60a3ef --- /dev/null +++ b/tslang/test/tester/own/own_err_merged_borrowing_calls_reset.ts @@ -0,0 +1,13 @@ +// -mm=own, TSLANG 245: a merge of two borrowing calls' results is a borrow of each; a call that overwrites what they +// read still ends it. +class Span { a = 1.0; } +@final class Terrain { + private t: Span = new Span(); private r: Span = new Span(); + tunnelSpan(i: int): Span { return this.t; } bridgeSpan(i: int): Span { return this.r; } + reset(): void { this.t = new Span(); this.r = new Span(); } +} +function afterReset(terrain: Terrain, tunnel: boolean): number { + const f = tunnel ? terrain.tunnelSpan(0) : terrain.bridgeSpan(0); + terrain.reset(); return f.a; +} +function main() { print(afterReset(new Terrain(), false)); } diff --git a/tslang/test/tester/tests/00tslang_issue_245.ts b/tslang/test/tester/tests/00tslang_issue_245.ts new file mode 100644 index 000000000..b19bbadb6 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_245.ts @@ -0,0 +1,57 @@ +// TSLANG 245: under -mm=own a local bound to a ternary whose two branches are borrowed method results +// (`c ? terrain.tunnelSpan(0) : terrain.bridgeSpan(0)`) was refused as if it were stored: "a value that borrows the +// result of 'Terrain.tunnelSpan' cannot be stored, returned or captured". Each branch alone was accepted. rc's release +// of the merge is its bookkeeping, as one of a single borrowing call is. + +class Span { + a = 1.0; + b = 2.0; +} + +@final +class Terrain { + private t: Span = new Span(); + private r: Span = new Span(); + + constructor() { + this.r.a = 10.0; + this.r.b = 20.0; + } + + tunnelSpan(i: int): Span { + return this.t; + } + + bridgeSpan(i: int): Span { + return this.r; + } +} + +function first(terrain: Terrain, tunnel: boolean): number { + const f = tunnel ? terrain.tunnelSpan(0) : terrain.bridgeSpan(0); + const churn = new Span(); + churn.a = 100.0; + return f.a + f.b; +} + +function inLoop(terrain: Terrain): number { + let s = 0.0; + for (let i = 0; i < 4; i++) { + const f = i % 2 == 0 ? terrain.tunnelSpan(i) : terrain.bridgeSpan(i); + const churn = new Span(); + churn.b = 100.0; + s += f.a; + } + + return s; +} + +function main() { + const terrain = new Terrain(); + const x = first(terrain, true); + const y = first(terrain, false); + const z = inLoop(terrain); + print(x, y, z); + assert(x == 3 && y == 30 && z == 22); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_246_named_call.ts b/tslang/test/tester/tests/00tslang_issue_246_named_call.ts new file mode 100644 index 000000000..08d96e353 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_246_named_call.ts @@ -0,0 +1,56 @@ +// TSLANG 246 (238's loop form): under -mm=own a closure given straight to a function that only calls it, inside a +// loop, was taken to move a class instance it captures when a `const` held it as a call's result (`const B = +// mk()`): "'B' is moved inside a loop but was made outside it". `new Back()` in its place was accepted. The +// canonicalizer, making the call direct, dropped what said a `const` holds the result as its value. + +type UVFn = (u: number, v: number) => number[]; + +@final class Back { + k: number = 2.0; + xs: number[] = []; + + init(): void { + this.xs.push(1.0); + } + + pt(x: number): number { + return x * this.k; + } +} + +function mk(): Back { + const b = new Back(); + b.init(); + return b; +} + +function surf(fn: UVFn, n: int): number[] { + const out: number[] = []; + for (let i = 0; i < n; i++) { + const r = fn(i / n, 0.5); + out.push(r[0]); + } + + return out; +} + +function inLoop(): number { + const B = mk(); + let t = 0.0; + for (let f = 0; f < 3; f++) { + const front = f === 0; + const a = surf((u: number, v: number): number[] => [B.pt(u), front ? v : -v], 2); + const churn = new Back(); + churn.k = 100.0; + t += a[1]; + } + + return t + B.pt(1.0) + B.xs.length; +} + +function main() { + const x = inLoop(); + print(x); + assert(x == 6); + print("done."); +} diff --git a/tslang/test/tester/tests/own_facts246_lib.ts b/tslang/test/tester/tests/own_facts246_lib.ts new file mode 100644 index 000000000..ade892028 --- /dev/null +++ b/tslang/test/tester/tests/own_facts246_lib.ts @@ -0,0 +1,111 @@ +// The library side of own-facts-246.cmake (TSLANG 246): what its object says of its functions, read by +// own_facts246_main.ts with --own-facts. +export type UVFn = (u: number, v: number) => number[]; +export type PFn = (x: number, y: number, z: number) => number[]; + +@final +export class Part { + p: number[] = []; + vert(x: number): void { + this.p.push(x); + } +} + +// calls its callbacks, so it may destroy anything; still its result is its caller's +export function surfRaw(fn: UVFn, n: int): Part { + const part = new Part(); + for (let i = 0; i < n; i++) { + const r = fn(i / n, 0.5); + part.vert(r[0]); + } + return part; +} + +export function orient(part: Part, hint: PFn): void { + const h = hint(part.p[0], 0.0, 0.0); + part.vert(h[0]); +} + +export function surf(fn: UVFn, n: int, hint: PFn): Part { + const part = surfRaw(fn, n); + orient(part, hint); + return part; +} + +// not exported: its declaration reaches the importer all the same +function cross(a: number[], b: number[]): number[] { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +} + +export function crossZ(a: number[], b: number[]): number { + return cross(a, b)[2]; +} + +// a slot table that regrows its keys (an int[] field reassigned, as a Map's buckets are), and an int[] field +// reassigned: each overwrites places holding an int[], not those near's result is read through +@final +export class Slots { + keys: int[] = []; + vals: int[] = []; + + get(k: int): int { + for (let i = 0; i < this.keys.length; i++) { + if (this.keys[i] == k) { + return this.vals[i]; + } + } + return -1; + } + + set(k: int, v: int): void { + const grown: int[] = []; + for (const key of this.keys) { + grown.push(key); + } + grown.push(k); + this.keys = grown; + this.vals.push(v); + } +} + +@final +export class Ter { + private slots = new Slots(); + private lists: int[][] = []; + bag: int[] = []; + + @lends("this") + near(n: int): int[] { + const slot = this.slots.get(n); + if (slot >= 0) { + return this.lists[slot]; + } + const list: int[] = []; + for (let i = 0; i < n; i++) { + list.push(i); + } + this.slots.set(n, this.lists.length); + this.lists.push(list); + return this.lists[this.lists.length - 1]; + } + + work(k: int): void { + const order: int[] = [k, k + 1]; + this.bag = order; + this.slots.set(1000 + k, -1); + } +} + +// a @value class, tested for null on both sides: each module makes its own `V..missing` +@value +export class V { + constructor(public readonly x: number) {} +} + +export class VHolder { + v: V | null = null; +} + +export function libX(h: VHolder): number { + return h.v ? h.v.x : -1.0; +} diff --git a/tslang/test/tester/tests/own_facts246_main.ts b/tslang/test/tester/tests/own_facts246_main.ts new file mode 100644 index 000000000..a29c4d4e0 --- /dev/null +++ b/tslang/test/tester/tests/own_facts246_main.ts @@ -0,0 +1,75 @@ +// own-facts-246.cmake (TSLANG 246): compiled with --own-facts=own_facts246_lib.obj. +import { surf, Part, Ter, crossZ, V, VHolder, libX } from "./own_facts246_lib"; + +@final +class Chair { + parts: Part[] = []; + add(p: Part): void { + this.parts.push(p); + } +} + +@final +class Back { + k: number = 2.0; + pt(x: number): number { + return x * this.k; + } +} + +// surf's result is fresh though surf may destroy anything: the chair can take it +function build(out: Chair): number { + const B = new Back(); + for (let f = 0; f < 2; f++) { + const front = f === 0; + const part = surf((u: number, v: number): number[] => [B.pt(u), v], 2, + (x: number, y: number, z: number): number[] => [front ? 1.0 : -1.0]); + out.add(part); + } + return B.pt(1.0); +} + +// near's result is read through Ter's lists; work overwrites other int[] places +function sum(t: Ter, n: int): int { + let s = 0; + for (const i of t.near(n)) { + t.work(i); + s += i; + } + return s; +} + +// the library's declarations of the same result type, one of a function it does not export (`cross`), each returning +// a value its caller owns: a call through a value still hands back a reference of its own +@final +class Style { + vals: number[] = [1.0, 2.0]; + @lends("this") + color(): number[] { + return this.vals; + } +} + +export function viaValue(fn: (a: number, b: number) => number[]): number { + let s = 0.0; + for (let i = 0; i < 2; i++) { + const q = fn(i, 2.0); + s += q[0] + q[1]; + } + return s; +} + +function main() { + const c = new Chair(); + const k = build(c); + const s = sum(new Ter(), 4); + const st = new Style(); + const w = viaValue((a: number, b: number): number[] => [a + st.color()[0], b]); + const z = crossZ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + const h = new VHolder(); + const missing = libX(h); + h.v = new V(7.0); + const here = h.v ? h.v.x : -1.0; + print(c.parts.length, c.parts[0].p.length, k, s, w, z, missing, here, libX(h)); + print("done."); +} diff --git a/tslang/test/tester/tests/own_facts246_virtual_lib.ts b/tslang/test/tester/tests/own_facts246_virtual_lib.ts new file mode 100644 index 000000000..5b71011f8 --- /dev/null +++ b/tslang/test/tester/tests/own_facts246_virtual_lib.ts @@ -0,0 +1,22 @@ +// A library for own_facts246_virtual_main.ts (TSLANG 246): a class whose method returns a value its caller owns, +// called from another module through the vtable. +export class Shape { + p: number[] = []; + mirror(): Shape { const r = new Shape(); for (const v of this.p) r.p.push(-v); return r; } + // (a member name the default library's JsonValue has too, which lends its result) + at(x: number): Shape { const r = new Shape(); for (const v of this.p) r.p.push(v + x); return r; } +} + +export function shapeOf(n: int): Shape { const r = new Shape(); r.p.push(n); return r; } + +export class Paint { + c: number[] = []; + fn: Shared<(x: number) => number[]> | null = null; + @keeps("f") + withFn(ch: int, f: (x: number) => number[]): Paint { const s = new Paint(); s.c.push(f(ch)[0]); s.fn = new Shared(f); return s; } +} + +export class Sink { + out: number[] = []; + add(shape: Shape, paint: Paint): void { if (this.out.length < 4) for (const v of shape.p) this.out.push(v + paint.c.length); } +} diff --git a/tslang/test/tester/tests/own_facts246_virtual_main.ts b/tslang/test/tester/tests/own_facts246_virtual_main.ts new file mode 100644 index 000000000..5875aa7e7 --- /dev/null +++ b/tslang/test/tester/tests/own_facts246_virtual_main.ts @@ -0,0 +1,26 @@ +// -mm=own, a module given own_facts246_virtual_lib.ts's object with --own-facts (TSLANG 246): `shapeOf(3).at(1.0)` +// calls Shape.at through the vtable, and Shape.at returns a value its caller owns. The default library's +// JsonValue.at, which lends its result, shares only the member name: it is not a method of Shape, and the call's +// result is still given back. Taken for JsonValue's, every turn of the loop leaked a Shape. +import { Shape, shapeOf, Paint, Sink } from "./own_facts246_virtual_lib"; + +class Layer { + put(sink: Sink, s: number, shape: Shape, paint: Paint): void { + if (s > 0.0) sink.add(shape, paint); + else sink.add(shape.mirror(), paint); + } + run(sink: Sink, paint: Paint): void { + for (let i = 0; i < 300000; i++) { + const s = i % 2 === 0 ? 1.0 : -1.0; + this.put(sink, s, shapeOf(3).at(1.0), paint.withFn(2, (x: number): number[] => [x + 1.0])); + } + } +} + +function main() { + const sink = new Sink(); + new Layer().run(sink, new Paint()); + const j = JsonValue.parse("[1, 2]"); + print(sink.out[0], sink.out[1], j.length); + print("done."); +} diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index 54b667afa..2e7ac7835 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -104,6 +104,8 @@ set(not_compilable_alone own_rest_kept_through_class_value_error.ts # imports export_ctor_overloads.ts (test-compile-export-import-ctor-overloads-*) import_ctor_overloads.ts + # uses the default library, which this test does not give (test-own-facts-246-virtual) + own_facts246_virtual_main.ts # declares a class export_declared_method_overloads.ts implements (test-compile-import-declared-method-overloads-*) import_declared_method_overloads.ts # errors by design (test-compile-argument-union-member-to-class-error, -assign-union-member-to-class-error,