diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index fa338d5e8..d3ec52793 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -2142,7 +2142,8 @@ reads `T | undefined`, under -mm=own the dictionary owns its values). Fixed: nothing extended, no decorator) is the same dictionary - `type Dictionary = { [x: string]: T }` (isStringIndexSignatureOnly). It was a record of `get`/`set` functions nothing could fill. A class may still `implements` it (nothing to implement); without the default library's dictionary it stays the interface it - was. Open: another interface `extends` it ("indexer is not declared" at an index of that one). + was. One extending it and adding nothing (`interface More extends Counts {}`) is that + dictionary too (`type More = Counts`); one adding members of its own stays an interface. - Later: a generic class, interface or type alias instantiated inside a generic function with a type parameter of the same name as one of its own (`Box` in `f`, Box's parameter named T) took the function's: the instance's context starts from the function's type parameters and aliases, a type parameter as an argument did @@ -2155,16 +2156,25 @@ Still open, looked at: - -mm=own: a local moved inside two `if`s one after the other (`if (a) keep(k); if (b) keep(k);`) is "moved here on some paths only" - so the dictionary copies its keys rather than taking the caller's; a spread of a record into a dictionary is refused (its fields would have two owners). -- A spread of a dictionary into one of another value type is an error for now. The generic-inference bug it - waited on is fixed (above); what is left is the default library's `objectDictionaryAssign(target, source)` - taking two type parameters, a library change to land first. +- Later: a spread of a dictionary into one of another value type (`{ ...ints }` of `int`s where numbers are wanted) + calls `__dictionary_assign_values`, made from source once a module, each value cast (it was an error: the + library's objectDictionaryAssign takes two of one type). A call, not a loop in place: under -mm=own the dictionary + made there is lent to it. (Under -mm=own a dictionary of a union holding strings is refused anyway: "a value that + borrows the result of 'ObjectDictionary.get' cannot be stored", open.) - `a[a.length] = x` on an array did not grow it (gc wrote past the end; rc and own crashed). Fixed under gc, rc and none: the element store grows the array to `i + 1` first when `i` is at or past the length (mlirGenGrowArrayForWrite, SetLengthOf: the slots in between read as the element type's default; a negative - index grows nothing). Test `00array_write_grows.ts`. Still open under -mm=own: growing through the array's - slot - a parameter's, or a `let`'s over one - reads to its passes as keeping the parameter ("'src' is a - parameter, kept here"), and a field's extra read of the array as a second reference; under own the write is - as before. + index grows nothing). Test `00array_write_grows.ts`. Later under -mm=own too: there the growth is a + SetLengthOf in place, unconditional and marked as only growing (ARRAY_GROWS_ONLY_ATTR_NAME: its lowering keeps the + longer length, a negative index grows nothing), which -mm=own's passes read as a push (growsOnly). As the call + the other models make, they read the array's slot given to it as kept ("'src' is a parameter, kept here") and + the elements a borrow reads as dropped; in a branch between the value stored and its store, the store as a + second reference. Not through a local over a parameter's array (`let src = order; src[i] = v`): changed in place + through it - a push too - the local owns what it holds and the parameter is kept, so there the write is as before + (open). A parameter's array, a field's of a parameter, arrays of objects and of arrays: flat at 6 MB over 200000 + rounds (gc, rc, own), clean on the wasm checked heap (own, rc). Not when the right side gave the variable another array (`a[1] = (a = [5], + 9)`): the store goes into the one the left side read; a store of another through another place (`h.a[0] = (h.a = + [5], 9)`, or in a call) is not seen, and grows the new one (open). Tests: `00object_dictionary.ts`, `00own_param_exclusive_moves.ts` (compile, JIT, rc, own). @@ -2227,9 +2237,21 @@ Tests: `00object_dictionary.ts`, `00own_param_exclusive_moves.ts` (compile, JIT, and "f" was not printed): TryOpLowering copies the finally for each way out of the try (the end of its body, the unwind, each return/break/continue), each copy with the yield's resume label, and the generator's switch dispatches by position - the copies shifted every label after them, so the resume landed after the yield in - another copy. Now an error at the yield (YieldInFinally), as a yield in a catch is, and a repeated resume label is - an error in the lowering rather than a resume somewhere else. Tests `generator_yield_in_finally.ts` - (diagnostic-location), `00generator_finally.ts`. + another copy. First an error (#980); then, USER DECISION, made to work as JavaScript's + (mlirGenTryWithYieldingFinally): the try and its catch clause in a labelled block with a catch-all keeping the + exception; each `return` in them (and return()'s at a resume point), and each `break`/`continue` out of them, + records its way out in a mode variable and leaves the block (YieldingFinally); the finally once after it, as code + a yield resumes in; then the way out taken. A return's value is kept in a variable of the generator; one through + two such finallys is handed on with the same one. return(v) gives what the finally yields and finishes with v + (kept in `.thrown`). A repeated resume label is an error in the lowering rather than a resume somewhere else. + return() while paused in a yield* finishes through the finally too (the delegate is left where it is: its own + finally blocks do not run). Under -mm=own, open: an object thrown through such a finally stops with "cannot copy + an 'any' that holds an object" (the exception kept is an `any`; numbers and strings work); a value that owns + memory returned through it is an error at the return (what is returned would be a borrow of the generator's + field); return() in a yield* is as before (and a yield* of a Generator is refused under own already: "a value + that borrows a field is used here after it may be released", before these changes too). Also: a `let` of a nested block hiding one around + it in a generator shared its field of the generator object (the outer `x` read the inner's value after the + block): a field of its own now. Tests `00generator_yield_in_finally.ts` (results node's), `00generator_finally.ts`. - Later: a generator is its own iterator - `g[Symbol.iterator]()` (`[Symbol.asyncIterator]` of an async one) is g itself, made at the call: a generator's object has a step and no member of that name. It was "Can't resolve @@ -2239,16 +2261,20 @@ Tests: `00object_dictionary.ts`, `00own_param_exclusive_moves.ts` (compile, JIT, `00generator_symbol_iterator.ts` (compile, JIT, rc, own). Still open, looked at: -- A yield in a finally block (an error, above): supporting it needs the finally lowered as straight code after the - try when it yields - a catch-all keeping the exception, the way out recorded (end, throw, return, break, - continue, the generator's return()/throw()), and taken again after the finally - not as the try's finally region. -- -mm=own: next(value) of a generator sending it an object (`Generator`) is refused ("'this value' - is a parameter, kept here, but -mm=own cannot make the callers of this function expression give it up"): next() - keeps what it is given, and a method used other than by a call can't make its callers give it up. A number or a - string works. -- -mm=own: a generator typed as an interface other than the library-instantiated Iterator - a program's own, or - Iterable - is "a value takes a second reference; -mm=own cannot prove a move or a borrow here yet" at its - `for...of` (before these changes too), and so is an array given as an Iterable. +- -mm=own: next(value) of a generator sending it an object (`Generator`): the generator keeps what it + is sent (`const b = yield x` is a variable of the generator), and next() is called through the Generator + interface, whose callers can't be made to give it up. Sent as a Shared it works; one of another type is now an + error at the yield that says so (it was "'this value' is a parameter, kept here"). Tests + `00generator_next_shared.ts`, diagnostic-location `generator_next_object_own.ts`. +- -mm=own: a generator typed as an interface of the program's own (an Iterable with next) works now. An array + given as an Iterable was "a value takes a second reference": the generator made over it would hold a borrow of + the array for as long as it lives, which -mm=own can't say. USER DECISION 2026-11-21: under -mm=own it iterates a + copy - `__array_values_owned` borrows the array, pushes its elements into a local and moves that into + `__array_values_of_copy` (@keeps), declared to return the interface: a generator object becomes an interface + only at its own function's return under -mm=own. A string the same way (`__string_values_owned`). An array of + objects can't be copied there (refused); a for...of over such an interface of strings is still "a second + reference" (open). Test `00iterable_array_copy.ts` (compile, JIT, rc, own). (A generator typed as such an interface + with yields of integer literals is typed by them, not by T, in every model: only the library's names give T.) Tests: `00iterables.ts`, `00generator_typed_yield.ts` (compile, JIT, rc), diagnostic-location `generator_return_of_other_type.ts`; `00generator_next_value.ts`, `00object_method_arity.ts`, diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index aff8a1588..68b545cb2 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -363,6 +363,9 @@ #define CALL_FIELD_NAME ".call" #define THIS_ALIAS ".this" #define GENERATOR_STEP ".step" +// a SetLengthOf of `a[i] = v` past the end of the array under -mm=own (mlirGenGrowArrayForWrite): it only grows - +// it releases no element - so to -mm=own's passes it is what a push is to the array, not a change of length +#define ARRAY_GROWS_ONLY_ATTR_NAME "__grows_only" #define GENERATOR_SWITCHSTATE ".switchstate" #define GENERATOR_STATELABELPREFIX ".state" diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index d95e8a4b5..1aa3eaf3f 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -97,6 +97,28 @@ struct WithScope std::shared_ptr outer; }; +// A `try` of a generator whose `finally` yields (mlirGenTryWithYieldingFinally): its body and catch clause are +// generated in a labelled block, and each way out of them other than its end - a `return` (and the one return() +// makes at a resume point), a `break` or `continue` out of the `try` - records which it was in the mode variable +// and leaves the block; the finally is generated once after it, as code of its own a yield can resume in, and +// then each recorded way out is taken. A `return`'s value is kept in a variable of the generator (`slot`). +struct YieldingFinallyExit +{ + enum Kind { Return, Break, Continue } kind; + std::string label; + std::string slot; + unsigned internalFlags = 0; +}; + +struct YieldingFinally +{ + std::string label; + std::string mode; + std::string slotPrefix; + mlir::Operation *funcOp = nullptr; + llvm::SmallVector exits; +}; + struct GenContext { GenContext() = default; @@ -334,6 +356,8 @@ struct GenContext // there - one entry for each place they go, and the finally gets the rest of the scope exit // for each. Shared by the body's guard and the catch clause's, which is a copy of it. mlir::SmallVector> *finallyEscapingJumps = nullptr; + // In a `try` of a generator whose `finally` yields: where its ways out go (YieldingFinally) + YieldingFinally *yieldingFinally = nullptr; // out-of-band cancellation signal; mutable so stop() stays callable through the const& threading mutable bool stopProcess = false; mlir::SmallVector> *postponedMessages = nullptr; diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 70dc3ee40..cd342462e 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -1125,6 +1125,14 @@ class SetLengthOfOpLowering : public TsLlvmPattern mlir::Value newCountAsLLVMType = rewriter.create(loc, llvmIndexType, op.getNewLength()); + // only growing (`a[i] = v` under -mm=own, mlirGenGrowArrayForWrite): the longer of the two, compared signed - + // the length a negative index asks for is never longer + if (op->hasAttr(ARRAY_GROWS_ONLY_ATTR_NAME)) + { + auto longer = rewriter.create(loc, LLVM::ICmpPredicate::sgt, newCountAsLLVMType, countAsLLVMType); + newCountAsLLVMType = rewriter.create(loc, longer, newCountAsLLVMType, countAsLLVMType); + } + // A longer array grows its block by doubling (a no-op while the capacity suffices), and a // shorter one keeps it (spec section 6). auto allocated = layout.ensureCapacity(arrayType, header, newCountAsLLVMType); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 3ffb52ea1..348470b0a 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -4176,12 +4176,42 @@ namespace mlirgen auto spreadValue = V(spreadResult); if (dictionaryClassInfoOf(spreadValue.getType(), genContext)) { + // of values of another type (`{ ...counts }` of numbers into a dictionary of `number | string`): a + // function made here from source once a module, each value cast to the dictionary's - the library's + // objectDictionaryAssign takes two of one type. A call, as that one's: under -mm=own the dictionary + // made here is lent to it (in place, the loop's second name for it was a second reference) if (spreadValue.getType() != dictionary.getType()) { - emitError(spreadLocation) << "a spread of '" << to_print(spreadValue.getType()) << "' into '" - << to_print(dictionary.getType()) - << "' is not supported yet: the values' types have to be the same"; - return ValueOrLogicalResult(mlir::failure()); + // ("_" in front of "__", as the scanner puts it) + auto convertName = "___dictionary_assign_values"; + auto convert = resolveIdentifier(spreadLocation, convertName, genContext); + if (!convert) + { + std::string src = std::string("function __dictionary_assign_values(target: ") + + OBJECT_DICTIONARY_CLASS_NAME + ", source: " + OBJECT_DICTIONARY_CLASS_NAME + + ") {\nfor (const k in source) { const v = source[k]; if (v !== undefined) target[k] = v; }\n}\n"; + MLIRLocationGuard vgLoc(overwriteLoc); + overwriteLoc = spreadLocation; + if (mlir::failed(parsePartialStatements(stows(src)))) + { + return ValueOrLogicalResult(mlir::failure()); + } + + convert = resolveIdentifier(spreadLocation, convertName, genContext); + if (!convert) + { + return ValueOrLogicalResult(mlir::failure()); + } + } + + SmallVector operands{dictionary, spreadValue}; + auto converted = mlirGenCallExpression(spreadLocation, convert, {}, operands, genContext); + if (mlir::failed(converted.result)) + { + return ValueOrLogicalResult(mlir::failure()); + } + + continue; } auto assign = resolveIdentifier(spreadLocation, OBJECT_DICTIONARY_ASSIGN_NAME, genContext); diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 1ec305f5b..d55853ef9 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -1821,7 +1821,9 @@ namespace mlirgen // an iterator - it has `next`, whose result's `value` is its element - and an array or a string has none of // its members. A generator over the elements, made here from source once a module (`__array_values`, // `__string_values`), is: its elements are cast to the interface's element type as they are given (`s32` - // to `number`). Under -mm=own the generator borrows the array (@borrows), as an array's values() does. + // to `number`). Under -mm=own it iterates a copy of the array, which it owns (USER DECISION 2026-11-21): a + // generator borrowing the array would have to hold the borrow for as long as it lives, which -mm=own can't say - + // `sum(a)` was "a value takes a second reference". (An array of objects, which can't be copied, stays refused.) std::optional MLIRGenImpl::castIterableToIterator(mlir::Location location, mlir::Value value, mlir::Type baseValueType, mlir_ts::InterfaceType interfaceType, const GenContext &genContext) { @@ -1867,19 +1869,37 @@ namespace mlirgen } auto isString = isa(baseValueType); + auto ownModel = compileOptions.memoryModel == MemoryModelOwn; + auto ownsCopy = !isString && ownModel; // info, we add "_" extra as scanner append "_" in front of "__"; - auto funcName = isString ? "___string_values" : "___array_values"; + auto funcName = isString ? (ownModel ? "___string_values_owned" : "___string_values") + : ownsCopy ? "___array_values_owned" : "___array_values"; auto funcRef = resolveIdentifier(location, funcName, genContext); if (!funcRef) { - std::string src = isString ? "@borrows(\"s\")\n" + // under -mm=own declared to return the interface (I): there a generator object becomes an interface only + // at its function's own return ("a value takes a second reference" anywhere else) + std::string src = isString && ownModel ? "@keeps(\"s\")\n" + "function* __string_values_owned(s: string): I {\n" + "for (const c of s) yield c;\n" + "}\n" + : isString ? "@borrows(\"s\")\n" "function* __string_values(s: string) {\n" "for (const c of s) yield c;\n" "}\n" - : "@borrows(\"a\")\n" - "function* __array_values(a: T[]) {\n" - "for (const v of a) yield v;\n" - "}\n"; + : ownsCopy ? "@keeps(\"c\")\n" + "function* __array_values_of_copy(c: T[]): I {\n" + "for (const v of c) yield v;\n" + "}\n" + "function __array_values_owned(a: T[]): I {\n" + "const c: T[] = [];\n" + "for (const v of a) c.push(v);\n" + "return __array_values_of_copy(c);\n" + "}\n" + : "@borrows(\"a\")\n" + "function* __array_values(a: T[]) {\n" + "for (const v of a) yield v;\n" + "}\n"; MLIRLocationGuard vgLoc(overwriteLoc); overwriteLoc = location; if (mlir::failed(parsePartialStatements(stows(src)))) @@ -1916,7 +1936,8 @@ namespace mlirgen return ValueOrLogicalResult(mlir::failure()); } - operands.push_back(V(arrayValue)); + auto elements = V(arrayValue); + operands.push_back(elements); } // generic, the string one too (its T unused): a function made only in a pass whose module is thrown away @@ -1924,6 +1945,11 @@ namespace mlirgen NodeFactory nf(NodeFactoryFlags::None); iterGenContext.typeAliasMap.insert({".ITER_T", isString ? mlir::Type(getStringType()) : elementType}); typeArguments.push_back(nf.createTypeReferenceNode(nf.createIdentifier(S(".ITER_T")).as())); + if (ownModel) + { + iterGenContext.typeAliasMap.insert({".ITER_I", interfaceType}); + typeArguments.push_back(nf.createTypeReferenceNode(nf.createIdentifier(S(".ITER_I")).as())); + } auto generator = mlirGenCallExpression(location, funcRef, typeArguments, operands, iterGenContext); if (generator.failed_or_no_value()) diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index be79fc926..6e2d8070e 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -458,14 +458,6 @@ namespace mlirgen return mlir::failure(); } - if (!!(yieldExpressionAST->internalFlags & InternalFlags::YieldInFinally)) - { - emitError(location, "a yield in a finally block of a generator is not supported yet: the finally is run " - "from each way out of the try statement, and the generator can't resume in the one " - "that runs while an exception unwinds; yield after the try statement"); - return mlir::failure(); - } - if (yieldExpressionAST->asteriskToken) { // it gives back nothing yet: it can only stand as a statement of its own @@ -540,6 +532,24 @@ namespace mlirgen // TNext> has - or undefined. It is read after the label: the turn that resumes here is the one that uses it. if (auto sent = resolveIdentifier(location, GENERATOR_SENT_NAME, genContext)) { + // -mm=own: a value the generator uses is one it keeps (`const b = yield x` is a variable of the generator, + // which lives between turns), and next() is called through the Generator interface, whose callers can't be + // made to give their value up - a Shared they can (a string is copied) + auto sentType = sent.getType(); + if (auto optType = dyn_cast(sentType)) + { + sentType = optType.getElementType(); + } + + if (compileOptions.memoryModel == MemoryModelOwn && supportedYield->second && !isa(sentType) && !isa(sentType) && + mth.ownsHeapMemory(location, sentType)) + { + emitError(location) << "-mm=own: a value of type '" << to_print(sentType) + << "' sent by next() is kept by the generator, and its callers can't be made to give it " + "up: give the generator's TNext as Shared<" << to_print(sentType) << ">"; + return mlir::failure(); + } + // a TNext, as TypeScript types the `yield`: the parameter is optional (the first next(), a for...of, // give none), and a turn given none reads TNext's default (0 for a number, null for a class) if (auto optType = dyn_cast(sent.getType())) diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index b5bc4a0c5..a258b45d9 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1162,13 +1162,15 @@ namespace mlirgen // its own try/catch may catch, and then it goes on to its next yield); one not started yet, or finished, does // not run: return(value) gives `{ value, done: true }`, throw(e) throws e. Either finishes the generator // (step -1), unless its body caught the throw. GENERATOR_MODE_NAME tells the yield how to resume - // (mlirGenGeneratorResumeChecks). A finally block that yields again is not followed: return() still finishes. + // (mlirGenGeneratorResumeChecks). A finally block that yields on the way out pauses the generator again: + // return() gives what it yields, and the value is the generator's result when the finally is done. void MLIRGenImpl::addGeneratorResumeMethods(NodeFactory &nf, FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, TypeNode yieldType, NodeArray &generatorObjectProperties) { // the yields of the body - not of a function inside it - resume checking the mode + // (a yield* hands it on to the yields its loop makes, mlirGenYieldStar) FilterVisitorSkipFuncsAST yieldsVisitor(SyntaxKind::YieldExpression, [&](auto yieldExpression) { - if (!yieldExpression->asteriskToken) + if (!yieldExpression->asteriskToken || compileOptions.memoryModel != MemoryModelOwn) { yieldExpression->internalFlags |= InternalFlags::GeneratorResumable; } @@ -1227,7 +1229,7 @@ namespace mlirgen }; // return(value: T) { - // if (this.step > 0) { this.mode = 2; this.next(); } + // if (this.step > 0) { this.mode = 2; this.thrown = value; return this.next(); } // this.step = -1; // return { value: value, done: true }; // } @@ -1245,7 +1247,10 @@ namespace mlirgen NodeArray resume; resume.push_back(assign(thisProp(GENERATOR_MODE_NAME), number("2"))); - resume.push_back(nf.createExpressionStatement(callNext())); + // the value the generator finishes with (the resume point's `return this.thrown`), a yield of a finally + // on the way out given back as the result + resume.push_back(assign(thisProp(GENERATOR_THROWN_NAME), nf.createTypeAssertion(anyType(), nf.createIdentifier(S("value"))))); + resume.push_back(nf.createReturnStatement(callNext())); NodeArray resultProperties; resultProperties.push_back(nf.createPropertyAssignment(nf.createIdentifier(S("value")), nf.createIdentifier(S("value")))); @@ -1318,7 +1323,8 @@ namespace mlirgen throwStatements.push_back(resetMode()); throwStatements.push_back(nf.createThrowStatement(thisProp(GENERATOR_THROWN_NAME))); - auto finish = nf.createReturnStatement(undefined); + // with the value return() was given (kept in `.thrown`) + auto finish = nf.createReturnStatement(thisProp(GENERATOR_THROWN_NAME)); finish->internalFlags |= InternalFlags::GeneratorReturn; NodeArray returnStatements; returnStatements.push_back(resetMode()); @@ -1425,6 +1431,7 @@ namespace mlirgen { FilterVisitorSkipFuncsAST yieldsInFinally(SyntaxKind::YieldExpression, [&](auto yieldExpression) { yieldExpression->internalFlags |= InternalFlags::YieldInFinally; + tryStatement->internalFlags |= InternalFlags::YieldInFinally; }); yieldsInFinally.visit(tryStatement->finallyBlock); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index c14e7236c..f911901b0 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -2827,7 +2827,17 @@ class MLIRGenImpl if (variableDeclarationInfo.allocateInContextThis) { - auto varValueInThisContext = registerVariableInThisContext(location, variableDeclarationInfo.variableName, variableDeclarationInfo.type, genContext); + // a generator's local is a field of the generator object, by name: one of a nested block hiding one + // around it (`let x = 1; { let x = 2; yield x; } yield x`) gets a field of its own - it shared the + // outer one's, and the outer `x` read 2 after the block + std::string fieldName = variableDeclarationInfo.variableName.str(); + if (symbolTable.count(variableDeclarationInfo.variableName)) + { + LocationHelper lh(builder.getContext()); + fieldName += "@" + std::to_string(std::get<0>(lh.getSpan(location))); + } + + auto varValueInThisContext = registerVariableInThisContext(location, fieldName, variableDeclarationInfo.type, genContext); variableDeclarationInfo.setStorage(varValueInThisContext); } @@ -4802,6 +4812,14 @@ class MLIRGenImpl // copy location info, to fix issue with names of anonymous functions _yield_expr->pos = yieldExpressionAST->pos; _yield_expr->_end = yieldExpressionAST->_end; + // where it resumes, return() and throw() of the generator are checked for, as at its own yields (the + // delegate is left where it is: its finally blocks do not run). Not under -mm=own yet: there the return and the + // throw at the resume point, inside the loop over the delegate - a field of the generator - were taken for a + // release of what the loop borrows from it + if (compileOptions.memoryModel != MemoryModelOwn) + { + _yield_expr->internalFlags |= yieldExpressionAST->internalFlags & InternalFlags::GeneratorResumable; + } auto forOfStat = nf.createForOfStatement(undefined, declList, yieldExpressionAST->expression, @@ -17836,6 +17854,19 @@ class MLIRGenImpl const GenContext &genContext); bool isStringIndexSignatureOnly(InterfaceDeclaration interfaceDeclarationAST, const GenContext &genContext); + // the interfaces that are dictionaries (isStringIndexSignatureOnly), by name: one extending one of them and adding + // nothing is that dictionary too + llvm::StringSet<> dictionaryInterfaces; + + mlir::Operation *currentFunctionOp(); + YieldingFinally *yieldingFinallyOf(const GenContext &genContext); + mlir::LogicalResult mlirGenTryWithYieldingFinally(TryStatement tryStatementAST, const GenContext &genContext); + mlir::LogicalResult mlirGenReturnThroughYieldingFinally(ReturnStatement returnStatementAST, YieldingFinally &yieldingFinally, + const GenContext &genContext); + bool jumpLeavesYieldingFinally(bool isBreak, const std::string &label, const YieldingFinally &yieldingFinally, + const GenContext &genContext); + mlir::LogicalResult mlirGenJumpThroughYieldingFinally(mlir::Location location, bool isBreak, Identifier label, + YieldingFinally &yieldingFinally, const GenContext &genContext); mlir::LogicalResult mlirGen(InterfaceDeclaration interfaceDeclarationAST, const GenContext &genContext); @@ -19010,7 +19041,8 @@ class MLIRGenImpl //LLVM_DEBUG(llvm::dbgs() << "\n!! declare variable: " << name << " = [" << value << "]\n";); - if (showWarnings && symbolTable.count(name)) + // (a generator's local hiding one around it is a field of its own: createLocalVariable) + if (showWarnings && symbolTable.count(name) && !genContext.allocateVarsInContextThis) { auto previousVariable = symbolTable.lookup(name).first; if (previousVariable && previousVariable.getParentBlock() == value.getParentBlock()) @@ -20223,17 +20255,56 @@ class MLIRGenImpl return; } - // Not under -mm=own yet: the array's slot written - a parameter's, a `let` over one ("'src' is a parameter, - // kept here") - and the array read once more before the store (a field's: "a value takes a second - // reference") are ways its passes do not take yet (TSLANG 152) + // the right side gave the variable another array (`a[1] = (a = [5], 9)`): the store goes into the array the + // left side read, as in JavaScript, and the slot now holds another one - nothing to grow through it + if (auto loadOp = array.getDefiningOp(); loadOp && loadOp->getBlock() == builder.getInsertionBlock()) + { + auto reassigned = false; + for (auto *op = loadOp->getNextNode(); op && !reassigned; op = op->getNextNode()) + { + op->walk([&](mlir_ts::StoreOp storeOp) { + reassigned |= storeOp.getReference() == arrayRef; + }); + } + + if (reassigned) + { + return; + } + } + + auto index32 = elementRefOp.getIndex(); + auto i32Type = builder.getI32Type(); + + // Under -mm=own in place, unconditionally, marked as only growing - its lowering keeps the longer of the two + // lengths, and a negative index grows nothing. Its passes took a call given the array's slot for one that may + // keep the slot's value (a parameter's: "'src' is a parameter, kept here") or drop the elements a borrow + // reads, and a growth in a branch between the value stored and its store for a second reference of it; they + // read this as a push (growsOnly). if (compileOptions.memoryModel == MemoryModelOwn) { + // Not through a local over a parameter's array (`let src = order; src[i] = v`): changed in place through + // it - a push too - the local owns what it holds, and the parameter is kept, which the callers can't be + // made to give up; every write through it, past the end or not, was refused. As before there (TSLANG 152). + if (auto varOp = arrayRef.getDefiningOp(); varOp && varOp->getNumOperands() > 0) + { + if (auto loadOp = varOp->getOperand(0).getDefiningOp(); + loadOp && loadOp.getReference().getDefiningOp()) + { + return; + } + } + + auto one = builder.create(location, i32Type, builder.getI32IntegerAttr(1)); + auto newLength32 = builder.create( + location, i32Type, builder.getI32IntegerAttr((int)SyntaxKind::PlusToken), index32, one); + auto newLength = builder.create(location, builder.getIndexType(), newLength32); + auto growOp = builder.create(location, arrayRef, newLength); + growOp->setAttr(ARRAY_GROWS_ONLY_ATTR_NAME, builder.getUnitAttr()); return; } // index >= length, signed: a negative index is never past the end - auto index32 = elementRefOp.getIndex(); - auto i32Type = builder.getI32Type(); auto length = builder.create(location, builder.getIndexType(), array); auto length32 = builder.create(location, i32Type, length); auto condition = builder.create( diff --git a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp index 74cb5a950..dd278d8f6 100644 --- a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp +++ b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp @@ -1446,8 +1446,34 @@ namespace mlirgen mlir::LogicalResult MLIRGenImpl::mlirGen(InterfaceDeclaration interfaceDeclarationAST, const GenContext &genContext) { + // `interface I2 extends D {}` of a dictionary interface D, adding nothing: that dictionary, `type I2 = D` + // (it was an interface extending a class: "indexer is not declared" at an index of it) + if (interfaceDeclarationAST->members.size() == 0 && interfaceDeclarationAST->heritageClauses.size() == 1) + { + auto heritageClause = interfaceDeclarationAST->heritageClauses.front(); + if (heritageClause->token == SyntaxKind::ExtendsKeyword && heritageClause->types.size() == 1) + { + auto extended = heritageClause->types.front(); + if (extended->expression == SyntaxKind::Identifier && + dictionaryInterfaces.contains(MLIRHelper::getName(extended->expression.as()))) + { + NodeFactory nf(NodeFactoryFlags::None); + auto typeReference = nf.createTypeReferenceNode(extended->expression.as(), extended->typeArguments); + typeReference->pos = extended->pos; + typeReference->_end = extended->_end; + auto typeAlias = nf.createTypeAliasDeclaration(interfaceDeclarationAST->modifiers, interfaceDeclarationAST->name, + interfaceDeclarationAST->typeParameters, typeReference); + typeAlias->pos = interfaceDeclarationAST->pos; + typeAlias->_end = interfaceDeclarationAST->_end; + typeAlias->parent = interfaceDeclarationAST->parent; + return mlirGen(typeAlias, genContext); + } + } + } + if (isStringIndexSignatureOnly(interfaceDeclarationAST, genContext)) { + dictionaryInterfaces.insert(MLIRHelper::getName(interfaceDeclarationAST->name)); NodeFactory nf(NodeFactoryFlags::None); auto typeLiteral = nf.createTypeLiteralNode(interfaceDeclarationAST->members); typeLiteral->pos = interfaceDeclarationAST->pos; diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 6eccad433..34d200875 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -856,6 +856,12 @@ namespace mlirgen { auto location = loc(returnStatementAST); + // in a `try` whose `finally` yields: through it (mlirGenTryWithYieldingFinally) + if (auto *yieldingFinally = yieldingFinallyOf(genContext)) + { + return mlirGenReturnThroughYieldingFinally(returnStatementAST, *yieldingFinally, genContext); + } + // `return e` in a generator: {value: e, done: true}, and every next() after it is done (step -1) if (!!(returnStatementAST->internalFlags & InternalFlags::GeneratorReturn)) { @@ -1936,6 +1942,12 @@ namespace mlirgen auto location = loc(continueStatementAST); auto label = MLIRHelper::getName(continueStatementAST->label); + if (auto *yieldingFinally = yieldingFinallyOf(genContext); + yieldingFinally && jumpLeavesYieldingFinally(false, label, *yieldingFinally, genContext)) + { + return mlirGenJumpThroughYieldingFinally(location, false, continueStatementAST->label, *yieldingFinally, genContext); + } + // a `continue` to the label of a block (not a loop) starts the block again: an extension // TypeScript doesn't have (tests/00break_continue.ts) if (!label.empty() && !llvm::is_contained(activeLabels, label)) @@ -1956,6 +1968,13 @@ namespace mlirgen auto location = loc(breakStatementAST); auto label = MLIRHelper::getName(breakStatementAST->label); + if (auto *yieldingFinally = yieldingFinallyOf(genContext); + yieldingFinally && label != yieldingFinally->label && + jumpLeavesYieldingFinally(true, label, *yieldingFinally, genContext)) + { + return mlirGenJumpThroughYieldingFinally(location, true, breakStatementAST->label, *yieldingFinally, genContext); + } + if (!label.empty() && !llvm::is_contained(activeLabels, label)) { emitError(location, "A 'break' statement can only jump to a label of an enclosing statement"); @@ -2465,8 +2484,280 @@ namespace mlirgen return mlir::success(); } + // the function the insertion point is in: a jump redirected by a YieldingFinally is one of its own function's + mlir::Operation *MLIRGenImpl::currentFunctionOp() + { + auto *block = builder.getInsertionBlock(); + if (!block || !block->getParent()) + { + return nullptr; + } + + if (auto funcOp = mlir::dyn_cast_or_null(block->getParentOp())) + { + return funcOp; + } + + return block->getParent()->getParentOfType(); + } + + YieldingFinally *MLIRGenImpl::yieldingFinallyOf(const GenContext &genContext) + { + auto *yieldingFinally = genContext.yieldingFinally; + return yieldingFinally && yieldingFinally->funcOp == currentFunctionOp() ? yieldingFinally : nullptr; + } + + // `try { ...; yield ...; } finally { ...; yield ...; }` in a generator. The finally is not the try's finally + // region: TryOpLowering copies that for each way out of the try, the copy on the unwind leg inside an + // exception handler, and a resume lands in one copy only. Here it is code of its own after the try, once: + // + // let M = 0, E: any = 0; + // L: { try { catch } catch (X) { E = X; M = 1; } } + // + // if (M == 1) throw E; + // if (M == 2) return this.R2; ... if (M == k) break label; ... + // + // Each `return` in the try or the catch clause (and the one return() makes at a resume point), and each + // `break` or `continue` out of them, sets M and leaves L instead (yieldingFinallyOf, YieldingFinally). A + // `return`'s value is kept in a variable of the generator, which lives between turns. + mlir::LogicalResult MLIRGenImpl::mlirGenTryWithYieldingFinally(TryStatement tryStatementAST, const GenContext &genContext) + { + NodeFactory nf(NodeFactoryFlags::None); + auto base = std::string("$fin") + std::to_string(tryStatementAST->pos); + + YieldingFinally yieldingFinally; + yieldingFinally.label = base + "_l"; + yieldingFinally.mode = base + "_m"; + yieldingFinally.slotPrefix = base + "_r"; + yieldingFinally.funcOp = currentFunctionOp(); + + auto ident = [&](const std::string &name) { return nf.createIdentifier(stows(name)); }; + auto number = [&](int value) { return nf.createNumericLiteral(stows(std::to_string(value)), TokenFlags::None); }; + auto placed = [&](auto node) { + node->pos = tryStatementAST->pos; + node->_end = tryStatementAST->_end; + return node; + }; + auto assign = [&](const std::string &name, Expression value) { + return placed(nf.createExpressionStatement( + nf.createBinaryExpression(ident(name), nf.createToken(SyntaxKind::EqualsToken), value))); + }; + auto declare = [&](const std::string &name, Expression init) { + NodeArray declarations; + declarations.push_back(nf.createVariableDeclaration(ident(name), undefined, undefined, init)); + return placed(nf.createVariableStatement(undefined, nf.createVariableDeclarationList(declarations, NodeFlags::Let))); + }; + auto modeIs = [&](int value) { + return nf.createBinaryExpression(ident(yieldingFinally.mode), nf.createToken(SyntaxKind::EqualsEqualsEqualsToken), + number(value)); + }; + + auto excName = base + "_e"; + auto caughtName = base + "_x"; + + EXIT_IF_FAILED(mlirGen(declare(yieldingFinally.mode, number(0)), genContext)); + // (a number in it, not `undefined`, as the generator's own `.thrown`) + EXIT_IF_FAILED(mlirGen(declare(excName, nf.createTypeAssertion(nf.createToken(SyntaxKind::AnyKeyword).as(), number(0))), + genContext)); + + // the try and its catch clause, without the finally + NodeArray innerStatements; + if (tryStatementAST->catchClause) + { + innerStatements.push_back(placed(nf.createTryStatement(tryStatementAST->tryBlock, tryStatementAST->catchClause, undefined))); + } + else + { + innerStatements.push_back(tryStatementAST->tryBlock); + } + + // what they throw, kept for after the finally + NodeArray caughtStatements; + caughtStatements.push_back(assign(excName, ident(caughtName))); + caughtStatements.push_back(assign(yieldingFinally.mode, number(1))); + auto catchAll = nf.createCatchClause(nf.createVariableDeclaration(ident(caughtName), undefined, undefined, undefined), + placed(nf.createBlock(caughtStatements, false))); + auto outerTry = placed(nf.createTryStatement(placed(nf.createBlock(innerStatements, false)), catchAll, undefined)); + + NodeArray labelledStatements; + labelledStatements.push_back(outerTry); + auto labelled = placed(nf.createLabeledStatement(ident(yieldingFinally.label), placed(nf.createBlock(labelledStatements, false)))); + + { + GenContext bodyGenContext(genContext); + bodyGenContext.yieldingFinally = &yieldingFinally; + EXIT_IF_FAILED(mlirGen(labelled, bodyGenContext)); + } + + // the finally, once, where a yield can resume + EXIT_IF_FAILED(mlirGen(tryStatementAST->finallyBlock, genContext)); + + // then the way out the try took + EXIT_IF_FAILED(mlirGen(placed(nf.createIfStatement(modeIs(1), placed(nf.createThrowStatement(ident(excName))), undefined)), + genContext)); + + for (auto [index, exit] : llvm::enumerate(yieldingFinally.exits)) + { + Statement statement; + switch (exit.kind) + { + case YieldingFinallyExit::Return: + { + // in a `try` around this one whose finally yields too: on through its finally, with the same slot + if (auto *outer = yieldingFinallyOf(genContext)) + { + auto code = 2 + (int)outer->exits.size(); + outer->exits.push_back(exit); + NodeArray forward; + forward.push_back(assign(outer->mode, number(code))); + forward.push_back(placed(nf.createBreakStatement(ident(outer->label)))); + statement = placed(nf.createBlock(forward, false)); + break; + } + + Expression value = undefined; + // (while the generator's variables are being found, the slot is not one of its fields yet) + if (!exit.slot.empty() && !genContext.passResult) + { + value = nf.createPropertyAccessExpression(nf.createToken(SyntaxKind::ThisKeyword), ident(exit.slot)); + } + + auto returnStatement = placed(nf.createReturnStatement(value)); + returnStatement->internalFlags = (InternalFlags)exit.internalFlags; + statement = returnStatement; + break; + } + case YieldingFinallyExit::Break: + statement = placed(nf.createBreakStatement(exit.label.empty() ? Identifier(undefined) : ident(exit.label))); + break; + case YieldingFinallyExit::Continue: + statement = placed(nf.createContinueStatement(exit.label.empty() ? Identifier(undefined) : ident(exit.label))); + break; + } + + EXIT_IF_FAILED(mlirGen(placed(nf.createIfStatement(modeIs(2 + (int)index), statement, undefined)), genContext)); + } + + return mlir::success(); + } + + // A `return` in the try or catch clause of a YieldingFinally: its value kept, its way out recorded, and the + // labelled block left - the finally runs before the return is made. + mlir::LogicalResult MLIRGenImpl::mlirGenReturnThroughYieldingFinally(ReturnStatement returnStatementAST, + YieldingFinally &yieldingFinally, + const GenContext &genContext) + { + NodeFactory nf(NodeFactoryFlags::None); + auto code = 2 + (int)yieldingFinally.exits.size(); + auto placed = [&](auto node) { + node->pos = returnStatementAST->pos; + node->_end = returnStatementAST->_end; + return node; + }; + + YieldingFinallyExit exit{YieldingFinallyExit::Return, "", "", (unsigned)returnStatementAST->internalFlags}; + NodeArray statements; + if (returnStatementAST->expression) + { + // -mm=own: the value kept for after the finally is a field of the generator, and what it returns is then a + // borrow of it - one that owns nothing (a number, a boolean) only, for now + // (not return()'s at a resume point, `return this.thrown`: under -mm=own a generator has return() only for a + // T that owns nothing) + auto isReturnOfResume = returnStatementAST->expression == SyntaxKind::PropertyAccessExpression && + MLIRHelper::getName(returnStatementAST->expression.as()->name) == GENERATOR_THROWN_NAME; + if (compileOptions.memoryModel == MemoryModelOwn && !isReturnOfResume) + { + auto valueType = evaluate(returnStatementAST->expression, genContext); + if (valueType && mth.ownsHeapMemory(loc(returnStatementAST), valueType)) + { + emitError(loc(returnStatementAST)) + << "-mm=own: a value of type '" << to_print(valueType) + << "' returned through a finally block that yields is not supported yet: return it after the " + "try statement, or yield it"; + return mlir::failure(); + } + } + + exit.slot = yieldingFinally.slotPrefix + std::to_string(yieldingFinally.exits.size()); + NodeArray declarations; + declarations.push_back(nf.createVariableDeclaration(nf.createIdentifier(stows(exit.slot)), undefined, undefined, + returnStatementAST->expression)); + statements.push_back(placed(nf.createVariableStatement(undefined, nf.createVariableDeclarationList(declarations, NodeFlags::Let)))); + } + + statements.push_back(placed(nf.createExpressionStatement(nf.createBinaryExpression( + nf.createIdentifier(stows(yieldingFinally.mode)), nf.createToken(SyntaxKind::EqualsToken), + nf.createNumericLiteral(stows(std::to_string(code)), TokenFlags::None))))); + statements.push_back(placed(nf.createBreakStatement(nf.createIdentifier(stows(yieldingFinally.label))))); + + yieldingFinally.exits.push_back(exit); + return mlirGen(placed(nf.createBlock(statements, false)), genContext); + } + + // Whether a `break` (isBreak) or `continue` to `label` leaves the labelled block of a YieldingFinally: it gets + // there before the loop, switch or label it goes to. A context is a copy of the one around it, so the innermost + // one already tells. + bool MLIRGenImpl::jumpLeavesYieldingFinally(bool isBreak, const std::string &label, + const YieldingFinally &yieldingFinally, const GenContext &genContext) + { + for (auto *context = &genContext; context; context = context->parentBlockContext) + { + if (label.empty()) + { + if (context->isLoopBodyScope || (isBreak && context->isSwitchScope)) + { + return false; + } + } + else if ((context->isLoopBodyScope && context->loopBodyLabel == label) || context->labelledScopeLabel == label) + { + return false; + } + + if (context->labelledScopeLabel == yieldingFinally.label) + { + return true; + } + } + + return false; + } + + mlir::LogicalResult MLIRGenImpl::mlirGenJumpThroughYieldingFinally(mlir::Location location, bool isBreak, Identifier label, + YieldingFinally &yieldingFinally, + const GenContext &genContext) + { + NodeFactory nf(NodeFactoryFlags::None); + auto code = 2 + (int)yieldingFinally.exits.size(); + yieldingFinally.exits.push_back( + {isBreak ? YieldingFinallyExit::Break : YieldingFinallyExit::Continue, MLIRHelper::getName(label), "", 0}); + + NodeArray statements; + statements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( + nf.createIdentifier(stows(yieldingFinally.mode)), nf.createToken(SyntaxKind::EqualsToken), + nf.createNumericLiteral(stows(std::to_string(code)), TokenFlags::None)))); + statements.push_back(nf.createBreakStatement(nf.createIdentifier(stows(yieldingFinally.label)))); + auto block = nf.createBlock(statements, false); + LocationHelper lh(builder.getContext()); + auto [pos, _end] = lh.getSpan(location); + block->pos = pos; + block->_end = _end; + for (auto statement : statements) + { + statement->pos = pos; + statement->_end = _end; + } + + return mlirGen(block, genContext); + } + mlir::LogicalResult MLIRGenImpl::mlirGen(TryStatement tryStatementAST, const GenContext &genContext) { + if (!!(tryStatementAST->internalFlags & InternalFlags::YieldInFinally)) + { + return mlirGenTryWithYieldingFinally(tryStatementAST, genContext); + } + auto location = loc(tryStatementAST); // An `await` in a `finally` (of an async function): the finally runs from the try's cleanup, which an diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index afacf7a14..6cf2cb6a4 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -798,6 +798,12 @@ inline bool isFresh(mlir::Value value) return def->hasAttr(OWNED_RESULT_ATTR_NAME) || isLiteral(def); } +// A SetLengthOf that only grows the array (`a[i] = v` past its end): it releases no element +inline bool growsOnly(mlir::Operation *op) +{ + return mlir::isa(op) && op->hasAttr(ARRAY_GROWS_ONLY_ATTR_NAME); +} + inline bool isCall(mlir::Operation *op) { return mlir::isa(user) && + if ((mlir::isa(user) || growsOnly(user)) && user->getOperand(0) == borrower.getResult()) { uses.push_back({user, {kills.begin(), kills.end()}}); diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 2c0f87230..fa1be1c33 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -688,6 +688,11 @@ namespace own_inference return false; } + if (growsOnly(op)) + { + return false; + } + return (isCall(op) && !callNoDrops(op)) || mlir::isa(op); diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index d6e9e5044..1ee761cce 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -500,8 +500,8 @@ namespace own_inference return true; } - return mlir::isa(user) && use.getOperandNumber() == 0 && - !reachableAfter(read, user, builder); + return (mlir::isa(user) || growsOnly(user)) && + use.getOperandNumber() == 0 && !reachableAfter(read, user, builder); }); } @@ -565,7 +565,8 @@ namespace own_inference }); } - return mlir::isa(user) && use.getOperandNumber() == 0; + return (mlir::isa(user) || growsOnly(user)) && + use.getOperandNumber() == 0; }); } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index f450e4a06..ee23f98ad 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -916,7 +916,7 @@ namespace own_inference drops.push_back(op); } } - else if (mlir::isa(op)) + else if (mlir::isa(op) || growsOnly(op)) { // through a handle, it may move the elements another handle's borrow reads (spec 23.3) if (reachesSharedValue(op->getOperand(0))) diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp index 3ad16edd1..64b192372 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -436,7 +436,7 @@ namespace own_signature } // `this.values.push(0.0)`: a write of that array field, and of nothing else - if (mlir::isa(refUser) && refUser->getOperand(0) == propertyRefOp.getResult()) + if ((mlir::isa(refUser) || growsOnly(refUser)) && refUser->getOperand(0) == propertyRefOp.getResult()) { stores[propertyRefOp.getPosition()]++; continue; @@ -971,8 +971,8 @@ namespace own_signature } // an array filled in place through the local before the move: `t.push(x)` (TSLANG 72) - if (mlir::isa(user) && + if ((mlir::isa(user) || growsOnly(user)) && !reaches(store, user, slot->getBlock())) { continue; @@ -981,8 +981,8 @@ namespace own_signature // ...and after it, through the place it moved to: `const sets = []; this.frames.push(new // Frame(sets)); for (...) sets.push(set)` (TSLANG 77) if (inPlaceAfter && - mlir::isa(user) && + (mlir::isa(user) || growsOnly(user)) && dominance.properlyDominates(store, user)) { for (auto &operand : user->getOpOperands()) diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 69083e862..4803451f9 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -2239,7 +2239,8 @@ namespace own_signature } } } - else if (mlir::isa(op)) + else if (mlir::isa(op) && + !growsOnly(op)) { if (reachesOutside(op->getOperand(0), funcOp)) { @@ -2256,7 +2257,7 @@ namespace own_signature } } } - else if (mlir::isa(op)) + else if (mlir::isa(op) || growsOnly(op)) { drops.any |= reachesSharedValue(op->getOperand(0)); } @@ -2466,7 +2467,8 @@ namespace own_signature (slot.getDefiningOp() || (isPlace(slot) && reachesOutside(slot, funcOp)) || isLoadedCell(slot) || (!isPlace(slot) && touchesHandle(op) && !isCountedReadSlot(slot))); } - else if (mlir::isa(op)) + else if (mlir::isa(op) && + !growsOnly(op)) { drops = reachesOutside(op->getOperand(0), funcOp); } @@ -2475,7 +2477,7 @@ namespace own_signature // the caller's borrow of a place it exchanges reads another place's value (spec 42) drops = reachesOutside(swapOp.getFirst(), funcOp) || reachesOutside(swapOp.getSecond(), funcOp); } - else if (mlir::isa(op)) + else if (mlir::isa(op) || growsOnly(op)) { // through a handle, it may move the elements another handle's borrow reads (spec 23.3) drops = reachesSharedValue(op->getOperand(0)); diff --git a/tslang/test/android/android_skips.txt b/tslang/test/android/android_skips.txt index e725aca69..7ec64f74f 100644 --- a/tslang/test/android/android_skips.txt +++ b/tslang/test/android/android_skips.txt @@ -13,4 +13,4 @@ json.ts none # (default library) builds a 100000-character st # refused by design under the model, as in ctest (which registers them under the other models only) 00weak_field.ts rc # '@weak' is not supported under -mm=rc (own spec 93): ctest runs it under gc, none and own 00let_without_initializer_owns.ts own # copies an `any` holding an object, which -mm=own refuses at run time: ctest runs it under gc, rc and none -00array_write_grows.ts own # a[i] = v past the end does not grow the array under -mm=own yet (TSLANG 152): ctest runs it under gc and rc +00generator_yield_in_finally_values.ts own # a string or an object returned through a finally that yields, and a yield* of a Generator, are errors under -mm=own yet (TSLANG 153): ctest runs it under gc and rc diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 5204fc252..725a8d780 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -471,6 +471,10 @@ tslang_add_test(NAME test-compile-00-generator-typed-yield COMMAND test-runner " tslang_add_test(NAME test-compile-00-object-method-arity COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_method_arity.ts") tslang_add_test(NAME test-compile-00-generator-next-value COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_next_value.ts") tslang_add_test(NAME test-compile-00-generator-return-throw COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_return_throw.ts") +tslang_add_test(NAME test-compile-00-iterable-array-copy COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00iterable_array_copy.ts") +tslang_add_test(NAME test-compile-00-generator-next-shared COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_next_shared.ts") +tslang_add_test(NAME test-compile-00-generator-yield-in-finally-values COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally_values.ts") +tslang_add_test(NAME test-compile-00-generator-yield-in-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally.ts") tslang_add_test(NAME test-compile-00-generator-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_finally.ts") tslang_add_test(NAME test-compile-00-generator-symbol-iterator COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_symbol_iterator.ts") tslang_add_test(NAME test-compile-00-generic-shadowed-type-param COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generic_shadowed_type_param.ts") @@ -1317,6 +1321,17 @@ tslang_add_test(NAME test-jit-own-00-generator-next-value COMMAND test-runner -j tslang_add_test(NAME test-jit-00-generator-return-throw COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_return_throw.ts") tslang_add_test(NAME test-jit-rc-00-generator-return-throw COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_return_throw.ts") tslang_add_test(NAME test-jit-own-00-generator-return-throw COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_return_throw.ts") +tslang_add_test(NAME test-jit-00-iterable-array-copy COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00iterable_array_copy.ts") +tslang_add_test(NAME test-jit-rc-00-iterable-array-copy COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00iterable_array_copy.ts") +tslang_add_test(NAME test-jit-own-00-iterable-array-copy COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00iterable_array_copy.ts") +tslang_add_test(NAME test-jit-00-generator-next-shared COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_next_shared.ts") +tslang_add_test(NAME test-jit-rc-00-generator-next-shared COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_next_shared.ts") +tslang_add_test(NAME test-jit-own-00-generator-next-shared COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_next_shared.ts") +tslang_add_test(NAME test-jit-00-generator-yield-in-finally-values COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally_values.ts") +tslang_add_test(NAME test-jit-rc-00-generator-yield-in-finally-values COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally_values.ts") +tslang_add_test(NAME test-jit-00-generator-yield-in-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally.ts") +tslang_add_test(NAME test-jit-rc-00-generator-yield-in-finally COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally.ts") +tslang_add_test(NAME test-jit-own-00-generator-yield-in-finally COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_in_finally.ts") tslang_add_test(NAME test-jit-00-generator-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_finally.ts") tslang_add_test(NAME test-jit-rc-00-generator-finally COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_finally.ts") tslang_add_test(NAME test-jit-own-00-generator-finally COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_finally.ts") @@ -1331,6 +1346,7 @@ tslang_add_test(NAME test-jit-rc-00-any-undefined-field COMMAND test-runner -jit tslang_add_test(NAME test-jit-own-00-any-undefined-field COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_undefined_field.ts") tslang_add_test(NAME test-jit-00-array-write-grows COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_write_grows.ts") tslang_add_test(NAME test-jit-rc-00-array-write-grows COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_write_grows.ts") +tslang_add_test(NAME test-jit-own-00-array-write-grows COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_write_grows.ts") tslang_add_test(NAME test-jit-00-constructor-type-value COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") tslang_add_test(NAME test-jit-rc-00-constructor-type-value COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") tslang_add_test(NAME test-jit-own-00-constructor-type-value COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") @@ -4198,14 +4214,23 @@ set_tests_properties(test-compile-diagnostic-location-generator-yield-in-catch PROPERTIES PASS_REGULAR_EXPRESSION "generator_yield_in_catch\\.ts:8:9: error: a yield in a catch block of a generator is not supported" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") -# A yield in a finally block of a generator is an error at the yield (the yield was skipped, and the rest of the -# finally resumed from the wrong place). -add_test(NAME test-compile-diagnostic-location-generator-yield-in-finally - COMMAND $ --emit=obj --no-default-lib -mm=none - "${PROJECT_SOURCE_DIR}/test/tester/diagnostic-location/generator_yield_in_finally.ts" - -o "${CMAKE_CURRENT_BINARY_DIR}/diagnostic-location-generator-yield-in-finally.obj") -set_tests_properties(test-compile-diagnostic-location-generator-yield-in-finally - PROPERTIES PASS_REGULAR_EXPRESSION "generator_yield_in_finally\\.ts:9:9: error: a yield in a finally block of a generator is not supported" + +# -mm=own: a value that owns memory returned through a finally block that yields is an error at the return. +add_test(NAME test-compile-diagnostic-location-generator-return-through-yielding-finally-own + COMMAND $ --emit=obj --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/diagnostic-location/generator_return_through_yielding_finally_own.ts" + -o "${CMAKE_CURRENT_BINARY_DIR}/diagnostic-location-generator-return-through-yielding-finally-own.obj") +set_tests_properties(test-compile-diagnostic-location-generator-return-through-yielding-finally-own + PROPERTIES PASS_REGULAR_EXPRESSION "generator_return_through_yielding_finally_own\\.ts:6:9: error: -mm=own: a value of type 'string' returned through a finally block that yields is not supported yet" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") + +# -mm=own: an object sent by next() is an error at the yield that reads it, pointing at Shared. +add_test(NAME test-compile-diagnostic-location-generator-next-object-own + COMMAND $ --emit=obj --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/diagnostic-location/generator_next_object_own.ts" + -o "${CMAKE_CURRENT_BINARY_DIR}/diagnostic-location-generator-next-object-own.obj") +set_tests_properties(test-compile-diagnostic-location-generator-next-object-own + PROPERTIES PASS_REGULAR_EXPRESSION "generator_next_object_own\\.ts:12:19: error: -mm=own: a value of type 'Box' sent by next\\(\\) is kept by the generator" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # A generic method in a type literal is an error at the method. diff --git a/tslang/test/tester/diagnostic-location/generator_next_object_own.ts b/tslang/test/tester/diagnostic-location/generator_next_object_own.ts new file mode 100644 index 000000000..1c4d0982f --- /dev/null +++ b/tslang/test/tester/diagnostic-location/generator_next_object_own.ts @@ -0,0 +1,20 @@ +// -mm=own: an object sent by next() is kept by the generator, whose callers (through the Generator interface) +// can't be made to give it up: an error at the yield that reads it, pointing at Shared. +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; +} +class Box { constructor(public n: number) {} } + +function* summer(): Generator { + let total = 0; + while (true) { + const b = yield total; + if (b) total += b.n; + } +} + +function main() { + const g = summer(); + g.next(new Box(1)); +} diff --git a/tslang/test/tester/diagnostic-location/generator_return_through_yielding_finally_own.ts b/tslang/test/tester/diagnostic-location/generator_return_through_yielding_finally_own.ts new file mode 100644 index 000000000..0db83bd03 --- /dev/null +++ b/tslang/test/tester/diagnostic-location/generator_return_through_yielding_finally_own.ts @@ -0,0 +1,14 @@ +// -mm=own: a value that owns memory returned through a finally block that yields is an error at the return (the +// value kept for after the finally is a field of the generator, and the return would hand out a borrow of it). +function* g(n: number) { + try { + yield "1"; + return "r" + n; + } finally { + yield "2"; + } +} + +function main() { + for (const v of g(1)) print(v); +} diff --git a/tslang/test/tester/diagnostic-location/generator_yield_in_finally.ts b/tslang/test/tester/diagnostic-location/generator_yield_in_finally.ts deleted file mode 100644 index 1f10a3596..000000000 --- a/tslang/test/tester/diagnostic-location/generator_yield_in_finally.ts +++ /dev/null @@ -1,15 +0,0 @@ -// A yield in a finally block of a generator is an error at the yield: the finally is copied for each way out of -// the try (one of them inside an exception handler) and a resume landed in one copy only - the yield was skipped -// and the rest of the finally ran from the wrong place. -function* g() { - try { - yield 1; - } finally { - print("in finally"); - yield 2; - } -} - -function main() { - for (const v of g()) print(v); -} diff --git a/tslang/test/tester/tests/00array_write_grows.ts b/tslang/test/tester/tests/00array_write_grows.ts index 9313e626b..2481d7356 100644 --- a/tslang/test/tester/tests/00array_write_grows.ts +++ b/tslang/test/tester/tests/00array_write_grows.ts @@ -1,7 +1,7 @@ // `a[i] = v` with `i` at or past the end of the array grows it to `i + 1`, as in JavaScript // (`a[a.length] = v` appends); the slots in between read as the element type's default. Before, the // length stayed and the write went past the end of the block: under gc into whatever lay there, under -// rc and own a crash. (Not under -mm=own yet: TSLANG 152.) +// rc and own a crash. class Item { constructor(public n: number) {} } @@ -10,6 +10,15 @@ class Holder { items: Item[] = []; } +// through a parameter's array, and a field's of a parameter +function append(src: number[], n: number) { + for (let i = 0; i < n; i++) src[src.length] = i; +} + +function addTo(h: Holder, n: number) { + h.items[h.items.length] = new Item(n); +} + function main() { const a: number[] = [1, 2]; a[a.length] = 3; @@ -32,9 +41,22 @@ function main() { for (const item of h.items) total += item.n; assert(h.items.length == 50 && total == 1225, "objects in a field"); + append(a, 2); + assert(a.length == 9 && a[8] == 1, "a parameter's array"); + addTo(h, 99); + assert(h.items.length == 51 && h.items[50].n == 99, "a parameter's field"); + + // an array of arrays, each grown + const m: string[][] = []; + for (let i = 0; i < 3; i++) { + m[i] = []; + for (let j = 0; j < 3; j++) m[i][j] = "c" + i + j; + } + assert(m.length == 3 && m[2].length == 3 && m[2][2] == "c22", "nested"); + // within the length: no change a[0] = 10; - assert(a.length == 7 && a[0] == 10, "inside"); + assert(a.length == 9 && a[0] == 10, "inside"); print("done."); } diff --git a/tslang/test/tester/tests/00generator_finally.ts b/tslang/test/tester/tests/00generator_finally.ts index d3a35e664..2c6aa52a9 100644 --- a/tslang/test/tester/tests/00generator_finally.ts +++ b/tslang/test/tester/tests/00generator_finally.ts @@ -1,5 +1,5 @@ // A generator's try/finally around its yields: the finally runs once, after the last turn in the try, before what -// follows. A yield in the finally itself is an error (diagnostic-location/generator_yield_in_finally.ts); a +// follows. A yield in the finally itself: 00generator_yield_in_finally.ts. A // generator declared in a finally block is a function of its own and may yield. let log = ""; diff --git a/tslang/test/tester/tests/00generator_next_shared.ts b/tslang/test/tester/tests/00generator_next_shared.ts new file mode 100644 index 000000000..d48eb6cae --- /dev/null +++ b/tslang/test/tester/tests/00generator_next_shared.ts @@ -0,0 +1,25 @@ +// next(value) of a Generator sending objects: under -mm=own the generator keeps what it is sent, +// so TNext is a Shared there (one of another type is an error that says so: +// diagnostic-location/generator_next_object_own.ts); in the other models the same program runs as it is. +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; +} +class Box { constructor(public n: number) {} } + +function* summer(): Generator> { + let total = 0; + while (true) { + const b = yield total; + if (b) total += b.value.n; + } +} + +function main() { + const g = summer(); + g.next(); + g.next(new Shared(new Box(2))); + const r = g.next(new Shared(new Box(3))); + assert(r.value == 5); + print("done."); +} diff --git a/tslang/test/tester/tests/00generator_yield_in_finally.ts b/tslang/test/tester/tests/00generator_yield_in_finally.ts new file mode 100644 index 000000000..25bb103ac --- /dev/null +++ b/tslang/test/tester/tests/00generator_yield_in_finally.ts @@ -0,0 +1,88 @@ +// A yield in a finally block of a generator, as in JavaScript: the finally runs once on each way out of the try - +// its end, a throw, a `return` (from the try or the catch clause), a `break` or `continue` out of it, return() and +// throw() - and pauses the generator at its yields; then the way out is taken: the value returned, the exception +// thrown on, the jump made. return(v) while the generator is paused in the try gives what the finally yields, and v +// when it is done. The expected results are node's for the same JavaScript. Before, the finally was copied for each +// way out and a resume landed in one copy only: its yield was skipped, and the rest of it ran from the wrong place +// (then an error). Also: a `let` of a nested block hiding one around it in a generator shared its variable. +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; + return: (value: T) => IterateResult; + throw: (e: any) => IterateResult; +} + +let log = ""; + +function* g1(): Generator { try { yield 1; } finally { log += "f1,"; yield 2; log += "f1b,"; } yield 3; } +function* g2(): Generator { try { yield 1; return 5; } finally { yield 2; } } +function* g3(): Generator { try { yield 1; throw "e3"; } finally { yield 2; } } +function* g4(): Generator { try { yield 1; throw "e4"; } catch (e) { log += "c:" + e + ","; return 6; } finally { yield 2; } } +function* g5(): Generator { for (let i = 0; i < 3; i++) { try { if (i == 1) continue; if (i == 2) break; yield i; } finally { yield 10 + i; } } yield 99; } +function* g6(): Generator { try { try { yield 1; return 7; } finally { yield 2; } } finally { yield 3; } } +function* g7(): Generator { let x = 1; try { let x = 2; yield x; return x; } finally { yield x; } } +function* g8(): Generator { try { yield 1; } finally { yield 2; throw "e8"; } } + +function* untyped() { try { yield 1; return 2; } finally { yield 3; } } +class C { + k = 10; + *gen() { try { yield this.k; return this.k + 1; } finally { yield this.k + 2; } } +} +// a function in the try returns from itself, not through the finally +function* closure() { try { const f = () => { return 5; }; yield f(); } finally { yield 6; } } + +function show(r: IterateResult) { + return r.done ? (r.value === undefined ? "D" : "D" + r.value) : "" + r.value; +} + +function run(it: Generator) { + let s = ""; + try { + for (;;) { + const r = it.next(); + s += show(r) + " "; + if (r.done) break; + } + } catch (e) { + s += "throw:" + e; + } + return s; +} + +function main() { + assert(run(g1()) == "1 2 3 D0 " && log == "f1,f1b,", "end of the try"); + assert(run(g2()) == "1 2 D5 ", "return through it"); + assert(run(g3()) == "1 2 throw:e3", "throw through it"); + assert(run(g4()) == "1 2 D6 " && log == "f1,f1b,c:e4,", "return from the catch clause"); + assert(run(g5()) == "0 10 11 12 99 D0 ", "continue and break through it"); + assert(run(g6()) == "1 2 3 D7 ", "nested"); + assert(run(g7()) == "2 1 D2 ", "the finally reads the outer x"); + assert(run(g8()) == "1 2 throw:e8", "a throw after the finally's yield"); + { + const it = g1(); it.next(); + assert(show(it.return(9)) == "2" && show(it.next()) == "D9" && show(it.next()) == "D0", "return() in the try"); + } + { + const it = g1(); it.next(); it.next(); + assert(show(it.return(9)) == "D9" && show(it.next()) == "D0", "return() in the finally"); + } + { + const it = g1(); it.next(); + let a = ""; try { a = show(it.throw("t")); } catch (e) { a = "throw:" + e; } + let b = ""; try { b = show(it.next()); } catch (e) { b = "throw:" + e; } + assert(a == "2" && b == "throw:t", "throw() in the try"); + } + let u = ""; + for (const v of untyped()) u += v; + assert(u == "13", "for...of an untyped generator"); + + let c = ""; + for (const it = new C().gen(); ;) { const r = it.next(); c += (r.done ? "D" : "") + r.value + " "; if (r.done) break; } + assert(c == "10 12 D11 ", "a generator method of a class"); + + let cl = ""; + for (const v of closure()) cl += v; + assert(cl == "56", "a function in the try"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00generator_yield_in_finally_values.ts b/tslang/test/tester/tests/00generator_yield_in_finally_values.ts new file mode 100644 index 000000000..ef736e774 --- /dev/null +++ b/tslang/test/tester/tests/00generator_yield_in_finally_values.ts @@ -0,0 +1,36 @@ +// A yield in a finally block of a generator, with values that live on the heap: a string or an object returned +// through it (kept for after the finally), and return() while the generator is paused in a yield* (it finishes +// through the finally, as in JavaScript - the delegate is left where it is). The results are node's for the same +// JavaScript. Not under -mm=own: a value that owns memory returned through such a finally is an error there yet +// (diagnostic-location/generator_return_through_yielding_finally_own.ts), and so is a yield* of a Generator. +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; + return: (value: T) => IterateResult; + throw: (e: any) => IterateResult; +} +class Item { constructor(public n: number) {} } + +function* strRet(n: number) { try { yield "1"; return "r" + n; } finally { yield "2"; } } +function* objRet(n: number) { try { yield new Item(1); return new Item(n); } finally { yield new Item(2); } } +function* inner(): Generator { try { yield 1; yield 2; } finally { } } +function* outer(): Generator { try { yield* inner(); } finally { yield 9; } } + +function main() { + for (let round = 0; round < 200; round++) { + let s = ""; + for (const it = strRet(3); ;) { const r = it.next(); s += (r.done ? "D" : "") + r.value + " "; if (r.done) break; } + assert(s == "1 2 Dr3 ", "a string returned through it"); + + let o = ""; + for (const it = objRet(4); ;) { const r = it.next(); o += (r.done ? "D" : "") + r.value.n + " "; if (r.done) break; } + assert(o == "1 2 D4 ", "an object returned through it"); + } + + const it = outer(); + it.next(); + const a = it.return(7); + const b = it.next(); + assert(a.value == 9 && !a.done && b.value == 7 && b.done, "return() in a yield*"); + print("done."); +} diff --git a/tslang/test/tester/tests/00iterable_array_copy.ts b/tslang/test/tester/tests/00iterable_array_copy.ts new file mode 100644 index 000000000..9a81c3f36 --- /dev/null +++ b/tslang/test/tester/tests/00iterable_array_copy.ts @@ -0,0 +1,30 @@ +// An array given where an iterator interface is wanted (`sum(a)` of `sum(v: Iterable)`): a generator over +// its elements. Under -mm=own it iterates a copy of the array, which it owns (USER DECISION 2026-11-21): one +// borrowing the array would hold the borrow for as long as it lives, which -mm=own can't say - it was "a value takes +// a second reference". The other models iterate the array itself. (-mm=own: a for...of over such an interface of +// strings is still refused, and an array of objects can't be copied there.) +type IterateResult = { value: T, done: boolean }; +interface Iterable { + next: () => IterateResult; +} + +function sum(v: Iterable) { + let s = 0.0; + for (const x of v) { + s += x; + } + + return s; +} + +function main() { + for (let round = 0; round < 1000; round++) { + assert(sum([1.5, 2]) == 3.5); + const a: number[] = [1, 2, 3]; + assert(sum(a) == 6 && a.length == 3); + const b = [4, 5]; + assert(sum(b) == 9); + } + + print("done."); +} diff --git a/tslang/test/tester/tests/00iterables.ts b/tslang/test/tester/tests/00iterables.ts index 52ff884ea..ef482cc9e 100644 --- a/tslang/test/tester/tests/00iterables.ts +++ b/tslang/test/tester/tests/00iterables.ts @@ -1,7 +1,7 @@ // An array or a string given where an iterator interface is wanted (`Iterable`: an object with `next`, as the // default library declares it) was "type 'number[]' can't be cast to interface 'Iterable': it has none of // the interface's members". A generator over its elements is given; an `s32[]` given to an `Iterable` is -// converted first. (-mm=own: a generator typed as an interface other than the library's is still refused.) +// converted first. (-mm=own: 00iterable_array_copy.ts.) // as the default library declares them (the tests compile without it) type IterateResult = { value: T, done: boolean }; interface Iterable { diff --git a/tslang/test/tester/tests/00object_dictionary.ts b/tslang/test/tester/tests/00object_dictionary.ts index 2114a4551..f4e695a71 100644 --- a/tslang/test/tester/tests/00object_dictionary.ts +++ b/tslang/test/tester/tests/00object_dictionary.ts @@ -109,6 +109,10 @@ interface Table { [key: string]: T; } +// ...and one extending it, adding nothing +interface MoreCounts extends Counts {} +interface Rows extends Table {} + function total(c: Counts) { let sum: number = 0; for (const k in c) sum += c[k] ?? 0; @@ -167,5 +171,18 @@ function main() { names[key] = "v1"; assert(names["k1"] == "v1" && names["k2"] === undefined, "a generic one"); + // a spread of a dictionary: of the same values (the library's objectDictionaryAssign), and of others, each value + // cast (it was "the values' types have to be the same") + const same: Counts = { ...counts, d: 4 }; + assert(total(same) == 10, "a spread of the same values"); + const ints: { [k: string]: int } = { p: 1, q: 2 }; + const widened: Counts = { ...ints, r: 3.5 }; + assert(widened["p"] == 1 && total(widened) == 6.5 && Object.keys(widened).length == 3, "a spread of other values"); + + const more: MoreCounts = { m: 5 }; + const rows: Rows = {}; + rows["r" + 1] = true; + assert(total(more) == 5 && rows["r1"] === true, "an interface extending one"); + print("done."); } diff --git a/tslang/test/wasm/wasm_skips.txt b/tslang/test/wasm/wasm_skips.txt index a687ed434..9eb1e83b4 100644 --- a/tslang/test/wasm/wasm_skips.txt +++ b/tslang/test/wasm/wasm_skips.txt @@ -17,4 +17,4 @@ json.ts none # (default library) builds a 100000-character st 01tuple.ts own # frees a block it does not own (native own: the program does not finish either) 00global_interface_initializer.ts own # asserts "a field read" (native own: the same assert) 00let_without_initializer_owns.ts own # copies an `any` holding an object, which -mm=own refuses at run time by design (native own: the same assert) -00array_write_grows.ts own # a[i] = v past the end does not grow the array under -mm=own yet (TSLANG 152): the write goes past the block +00generator_yield_in_finally_values.ts own # a string or an object returned through a finally that yields, and a yield* of a Generator, are errors under -mm=own yet (TSLANG 153)