diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 3a9de8b42..d0801a073 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3114,3 +3114,25 @@ this.objs) yield o.n`, 182's leftover) stays refused, with its error. USER RULIN out of the array (which would empty it, unlike JavaScript). Tests diagnostic-location `generator_override_throwing_object_through_yielding_finally_own.ts`. + +186 (2026-11-24). Fixed: +- `arguments.length` of `h(1, undefined)` for `h(a, b?)` was 1 (JavaScript says 2, 114/183): the function can't tell + an `undefined` given from a parameter left out. A function declaration whose body reads `arguments` and has optional + parameters (not a method, not generic, not exported, no rest parameter) takes a parameter of its own after the + others, `.argc` (ARGUMENT_COUNT_NAME, mlirGenParameters), and a call by its name gives it the count of its + arguments (mlirGenCall); the length is that count, no more than the parameters (the arguments past them are not + passed). Called as a function value it is left out, and the length is worked out from the parameters as before. +- An optional value given to an `any` (`const x: any = b` of a `b?: string`): one holding nothing was boxed as the + type's value with no text, which crashed where it was read (`"" + x`); it is boxed as undefined now, and one holding + a value as that value (as an optional `any` was). +- A `yield*` over a generator whose type has throw() but not return(): the delegate was not held, so a throw() of the + generator was not handed to it. It is held for its throw(), and no return() is called that the type does not have. +- -mm=own: `yield* it` of a generator a parameter holds hands a throw() to the delegate's throw() as well (184 did a + delegate made there), for elements that own nothing. + +Looked at, still open: +- `arguments` of a method, a generic function or one called as a function value: the length is worked out from the + parameters, as before (an `undefined` given counts as left out). + +Tests `00arguments_length_given.ts` (cases added), `00generator_yield_star_throw_only.ts` and +`00generator_yield_star_throw_param.ts` (gc, rc, own). diff --git a/docs/whats-new.md b/docs/whats-new.md index 5b43fb5b7..39770e416 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,6 @@ # What's new +- `arguments.length` counts an `undefined` given (`h(1, undefined)` is 2) in a call by name; an optional value given to an `any` that holds nothing is `undefined`; a `yield*` hands throw() to a delegate typed with `throw` but no `return`, and under -mm=own to one a parameter holds - -mm=own: a method whose override throws an object, called through the base class in a `try` whose `finally` yields, is a compile error at the call, not a stop at run time - A function with parameters of different types can be given to `(...args: A) => T` (`A` is inferred as a tuple, `[number, string]`); under -mm=own, throw() of a generator paused in a `yield*` of numbers is handed to the delegate too - `arguments.length` counts the arguments given, not the parameters declared; a generic arrow can be given to a generic parameter (`wrap((x: T) => x)`), and a function to `(...args: A) => T`; throw() of a generator paused in a `yield*` is handed to the delegate's throw(), which may catch it and go on yielding diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 7abfaa675..ad1ea0d8c 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -237,6 +237,8 @@ #define INFINITY_NAME "Infinity" #define NAN_NAME "NaN" #define THIS_NAME "this" +// the parameter a function that reads `arguments` is given the count of its arguments in (TSLANG 186) +#define ARGUMENT_COUNT_NAME ".argc" #define SUPER_NAME "super" #define STATIC_NAME "static" #define STATIC_CONSTRUCTOR_NAME "static_constructor" diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index 3beca6243..8610ce2ed 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -392,6 +392,8 @@ struct GenContext // variable its result goes to, in place of the delegate's next(), and the flag that says next() is not called const char *yieldStarResult = nullptr; const char *yieldStarSkipNext = nullptr; + // ...and whether that delegate has `return` (one with `throw` only is held for its throw(), TSLANG 186) + bool yieldStarHasReturn = true; // 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/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 57ac736ac..8a7c66cce 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -3148,6 +3148,35 @@ namespace mlirgen // through its virtual table: the method of the class the call names) auto *calleeOp = funcRefValue.getDefiningOp(); auto calleeName = calleeOp ? calleeOp->getAttrOfType("identifier") : mlir::FlatSymbolRefAttr(); + + // a function that reads `arguments` called by its name: given the count of the arguments, `undefined` for + // the parameters left out before it (mlirGenParameters, TSLANG 186). More arguments than parameters are put + // after it, refused as before. + if (auto symbolRefOp = mlir::dyn_cast_or_null(calleeOp)) + { + auto counting = functionsCountingArguments.find(symbolRefOp.getIdentifier()); + if (counting != functionsCountingArguments.end()) + { + auto countPosition = counting->second; + auto given = operands.size(); + auto countValue = builder.create(location, builder.getI32Type(), + builder.getI32IntegerAttr((int)given)); + CAST_A(count, location, getNumberType(), countValue, genContext); + if (given <= countPosition) + { + while (operands.size() < countPosition) + { + operands.push_back(builder.create(location, getUndefinedType())); + } + + operands.push_back(count); + } + else + { + operands.insert(operands.begin() + countPosition, count); + } + } + } if (compileOptions.memoryModel == MemoryModelOwn && calleeName && mlir::isa(calleeOp)) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 606cf2377..0ab51d502 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -1083,16 +1083,24 @@ namespace mlirgen } // `any | undefined` (an optional `any` field, `{ baz?: any }`) is the `any` it holds, or undefined boxed: - // boxed whole it had no `typeof` name, and lowering made a box with no tag + // boxed whole it had no `typeof` name, and lowering made a box with no tag. So is any other optional + // (`b?: string` given to an `any`, TSLANG 186): the value it holds boxed, or undefined - boxed whole, one + // holding nothing was a string with no text, which crashed where it was read if (isa(type)) { - if (auto optType = dyn_cast(valueType); optType && isa(optType.getElementType())) + if (auto optType = dyn_cast(valueType)) { auto hasValue = builder.create(location, getBooleanType(), value); auto ifOp = builder.create(location, type, hasValue, true); builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); - builder.create(location, mlir::ValueRange{builder.create(location, type, value)}); + mlir::Value held = builder.create(location, optType.getElementType(), value); + if (!isa(held.getType())) + { + CAST(held, location, type, held, genContext); + } + + builder.create(location, mlir::ValueRange{held}); builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); auto undefinedValue = builder.create(location, getUndefinedType()); diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index c64cd990c..7612d9fcd 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -4047,6 +4047,8 @@ namespace mlirgen // `h(1)` of `h(a, b?)` gave one argument, not two (TSLANG 114, 183) SmallVector givenOptional; auto anyOptional = false; + // the count a call by the function's name gives (ARGUMENT_COUNT_NAME, TSLANG 186) + mlir::Value givenCount; for (auto ¶m : genContext.bodyFuncProto->getParams()) { // a method's object is not one of its arguments @@ -4055,6 +4057,14 @@ namespace mlirgen continue; } + if (param->getName() == ARGUMENT_COUNT_NAME) + { + auto result = mlirGen(location, param->getName(), genContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + givenCount = V(result); + continue; + } + // a destructured parameter is the argument under the name the compiler gave it; a rest parameter's // elements are the arguments after the others (TSLANG 114) auto result = mlirGen(location, param->getName(), genContext); @@ -4127,8 +4137,8 @@ namespace mlirgen mlirGenRetainCaptured(location, values); argumentsArray = builder.create(location, getArrayType(getAnyType()), values); - // as many as the caller gave: up to the last parameter given (an optional one given `undefined` is given, - // `h(1, undefined)`, as JavaScript counts it); the ones after it are left out + // as many as the caller gave: up to the last parameter given; the ones after it are left out (an optional + // one given `undefined` looks left out here: the count a call by name gives, below, counts it) if (anyOptional) { auto i32Type = builder.getI32Type(); @@ -4153,6 +4163,34 @@ namespace mlirgen count = ifOp.getResult(0); } + // ...unless the caller said how many it gave (a call by the function's name): an `undefined` given + // is given (`h(1, undefined)` is 2), and more than the parameters are as many as they are + if (givenCount && isa(givenCount.getType())) + { + auto hasCount = builder.create(location, getBooleanType(), givenCount); + auto ifOp = builder.create(location, mlir::TypeRange{i32Type}, hasCount, true); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto countNumber = builder.create(location, getNumberType(), givenCount); + auto parameterCount = builder.create( + location, i32Type, builder.getI32IntegerAttr((int)givenOptional.size())); + CAST_A(parameterNumber, location, getNumberType(), parameterCount, genContext); + // (no more than the array holds: the arguments past the parameters are not passed) + auto fewer = mlirGenBinaryValues(location, SyntaxKind::LessThanToken, countNumber, parameterNumber, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(fewer) + auto pickOp = builder.create(location, mlir::TypeRange{getNumberType()}, V(fewer), true); + builder.setInsertionPointToStart(&pickOp.getThenRegion().front()); + builder.create(location, mlir::ValueRange{countNumber}); + builder.setInsertionPointToStart(&pickOp.getElseRegion().front()); + builder.create(location, mlir::ValueRange{parameterNumber}); + builder.setInsertionPointAfter(pickOp); + mlir::Value callerCount = builder.create(location, i32Type, pickOp.getResult(0)); + builder.create(location, mlir::ValueRange{callerCount}); + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + builder.create(location, mlir::ValueRange{count}); + builder.setInsertionPointAfter(ifOp); + count = ifOp.getResult(0); + } + // (set on the array's place: the local below, or a place of its own for a temporary) argumentsCount = builder.create(location, builder.getIndexType(), count); } diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 201134b7c..082439399 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -465,6 +465,35 @@ namespace mlirgen } } + // `arguments.length` counts what the caller gave, and an `undefined` given for an optional parameter is + // given (`h(1, undefined)` of `h(a, b?)` is 2, TSLANG 186): the function can't tell it from one left out. + // So a function declaration whose body reads `arguments` and has optional parameters (not a method, not + // generic, not exported, no rest parameter - its array holds what is given) takes a parameter of its own + // after the others, ARGUMENT_COUNT_NAME, which a call by its name gives the count of its arguments + // (mlirGenCall); a call of it as a function value leaves it out, and the count is worked out as before + // (mlirGenArguments) + if (kind == SyntaxKind::FunctionDeclaration && parametersContextAST.as()->body && + parametersContextAST->typeParameters.size() == 0 && !hasModifier(parametersContextAST, SyntaxKind::ExportKeyword) && + !hasModifier(parametersContextAST, SyntaxKind::DeclareKeyword) && + llvm::none_of(params, [](auto ¶m) { return param->getIsMultiArgsParam(); }) && + llvm::any_of(params, [](auto ¶m) { return param->getIsOptional(); })) + { + auto readsArguments = false; + FilterVisitorSkipFuncsAST argumentsVisitor(SyntaxKind::Identifier, [&](auto identifier) { + if (MLIRHelper::getName(identifier) == "arguments") + { + readsArguments = true; + } + }); + argumentsVisitor.visit(parametersContextAST.as()->body); + + if (readsArguments) + { + params.push_back(std::make_shared(ARGUMENT_COUNT_NAME, getNumberType(), + loc(parametersContextAST), true, false)); + } + } + return {mlir::success(), isGenericTypes, params}; } @@ -1489,21 +1518,11 @@ namespace mlirgen return nf.createBlock(delegateStatements, false).as(); }; - NodeArray throwStatements; - throwStatements.push_back(resetMode()); - if (genContext.yieldStarDelegate && genContext.yieldStarResult && genContext.yieldStarSkipNext && ownDelegate) - { - // -mm=own, the same in the local the delegate is exchanged into (TSLANG 184): - // { ...exchange...; try { if (.yq!.throw) { .yc = .yq!.throw!(this.thrown); .ys = true; } } finally { ... } } - // if (!.ys) throw this.thrown; - auto delegateThrow = [&]() { - return nf.createPropertyAccessExpression(nf.createNonNullExpression(delegateLocal()), nf.createIdentifier(S("throw"))); - }; - auto skipIdent = [&]() { return nf.createIdentifier(stows(std::string(genContext.yieldStarSkipNext))); }; - // what was thrown, exchanged out of the generator's field into a local first: given from the field, the - // delegate's throw() - which keeps what it is given - was taken for a call that may overwrite the field it - // borrows (`let .yt: any = 0; [.yt, this.thrown] = [this.thrown, .yt];`) - auto thrownLocal = [&]() { return nf.createIdentifier(stows(".yt" + std::string(genContext.yieldStarDelegate))); }; + // -mm=own: what was thrown, exchanged out of the generator's field into a local first: given from the field, + // the delegate's throw() - which keeps what it is given - was taken for a call that may overwrite the field it + // borrows (`let .yt: any = 0; [.yt, this.thrown] = [this.thrown, .yt];`) + auto thrownLocal = [&]() { return nf.createIdentifier(stows(".yt" + std::string(genContext.yieldStarDelegate))); }; + auto exchangeThrown = [&](NodeArray &statements) { NodeArray thrownDeclarations; auto thrownDeclaration = nf.createVariableDeclaration( thrownLocal(), undefined, nf.createToken(SyntaxKind::AnyKeyword).as(), @@ -1517,15 +1536,28 @@ namespace mlirgen NodeArray thrownValues; thrownValues.push_back(thisProp(GENERATOR_THROWN_NAME)); thrownValues.push_back(thrownLocal()); + statements.push_back( + nf.createVariableStatement(undefined, nf.createVariableDeclarationList(thrownDeclarations, NodeFlags::Let))); + statements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( + nf.createArrayLiteralExpression(thrownTargets, false), nf.createToken(SyntaxKind::EqualsToken), + nf.createArrayLiteralExpression(thrownValues, false)))); + }; + NodeArray throwStatements; + throwStatements.push_back(resetMode()); + if (genContext.yieldStarDelegate && genContext.yieldStarResult && genContext.yieldStarSkipNext && ownDelegate) + { + // -mm=own, the same in the local the delegate is exchanged into (TSLANG 184): + // { ...exchange...; try { if (.yq!.throw) { .yc = .yq!.throw!(this.thrown); .ys = true; } } finally { ... } } + // if (!.ys) throw this.thrown; + auto delegateThrow = [&]() { + return nf.createPropertyAccessExpression(nf.createNonNullExpression(delegateLocal()), nf.createIdentifier(S("throw"))); + }; + auto skipIdent = [&]() { return nf.createIdentifier(stows(std::string(genContext.yieldStarSkipNext))); }; NodeArray arguments; arguments.push_back(thrownLocal()); NodeArray handStatements; - handStatements.push_back( - nf.createVariableStatement(undefined, nf.createVariableDeclarationList(thrownDeclarations, NodeFlags::Let))); - handStatements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( - nf.createArrayLiteralExpression(thrownTargets, false), nf.createToken(SyntaxKind::EqualsToken), - nf.createArrayLiteralExpression(thrownValues, false)))); + exchangeThrown(handStatements); handStatements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( nf.createIdentifier(stows(std::string(genContext.yieldStarResult))), nf.createToken(SyntaxKind::EqualsToken), nf.createCallExpression(nf.createNonNullExpression(delegateThrow()), undefined, arguments)))); @@ -1546,9 +1578,16 @@ namespace mlirgen return nf.createPropertyAccessExpression(nf.createIdentifier(stows(std::string(genContext.yieldStarDelegate))), nf.createIdentifier(S("throw"))); }; + // (-mm=own - a delegate a parameter names, `yield* it`, TSLANG 186 - with what was thrown in a local, as above) + auto own = compileOptions.memoryModel == MemoryModelOwn; NodeArray arguments; - arguments.push_back(thisProp(GENERATOR_THROWN_NAME)); + arguments.push_back(own ? Expression(thrownLocal()) : Expression(thisProp(GENERATOR_THROWN_NAME))); NodeArray handStatements; + if (own) + { + exchangeThrown(handStatements); + } + handStatements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( nf.createIdentifier(stows(std::string(genContext.yieldStarResult))), nf.createToken(SyntaxKind::EqualsToken), nf.createCallExpression(nf.createNonNullExpression(delegateThrow()), undefined, arguments)))); @@ -1569,7 +1608,8 @@ namespace mlirgen NodeArray returnStatements; returnStatements.push_back(resetMode()); // at the yield of a yield*: the delegate's return() first, with the same value (mlirGenYieldStar) - if (ownDelegate) + // (a delegate held for its throw() only has no return() to call, TSLANG 186) + if (ownDelegate && genContext.yieldStarHasReturn) { // -mm=own: in the local the delegate is exchanged into, `.yq!.return?.(this.thrown)` NodeArray arguments; @@ -1580,7 +1620,7 @@ namespace mlirgen nf.createToken(SyntaxKind::QuestionDotToken), undefined, arguments))); returnStatements.push_back(withDelegateLocal(callStatements)); } - else if (genContext.yieldStarDelegate) + else if (genContext.yieldStarDelegate && genContext.yieldStarHasReturn) { NodeArray arguments; arguments.push_back(thisProp(GENERATOR_THROWN_NAME)); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 86a948cb6..3e67a3408 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -322,6 +322,8 @@ class MLIRGenImpl void renameNamespaceBlockLocals(ModuleBlock block, StringRef namespaceFullName); // "|" -> the block of the namespace that declared the name, not exported, first llvm::StringMap namespaceBlockNames; + // the functions given the count of their arguments -> the position of ARGUMENT_COUNT_NAME (TSLANG 186) + llvm::StringMap functionsCountingArguments; // -mm=own: the functions that throw an object out of themselves -> its type (mlirGen(ThrowStatement)) llvm::StringMap functionsThrowingObjects; // -mm=own: function -> the functions it calls outside a catch clause of its own @@ -4377,6 +4379,12 @@ class MLIRGenImpl return std::make_tuple(FunctionPrototypeDOM::TypePtr(nullptr), funcType, SmallVector{}); } + // a call by the function's name gives it the count of its arguments (mlirGenParameters, mlirGenCall) + if (!params.empty() && params.back()->getName() == ARGUMENT_COUNT_NAME) + { + functionsCountingArguments[fullName] = params.size() - 1; + } + SmallVector argTypes; auto isMultiArgs = false; @@ -5378,8 +5386,12 @@ class MLIRGenImpl if (auto delegateInterface = dyn_cast_or_null(delegateType)) { auto delegateInfo = getInterfaceInfoByFullName(delegateInterface.getName().getValue()); - if (delegateInfo && (delegateInfo->findField(builder.getStringAttr("return")) || - delegateInfo->findMethod("return"))) + // (one with `throw` and no `return` too, for its throw(), TSLANG 186) + auto hasReturn = delegateInfo && (delegateInfo->findField(builder.getStringAttr("return")) || + delegateInfo->findMethod("return")); + auto hasThrow = delegateInfo && (delegateInfo->findField(builder.getStringAttr("throw")) || + delegateInfo->findMethod("throw")); + if (hasReturn || hasThrow) { auto delegateIdent = nf.createIdentifier(S(".yd")); NodeArray delegateDeclarations; @@ -5391,6 +5403,7 @@ class MLIRGenImpl GenContext delegateGenContext(genContext); delegateGenContext.yieldStarDelegate = ".yd"; + delegateGenContext.yieldStarHasReturn = hasReturn; // ...and one that has `throw` too: a throw() of this generator at that yield is handed to it // (TSLANG 183) - it may catch the exception and go on yielding, or finish - so the loop calls @@ -5398,7 +5411,7 @@ class MLIRGenImpl // let .yc = .yd.next(); // while (!.yc.done) { let .ys = false; yield .yc.value; if (!.ys) .yc = .yd.next(); } // (the resume check: `.yc = .yd.throw!(this.thrown); .ys = true;`, mlirGenGeneratorResumeChecks) - if (delegateInfo->findField(builder.getStringAttr("throw")) || delegateInfo->findMethod("throw")) + if (hasThrow) { auto resultIdent = nf.createIdentifier(S(".yc")); auto skipIdent = nf.createIdentifier(S(".ys")); @@ -5489,12 +5502,28 @@ class MLIRGenImpl auto site = std::to_string(static_cast(yieldExpressionAST->pos)); auto resultIdent = nf.createIdentifier(stows(".yc" + site)); auto delegateName = MLIRHelper::getName(delegateExpression.as()); - // a return() of this generator calls the delegate's return() first, when it has one + // a return() of this generator calls the delegate's return() first, when it has one; a throw() is + // handed to its throw() (TSLANG 186, 184 for a delegate made there), for elements that own nothing: + // the resume check puts its result in `.yc` and sets `.ys`, and the step's next() is then not called auto delegateInfo = getInterfaceInfoByFullName(delegateInterface.getName().getValue()); - if (!!(_yield_expr->internalFlags & InternalFlags::GeneratorResumable) && delegateInfo && - (delegateInfo->findField(builder.getStringAttr("return")) || delegateInfo->findMethod("return"))) + auto resumable = !!(_yield_expr->internalFlags & InternalFlags::GeneratorResumable); + auto hasReturn = delegateInfo && (delegateInfo->findField(builder.getStringAttr("return")) || + delegateInfo->findMethod("return")); + auto handsThrow = resumable && delegateInfo && + (delegateInfo->findField(builder.getStringAttr("throw")) || delegateInfo->findMethod("throw")) && + !mth.ownsHeapMemory(loc(yieldExpressionAST), iteratorElementType(delegateInterface)); + auto resultName = ".yc" + site; + auto skipName = ".ys" + site; + if (resumable && (hasReturn || handsThrow)) { delegateGenContext.yieldStarDelegate = delegateName.c_str(); + delegateGenContext.yieldStarHasReturn = hasReturn; + } + + if (handsThrow) + { + delegateGenContext.yieldStarResult = resultName.c_str(); + delegateGenContext.yieldStarSkipNext = skipName.c_str(); } auto nextCall = [&]() { @@ -5512,13 +5541,34 @@ class MLIRGenImpl NodeArray loopStatements; loopStatements.push_back( nf.createVariableStatement(undefined, nf.createVariableDeclarationList(valueDeclarations, NodeFlags::Const))); - loopStatements.push_back(nf.createExpressionStatement(_yield_expr)); + + auto nextStep = [&]() { + return nf.createBinaryExpression(resultIdent, nf.createToken(SyntaxKind::EqualsToken), nextCall()); + }; + if (handsThrow) + { + // `let .ys = false; yield .v; if (!.ys) .yc = it.next();` + auto skipIdent = nf.createIdentifier(stows(skipName)); + NodeArray skipDeclarations; + skipDeclarations.push_back( + nf.createVariableDeclaration(skipIdent, undefined, undefined, nf.createToken(SyntaxKind::FalseKeyword))); + loopStatements.push_back( + nf.createVariableStatement(undefined, nf.createVariableDeclarationList(skipDeclarations, NodeFlags::Let))); + loopStatements.push_back(nf.createExpressionStatement(_yield_expr)); + loopStatements.push_back(nf.createIfStatement( + nf.createPrefixUnaryExpression(nf.createToken(SyntaxKind::ExclamationToken), skipIdent), + nf.createExpressionStatement(nextStep()), undefined)); + } + else + { + loopStatements.push_back(nf.createExpressionStatement(_yield_expr)); + } auto loop = nf.createForStatement( nf.createVariableDeclarationList(resultDeclarations, NodeFlags::Let), nf.createPrefixUnaryExpression(nf.createToken(SyntaxKind::ExclamationToken), nf.createPropertyAccessExpression(resultIdent, nf.createIdentifier(S("done")))), - nf.createBinaryExpression(resultIdent, nf.createToken(SyntaxKind::EqualsToken), nextCall()), + handsThrow ? Expression() : Expression(nextStep()), nf.createBlock(loopStatements, false)); return mlirGen(loop, delegateGenContext); } @@ -5571,12 +5621,17 @@ class MLIRGenImpl auto delegateIdent = nf.createIdentifier(stows(delegateName)); auto resultIdent = nf.createIdentifier(stows(".yc" + site)); // ...and a return() of this generator calls the delegate's return() first, when it has one - // (mlirGenGeneratorResumeChecks) + // (mlirGenGeneratorResumeChecks) - and one with `throw` only is held for its throw() (TSLANG 186) auto delegateInfo = getInterfaceInfoByFullName(delegateInterface.getName().getValue()); - if (!!(_yield_expr->internalFlags & InternalFlags::GeneratorResumable) && delegateInfo && - (delegateInfo->findField(builder.getStringAttr("return")) || delegateInfo->findMethod("return"))) + auto hasReturn = delegateInfo && (delegateInfo->findField(builder.getStringAttr("return")) || + delegateInfo->findMethod("return")); + auto hasThrow = delegateInfo && (delegateInfo->findField(builder.getStringAttr("throw")) || + delegateInfo->findMethod("throw")); + if (!!(_yield_expr->internalFlags & InternalFlags::GeneratorResumable) && + (hasReturn || (hasThrow && !mth.ownsHeapMemory(loc(yieldExpressionAST), elementType)))) { delegateGenContext.yieldStarDelegate = delegateName.c_str(); + delegateGenContext.yieldStarHasReturn = hasReturn; } // ...and a throw() of it is handed to the delegate's throw(), when it has one (TSLANG 184, as 183 for @@ -5589,7 +5644,7 @@ class MLIRGenImpl auto resultName = ".yc" + site; auto skipIdent = nf.createIdentifier(stows(skipName)); auto handsThrow = delegateGenContext.yieldStarDelegate && !mth.ownsHeapMemory(loc(yieldExpressionAST), elementType) && - (delegateInfo->findField(builder.getStringAttr("throw")) || delegateInfo->findMethod("throw")); + hasThrow; if (handsThrow) { delegateGenContext.yieldStarResult = resultName.c_str(); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index e3d36e7a3..0cc9026a1 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1424,6 +1424,16 @@ tslang_add_test(NAME test-jit-rc-00-generator-yield-star-throw COMMAND test-runn tslang_add_test(NAME test-compile-00-generator-yield-star-throw COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw.ts") tslang_add_test(NAME test-jit-own-00-generator-yield-star-throw COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw.ts") tslang_add_test(NAME test-compile-own-00-generator-yield-star-throw COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw.ts") +tslang_add_test(NAME test-jit-00-generator-yield-star-throw-only COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_only.ts") +tslang_add_test(NAME test-jit-rc-00-generator-yield-star-throw-only COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_only.ts") +tslang_add_test(NAME test-jit-own-00-generator-yield-star-throw-only COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_only.ts") +tslang_add_test(NAME test-compile-00-generator-yield-star-throw-only COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_only.ts") +tslang_add_test(NAME test-compile-own-00-generator-yield-star-throw-only COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_only.ts") +tslang_add_test(NAME test-jit-00-generator-yield-star-throw-param COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_param.ts") +tslang_add_test(NAME test-jit-rc-00-generator-yield-star-throw-param COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_param.ts") +tslang_add_test(NAME test-jit-own-00-generator-yield-star-throw-param COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_param.ts") +tslang_add_test(NAME test-compile-00-generator-yield-star-throw-param COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_param.ts") +tslang_add_test(NAME test-compile-own-00-generator-yield-star-throw-param COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw_param.ts") tslang_add_test(NAME test-jit-00-own-union-shape-field-borrow COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_union_shape_field_borrow.ts") tslang_add_test(NAME test-jit-rc-00-own-union-shape-field-borrow COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_union_shape_field_borrow.ts") tslang_add_test(NAME test-jit-own-00-own-union-shape-field-borrow COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_union_shape_field_borrow.ts") diff --git a/tslang/test/tester/tests/00arguments_length_given.ts b/tslang/test/tester/tests/00arguments_length_given.ts index fd4b0b48a..b58ab7395 100644 --- a/tslang/test/tester/tests/00arguments_length_given.ts +++ b/tslang/test/tester/tests/00arguments_length_given.ts @@ -1,6 +1,6 @@ // TSLANG 183 (114): `arguments.length` counts the arguments the caller gave, as in JavaScript, not the parameters the // function declares: an optional parameter left out, and one with a default value left out, are not counted. -function h(a: number, b?: number) { +function h(a: number, b?: number): number { return arguments.length; } @@ -42,6 +42,14 @@ function main() { assert(sum(1) == 11 && sum(1, 2) == 32 && sum(1, 2, 3) == 63, "sum"); assert(rest(1) == 1 && rest(1, 2, 3) == 3, "rest"); + // an `undefined` given is given (TSLANG 186): the call by name passes the count + assert(h(1, undefined) == 2, "h undefined"); + assert(d(1, undefined) == 2 && d(1, 2, undefined) == 3 && d(1, undefined, "x") == 3, "d undefined"); + assert(words("a" + 1, undefined) == "a1undefined", "words undefined"); + // ...through a function value it is counted as before (the count is not passed) + const hv: (a: number, b?: number) => number = h; + assert(hv(1) == 1 && hv(1, 2) == 2, "h value"); + // runtime strings, left out at every other call let t: number = 0; for (let i = 0; i < 2000; i++) t += words("a" + i, i % 2 == 0 ? "b" + i : undefined).length; diff --git a/tslang/test/tester/tests/00generator_yield_star_throw_only.ts b/tslang/test/tester/tests/00generator_yield_star_throw_only.ts new file mode 100644 index 000000000..d75792d83 --- /dev/null +++ b/tslang/test/tester/tests/00generator_yield_star_throw_only.ts @@ -0,0 +1,40 @@ +// TSLANG 186: a yield* over a generator whose type has throw() but not return(): a throw() of the generator at that +// yield is handed to the delegate's throw() as with a Generator that has both (183/184), and nothing calls a return() +// the type does not have +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; + throw?: (e: any) => IterateResult; +} + +let log = ""; + +function* inner(k: number): Generator { + try { + yield k; + yield k + 1; + } catch (e) { + log += "caught " + e + ";"; + } + yield k + 2; +} + +function* outer(k: number): Generator { + yield* inner(k); + yield 9; +} + +function main() { + const g = outer(1); + assert(g.next().value == 1, "1"); + assert(g.throw!("x").value == 3, "the delegate's next value"); + assert(log == "caught x;", "caught: " + log); + assert(g.next().value == 9, "then the generator's own"); + assert(g.next().done, "finished"); + + let sum: number = 0; + for (const v of outer(10)) sum += v; + assert(sum == 10 + 11 + 12 + 9, "to the end"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00generator_yield_star_throw_param.ts b/tslang/test/tester/tests/00generator_yield_star_throw_param.ts new file mode 100644 index 000000000..0d78ddbee --- /dev/null +++ b/tslang/test/tester/tests/00generator_yield_star_throw_param.ts @@ -0,0 +1,40 @@ +// TSLANG 186: a yield* of a generator a parameter holds (`yield* it`): a throw() of the generator at that yield is +// handed to the delegate's throw() in every model, -mm=own too (for elements that own nothing) +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; + return?: (value: T) => IterateResult; + throw?: (e: any) => IterateResult; +} + +let log = ""; + +function* inner(k: number): Generator { + try { + yield k; + yield k + 1; + } catch (e) { + log += "caught " + e + ";"; + } + yield k + 2; +} + +function* outer(it: Generator): Generator { + yield* it; + yield 9; +} + +function main() { + const g = outer(inner(1)); + assert(g.next().value == 1, "1"); + assert(g.throw!("x").value == 3, "the delegate's next value"); + assert(log == "caught x;", "caught: " + log); + assert(g.next().value == 9, "then the generator's own"); + assert(g.next().done, "finished"); + + let sum: number = 0; + for (const v of outer(inner(10))) sum += v; + assert(sum == 42, "to the end"); + + print("done."); +}