From d5935d1a30014c5856690cd536d96ee96f6e196d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 14:33:34 +0000 Subject: [PATCH 1/2] arguments.length counts the arguments given; generic arrows through generics and rest-array function types; throw() at a yield* reaches the delegate (TSLANG 183) Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 31 ++++ docs/whats-new.md | 1 + .../TypeScript/MLIRLogic/MLIRGenContext.h | 4 + tslang/lib/TypeScript/MLIRGenCast.cpp | 135 ++++++++++++++++-- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 78 +++++++++- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 25 +++- tslang/lib/TypeScript/MLIRGenGenerics.cpp | 74 ++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 50 ++++++- tslang/test/tester/CMakeLists.txt | 10 ++ .../tester/tests/00arguments_length_given.ts | 51 +++++++ .../tests/00generator_yield_star_throw.ts | 117 +++++++++++++++ .../tests/00generic_arrow_through_generic.ts | 33 +++++ 12 files changed, 595 insertions(+), 14 deletions(-) create mode 100644 tslang/test/tester/tests/00arguments_length_given.ts create mode 100644 tslang/test/tester/tests/00generator_yield_star_throw.ts create mode 100644 tslang/test/tester/tests/00generic_arrow_through_generic.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index b044c1bfc..127520268 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -3041,3 +3041,34 @@ Looked at, still open: borrow of an element cannot be one. Tests `00own_generator_for_of_this_field.ts` (gc, rc, own). + +183 (114, 94, 156, 2026-11-24). Fixed: +- `arguments.length` (114) counted the parameters the function declares, not the arguments given: `h(1)` of + `h(a, b?)` was 2. An optional parameter, or one with a default value, that the caller left out is not counted now + (mlirGenArguments: the count is worked out from the parameters given, and the `arguments` array is that long), in + a loop condition and a for-of over `arguments` too. A function with a rest parameter is as before. +- A generic arrow given to a parameter typed by a type parameter (94: `wrap((x: T) => x)`, `apply((x: T) => + x)`): the arrow is instantiated for `any` and its type inferred from that (resolveGenericParamFromFunctionCall). A + rest parameter typed by a type parameter (`(...args: A) => T`) is inferred from the function given, `A` an array + of its parameters' type (tryInferFunction), and a function that takes its parameters one by one can be given as a + function type whose rest parameter is an array: an adapter reads them out of the array (fewerParametersThunk for a + named function or an arrow, functionValueAdapter for one read at run time, `{ x: (n: number) => n + 1 }.x`). 94's + example now compiles and runs (gc, rc). +- throw() of a generator paused in a `yield*` (156): the exception is handed to the delegate's throw(), as in + JavaScript. The delegate may catch it and go on yielding (the generator gives its next value), or finish (the + `yield*` is done and the generator goes on), or throw it on (its finally blocks run, then the generator's own try + statements see it). The loop over a delegate that has `throw` calls next() itself, and the resume check at its + yield puts what throw() gives in place of the next step (mlirGenYieldStar, mlirGenGeneratorResumeChecks). + +Looked at, still open: +- `h(1, undefined)` of `h(a, b?)` gives 1 for `arguments.length` (JavaScript gives 2): an `undefined` given and one + left out are the same to the function. +- A function whose parameters have different types given to `(...args: A) => T` (`call2((a: number, b: string) => + b + a, 1, "x")`): `A` is inferred as `(number | string)[]`, not the tuple `[number, string]`, and the function is + refused. +- -mm=own: the function given as a rest-array function type when it is read at run time (an object literal's field, + 94's example): the own rule for adapters of such values, with that error. throw() at a `yield*` under -mm=own still + throws at the yield (the delegate is exchanged into a local for each call there, 156). + +Tests `00arguments_length_given.ts` (gc, rc, own), `00generic_arrow_through_generic.ts` (gc, rc), +`00generator_yield_star_throw.ts` (gc, rc). diff --git a/docs/whats-new.md b/docs/whats-new.md index 3dd9eee91..af8bb124a 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,6 @@ # What's new +- `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 - -mm=own: `for (const s of this.items) yield s` works in a generator method: the field is read again at each step (a field assigned during the loop is followed, unlike JavaScript's for-of) - -mm=own: a field read through a union of object shapes can be returned as a borrow of the argument (`getBox(s: Sq | Ci) { return s.box; }`); a method that throws an object through a `finally` that yields is a compile error at the call - -mm=own: a value moved in some branches of an `if ... else if` with no `else` is released on the others; `typeof a === "string"` narrows a `const` holding an `any`; a call that throws an object through a `finally` that yields is a compile error, not a stop at run time diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index 1ffb2391c..3b8c4164c 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -383,6 +383,10 @@ struct GenContext // In the loop a `yield*` makes over a delegate that has `return`: the variable holding it, whose return() a // return() of the generator calls first at that yield (mlirGenGeneratorResumeChecks) const char *yieldStarDelegate = nullptr; + // ...and where a throw() of the generator at that yield is handed to the delegate's throw() (TSLANG 183): the + // 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; // 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/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index a2a81e7d7..33d50ef3c 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -3529,6 +3529,58 @@ namespace mlirgen return !(sameResults && srcInputs.size() == destInputs.size()); } + // The array a function type's rest parameter is (`(...args: A) => T` with A `number[]`), null where it has none + static mlir_ts::ArrayType restArrayOf(mlir_ts::FunctionType funcType) + { + return funcType && funcType.isVarArg() && !funcType.isCVarArg() && funcType.getNumInputs() > 0 + ? dyn_cast(funcType.getInputs().back()) + : mlir_ts::ArrayType(); + } + + // adaptableSignature for a function given as a type with a rest array (TSLANG 94): the parameters the function + // takes past the type's fixed ones are elements of the array. With the same parameters as those elements there + // is still an adapter to make: it reads them out of the array. `fixedCount` is the number of fixed ones. + static bool adaptableToRestArray(mlir::ArrayRef srcInputs, mlir::TypeRange srcResults, + mlir::ArrayRef destInputs, mlir::TypeRange destResults, + mlir_ts::ArrayType restArray, bool &dropResult, size_t &fixedCount) + { + fixedCount = destInputs.size() - 1; + SmallVector destExpanded(destInputs.drop_back()); + for (auto index = fixedCount; index < srcInputs.size(); index++) + { + destExpanded.push_back(restArray.getElementType()); + } + + if (adaptableSignature(srcInputs, srcResults, destExpanded, destResults, dropResult)) + { + return true; + } + + dropResult = false; + return llvm::equal(srcInputs, destExpanded) && srcResults == destResults; + } + + // The arguments an adapter gives a function from the type's fixed ones and its rest array `rest`: the fixed ones, + // then an element of the array for each parameter the function takes past them + static void expandRestArguments(mlir::OpBuilder &builder, mlir::Location location, mlir::Type structIndexType, + mlir::ValueRange fixedArgs, mlir::Value rest, mlir_ts::ArrayType restArray, + size_t fixedCount, size_t srcCount, SmallVectorImpl &expandedArgs) + { + for (auto index = size_t(0); index < std::min((size_t)fixedArgs.size(), fixedCount); index++) + { + expandedArgs.push_back(fixedArgs[index]); + } + + for (auto index = fixedCount; index < srcCount; index++) + { + auto position = + builder.create(location, structIndexType, builder.getI32IntegerAttr((int)(index - fixedCount))); + auto elementRef = builder.create( + location, mlir_ts::RefType::get(restArray.getElementType()), rest, position); + expandedArgs.push_back(builder.create(location, restArray.getElementType(), elementRef)); + } + } + // The body of an adapter adaptableSignature allowed: calls `callee` with `leading` (a closure's captures, a // method's `this`) and then `args` - as many as the callee takes, `undefined` for its optional ones past them - // and returns its result as `destResults` says: as it is, widened, or dropped (released). Fails where an @@ -3635,8 +3687,12 @@ namespace mlirgen auto resFuncType = mth.GetFunctionType(type); // a closure's own value is its function bound over the captures (a method's is bound to its object) auto closure = boundOp && boundOp->hasAttr(OWNS_CAPTURE_ATTR_NAME); + // ...or one with a rest parameter, whose array holds what the function takes after the others (`(...args: A) + // => T` with A an array, given `(n: number) => number`, TSLANG 94): the adapter reads them out of it + auto restArray = restArrayOf(resFuncType); if (!symbolRefOp || !inFuncType || !resFuncType || inFuncType.isVarArg() || inFuncType.isCVarArg() - || resFuncType.isVarArg() || resFuncType.isCVarArg() || (boundOp && (!closure || inFuncType.getInputs().empty()))) + || (resFuncType.isVarArg() && !restArray) || resFuncType.isCVarArg() + || (boundOp && (!closure || inFuncType.getInputs().empty()))) { return mlir::Value(); } @@ -3650,8 +3706,14 @@ namespace mlirgen auto inInputs = inFuncType.getInputs(); auto srcInputs = boundOp ? inInputs.drop_front() : inInputs; + bool dropResult; - if (!adaptableSignature(srcInputs, inFuncType.getResults(), destInputs, resFuncType.getResults(), dropResult)) + size_t fixedCount = destInputs.size(); + auto adaptable = restArray + ? adaptableToRestArray(srcInputs, inFuncType.getResults(), destInputs, resFuncType.getResults(), restArray, + dropResult, fixedCount) + : adaptableSignature(srcInputs, inFuncType.getResults(), destInputs, resFuncType.getResults(), dropResult); + if (!adaptable) { return mlir::Value(); } @@ -3665,7 +3727,7 @@ namespace mlirgen resInputs.append(destInputs.begin(), destInputs.end()); auto calleeName = symbolRefOp.getIdentifier(); - auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), resInputs, resFuncType.getResults(), false); + auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), resInputs, resFuncType.getResults(), !!restArray); // one for each type it is given as: the name is the type's, printed (deterministic, unlike its pointer) std::string typeText; llvm::raw_string_ostream typeStream(typeText); @@ -3722,6 +3784,29 @@ namespace mlirgen mlir::ValueRange leading = boundOp ? mlir::ValueRange(passed).take_front(1) : mlir::ValueRange(); mlir::ValueRange args = boundOp ? mlir::ValueRange(passed).drop_front(1) : mlir::ValueRange(passed); + + // the rest array's elements, for the parameters past the others + SmallVector expandedArgs; + if (restArray) + { + auto restIndex = (boundOp ? 1u : 0u) + (unsigned)fixedCount; + mlir::Value rest; + if (restIndex < passed.size()) + { + rest = passed[restIndex]; + } + else + { + auto restParam = builder.create( + noLocation, mlir_ts::RefType::get(restArray), entryBlock.getArgument(restIndex), + builder.getBoolAttr(false), builder.getIndexAttr(restIndex + 1)); + rest = builder.create(noLocation, restArray, restParam); + } + + expandRestArguments(builder, noLocation, mth.getStructIndexType(), args, rest, restArray, fixedCount, + srcInputs.size(), expandedArgs); + args = mlir::ValueRange(expandedArgs); + } if (mlir::failed(emitSignatureAdapterBody(noLocation, callee, leading, srcInputs, inFuncType.getResults(), args, destResults, hasResult ? entryOp.getReference() : mlir::Value(), genContext))) @@ -3769,7 +3854,10 @@ namespace mlirgen auto srcType = mth.GetFunctionType(valueType); auto destType = mth.GetFunctionType(type); - if (!srcType || !destType || srcType.isVarArg() || srcType.isCVarArg() || destType.isVarArg() || destType.isCVarArg()) + // a type whose rest parameter is an array the function's parameters are read out of (TSLANG 94) + auto restArray = restArrayOf(destType); + if (!srcType || !destType || srcType.isVarArg() || srcType.isCVarArg() || (destType.isVarArg() && !restArray) + || destType.isCVarArg()) { return mlir::Value(); } @@ -3795,7 +3883,10 @@ namespace mlirgen } bool dropResult; - if (!adaptableSignature(srcInputs, srcType.getResults(), destInputs, destType.getResults(), dropResult)) + size_t fixedCount = destInputs.size(); + if (!(restArray ? adaptableToRestArray(srcInputs, srcType.getResults(), destInputs, destType.getResults(), restArray, + dropResult, fixedCount) + : adaptableSignature(srcInputs, srcType.getResults(), destInputs, destType.getResults(), dropResult))) { return mlir::Value(); } @@ -3809,7 +3900,7 @@ namespace mlirgen SmallVector thunkInputs{boxType}; thunkInputs.append(destInputs.begin(), destInputs.end()); - auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), thunkInputs, destType.getResults(), false); + auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), thunkInputs, destType.getResults(), !!restArray); // one adapter for each pair of types: the name is the types', printed (deterministic, unlike their pointers) std::string typesText; @@ -3861,8 +3952,17 @@ namespace mlirgen callee = builder.create(noLocation, srcType, func); } + mlir::ValueRange args = entryBlock.getArguments().drop_front(); + SmallVector expandedArgs; + if (restArray) + { + expandRestArguments(builder, noLocation, mth.getStructIndexType(), args, args.back(), restArray, fixedCount, + srcInputs.size(), expandedArgs); + args = mlir::ValueRange(expandedArgs); + } + if (mlir::failed(emitSignatureAdapterBody(noLocation, callee, leading, srcInputs, srcType.getResults(), - entryBlock.getArguments().drop_front(), destResults, + args, destResults, hasResult ? entryOp.getReference() : mlir::Value(), genContext))) { funcOp.erase(); @@ -4109,9 +4209,19 @@ namespace mlirgen guardAsBoolean = true; } + // ...and a function given as one whose rest parameter holds what it takes (`(n: number) => number` as + // `(...args: number[]) => number`, TSLANG 94) + auto toRestArray = false; + if (auto srcFuncType = mth.GetFunctionType(valueType), destFuncType = mth.GetFunctionType(type); + srcFuncType && destFuncType && !srcFuncType.isVarArg() && destFuncType.isVarArg() + && destFuncType.getNumInputs() > 0 && isa(destFuncType.getInputs().back())) + { + toRestArray = true; + } + // fewer parameters, more optional ones, a result given as `void` (`let f: () => void = n`) or // widened (`() => string` as `() => string | number`): adaptableSignature - if (guardAsBoolean || test.result == MatchResultType::NotMatchArgCount + if (guardAsBoolean || toRestArray || test.result == MatchResultType::NotMatchArgCount || test.result == MatchResultType::NotMatchResultCount || test.result == MatchResultType::NotMatchResult) { @@ -4145,9 +4255,14 @@ namespace mlirgen }; bool dropResult; - ownAdapterRefused = adaptableSignature(visibleInputs(valueType, srcType), srcType.getResults(), + size_t fixedCount; + auto restArray = restArrayOf(destType); + ownAdapterRefused = (restArray && !srcType.isVarArg() ? adaptableToRestArray(visibleInputs(valueType, srcType), srcType.getResults(), + visibleInputs(type, destType), destType.getResults(), + restArray, dropResult, fixedCount) + : adaptableSignature(visibleInputs(valueType, srcType), srcType.getResults(), visibleInputs(type, destType), destType.getResults(), - dropResult); + dropResult)); } emitFunctionTypeMismatch(location, valueType, type, test, ownAdapterRefused); diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 25d471ea4..c64cd990c 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -4043,6 +4043,10 @@ namespace mlirgen SmallVector values; mlir::Value restArguments; + // what the caller gave for each optional parameter, the optional the parameter is made of (ts.ParamOpt): + // `h(1)` of `h(a, b?)` gave one argument, not two (TSLANG 114, 183) + SmallVector givenOptional; + auto anyOptional = false; for (auto ¶m : genContext.bodyFuncProto->getParams()) { // a method's object is not one of its arguments @@ -4056,6 +4060,27 @@ namespace mlirgen auto result = mlirGen(location, param->getName(), genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) auto value = V(result); + + // (`b?: number` is held as the optional it is given; `b = 7` as its value, made of that optional) + mlir::Value given; + if (isa(value.getType()) && !param->getIsMultiArgsParam()) + { + given = value; + anyOptional = true; + } + else if (auto loadOp = value.getDefiningOp()) + { + if (auto paramOpt = loadOp.getReference().getDefiningOp()) + { + given = paramOpt->getOperand(0); + anyOptional = true; + } + } + + if (!param->getIsMultiArgsParam()) + { + givenOptional.push_back(given); + } if (param->getIsMultiArgsParam()) { if (!isa(value.getType())) @@ -4077,6 +4102,7 @@ namespace mlirgen } mlir::Value argumentsArray; + mlir::Value argumentsCount; if (restArguments) { // [...the others, ...rest], as an array literal with a spread is made: each element of the rest is @@ -4100,6 +4126,36 @@ namespace mlirgen // the array releases what it holds when it dies (as a rest parameter's array does) 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 + if (anyOptional) + { + auto i32Type = builder.getI32Type(); + mlir::Value count = builder.create(location, i32Type, builder.getI32IntegerAttr(0)); + for (auto [index, given] : llvm::enumerate(givenOptional)) + { + auto atLeast = builder.create(location, i32Type, + builder.getI32IntegerAttr((int)index + 1)); + if (!given) + { + count = atLeast; + continue; + } + + auto hasValue = builder.create(location, getBooleanType(), given); + auto ifOp = builder.create(location, mlir::TypeRange{i32Type}, hasValue, true); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + builder.create(location, mlir::ValueRange{atLeast}); + 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); + } } // held by a local of its own: read as a temporary (`for (const v of arguments)`), a spread literal was @@ -4110,6 +4166,15 @@ namespace mlirgen auto *regionOwner = builder.getInsertionBlock() ? builder.getInsertionBlock()->getParentOp() : nullptr; if (mlir::isa_and_nonnull(regionOwner)) { + if (argumentsCount) + { + auto arrayRef = builder.create(location, mlir_ts::RefType::get(argumentsArray.getType()), + argumentsArray, builder.getBoolAttr(false), + builder.getIndexAttr(0)); + builder.create(location, arrayRef, argumentsCount); + return V(builder.create(location, argumentsArray.getType(), arrayRef)); + } + return argumentsArray; } @@ -4127,7 +4192,18 @@ namespace mlirgen return mlir::failure(); } - return resolveIdentifier(location, name, genContext); + auto local = resolveIdentifier(location, name, genContext); + if (local && argumentsCount) + { + MLIRCodeLogic mcl(builder, compileOptions); + if (auto localRef = mcl.GetReferenceFromValue(location, local)) + { + builder.create(location, localRef, argumentsCount); + return V(builder.create(location, local.getType(), localRef)); + } + } + + return local; } ValueOrLogicalResult MLIRGenImpl::mlirGen(mlir::Location location, StringRef name, const GenContext &genContext) diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 42bdf49b0..1e75090c1 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1449,7 +1449,30 @@ namespace mlirgen NodeArray throwStatements; throwStatements.push_back(resetMode()); - throwStatements.push_back(nf.createThrowStatement(thisProp(GENERATOR_THROWN_NAME))); + if (genContext.yieldStarDelegate && genContext.yieldStarResult && genContext.yieldStarSkipNext) + { + // at the yield of a yield* whose delegate has throw(): handed to it, its result the loop's next step + // (mlirGenYieldStar) - `if (.yd.throw) { .yc = .yd.throw!(this.thrown); .ys = true; } else throw this.thrown;` + auto delegateThrow = [&]() { + return nf.createPropertyAccessExpression(nf.createIdentifier(stows(std::string(genContext.yieldStarDelegate))), + nf.createIdentifier(S("throw"))); + }; + NodeArray arguments; + arguments.push_back(thisProp(GENERATOR_THROWN_NAME)); + NodeArray 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)))); + handStatements.push_back(nf.createExpressionStatement(nf.createBinaryExpression( + nf.createIdentifier(stows(std::string(genContext.yieldStarSkipNext))), nf.createToken(SyntaxKind::EqualsToken), + nf.createToken(SyntaxKind::TrueKeyword)))); + throwStatements.push_back(nf.createIfStatement(delegateThrow(), nf.createBlock(handStatements, false), + nf.createThrowStatement(thisProp(GENERATOR_THROWN_NAME)))); + } + else + { + throwStatements.push_back(nf.createThrowStatement(thisProp(GENERATOR_THROWN_NAME))); + } // with the value return() was given (kept in `.thrown`) auto finish = nf.createReturnStatement(thisProp(GENERATOR_THROWN_NAME)); diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index 67199209e..92baab2ad 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -341,6 +341,58 @@ namespace mlirgen funcType = funcType.drop_front(); } + // `(...args: A) => T` given `(n: number) => number` (TSLANG 94): A is the array the rest parameter holds, + // `number[]`, as the arguments given for a rest parameter make it - not `number`, which with those + // arguments' `s32[]` made A a union of both + auto templateIsVarArg = false; + if (auto tempFunc = dyn_cast(templateType)) + { + templateIsVarArg = tempFunc.isVarArg(); + } + else if (auto tempHybrid = dyn_cast(templateType)) + { + templateIsVarArg = tempHybrid.isVarArg(); + } + + // (a function with a rest parameter of its own, `(...args: number[]) => ...`, is matched as before) + auto concreteIsVarArg = false; + if (auto concreteFunc = dyn_cast(concreteType)) + { + concreteIsVarArg = concreteFunc.isVarArg(); + } + else if (auto concreteHybrid = dyn_cast(concreteType)) + { + concreteIsVarArg = concreteHybrid.isVarArg(); + } + + if (templateIsVarArg && !concreteIsVarArg && !tempfuncType.empty() && + isa(tempfuncType.back()) && funcType.size() >= tempfuncType.size() - 1) + { + auto fixed = tempfuncType.size() - 1; + inferTypeFuncType(location, tempfuncType.take_front(fixed), funcType.take_front(fixed), results, genContext); + + struct ArrayInfo arrayInfo{}; + for (auto restType : funcType.drop_front(fixed)) + { + accumulateArrayItemType(location, restType, arrayInfo); + } + + if (arrayInfo.accumulatedArrayElementType) + { + inferType(location, tempfuncType.back(), getArrayType(arrayInfo.accumulatedArrayElementType), + results, genContext); + } + + auto tempfuncRetType = mth.getReturnsFromFuncRef(templateType); + auto funcRetType = mth.getReturnsFromFuncRef(concreteType); + if (tempfuncRetType.size() > 0 && funcRetType.size() > 0) + { + inferTypeFuncType(location, tempfuncRetType, funcRetType, results, genContext); + } + + return true; + } + if (funcType.size() > 0 || tempfuncType.size() == 0) { inferTypeFuncType(location, tempfuncType, funcType, results, genContext); @@ -1056,6 +1108,28 @@ namespace mlirgen } StringMap inferredTypes; + + // a generic function given for a parameter that is a type parameter itself (`wrap(x: X)` given + // `(x: T) => x`, TSLANG 94): X is the function with `any` for its own type parameters, which it is + // instantiated as where it is given (a value of a type parameter can't stay generic). Its type with T + // in it was taken for X: "can't find type by name: T". + if (isa(paramType) && isGenericFunctionReference(argOp)) + { + // (the instance's own type: the receiver it is made for says no result, which is found from its body) + auto instantiated = instantiateGenericFunctionWithAny(location, argOp, genericTypeGenContext); + if (instantiated && V(instantiated) && !isGenericFunctionReference(V(instantiated))) + { + inferType(location, paramType, V(instantiated).getType(), inferredTypes, genericTypeGenContext); + if (mlir::failed(appendInferredTypes(location, functionGenericTypeInfo->typeParams, inferredTypes, + anyNamedGenericType, genericTypeGenContext, false, true))) + { + return {mlir::failure(), true}; + } + + return {mlir::success(), true}; + } + } + inferType(location, paramType, argOp.getType(), inferredTypes, genericTypeGenContext); if (mlir::failed(appendInferredTypes(location, functionGenericTypeInfo->typeParams, inferredTypes, anyNamedGenericType, genericTypeGenContext, false, true))) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index aea75cf7a..4ded56e2b 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -5204,11 +5204,57 @@ class MLIRGenImpl NodeArray statements; statements.push_back(nf.createVariableStatement( undefined, nf.createVariableDeclarationList(delegateDeclarations, NodeFlags::Const))); - statements.push_back(nf.createForOfStatement(undefined, declList, delegateIdent, - nf.createExpressionStatement(_yield_expr))); GenContext delegateGenContext(genContext); delegateGenContext.yieldStarDelegate = ".yd"; + + // ...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 + // next() itself, and the resume check puts what throw() gives in place of the next step: + // 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")) + { + auto resultIdent = nf.createIdentifier(S(".yc")); + auto skipIdent = nf.createIdentifier(S(".ys")); + auto nextCall = [&]() { + return nf.createCallExpression( + nf.createPropertyAccessExpression(delegateIdent, nf.createIdentifier(S(ITERATOR_NEXT))), undefined, + NodeArray()); + }; + auto declare = [&](Identifier name, Expression initializer) { + NodeArray declarations; + declarations.push_back(nf.createVariableDeclaration(name, undefined, undefined, initializer)); + return nf.createVariableStatement(undefined, nf.createVariableDeclarationList(declarations, NodeFlags::Let)); + }; + + _yield_expr->expression = nf.createPropertyAccessExpression(resultIdent, nf.createIdentifier(S("value"))); + + NodeArray loopStatements; + loopStatements.push_back(declare(skipIdent, nf.createToken(SyntaxKind::FalseKeyword))); + loopStatements.push_back(nf.createExpressionStatement(_yield_expr)); + loopStatements.push_back(nf.createIfStatement( + nf.createPrefixUnaryExpression(nf.createToken(SyntaxKind::ExclamationToken), skipIdent), + nf.createExpressionStatement( + nf.createBinaryExpression(resultIdent, nf.createToken(SyntaxKind::EqualsToken), nextCall())), + undefined)); + + statements.push_back(declare(resultIdent, nextCall())); + statements.push_back(nf.createWhileStatement( + nf.createPrefixUnaryExpression(nf.createToken(SyntaxKind::ExclamationToken), + nf.createPropertyAccessExpression(resultIdent, nf.createIdentifier(S("done")))), + nf.createBlock(loopStatements, false))); + + delegateGenContext.yieldStarResult = ".yc"; + delegateGenContext.yieldStarSkipNext = ".ys"; + } + else + { + statements.push_back(nf.createForOfStatement(undefined, declList, delegateIdent, + nf.createExpressionStatement(_yield_expr))); + } + for (auto statement : statements) { if (mlir::failed(mlirGen(statement, delegateGenContext))) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 0dec1cb4e..719f1299b 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1412,6 +1412,16 @@ tslang_add_test(NAME test-jit-00-own-generator-for-of-this-field COMMAND test-ru tslang_add_test(NAME test-jit-rc-00-own-generator-for-of-this-field COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_generator_for_of_this_field.ts") tslang_add_test(NAME test-jit-own-00-own-generator-for-of-this-field COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_generator_for_of_this_field.ts") tslang_add_test(NAME test-compile-own-00-own-generator-for-of-this-field COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_generator_for_of_this_field.ts") +tslang_add_test(NAME test-jit-00-arguments-length-given COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00arguments_length_given.ts") +tslang_add_test(NAME test-jit-rc-00-arguments-length-given COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00arguments_length_given.ts") +tslang_add_test(NAME test-jit-own-00-arguments-length-given COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00arguments_length_given.ts") +tslang_add_test(NAME test-compile-00-arguments-length-given COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00arguments_length_given.ts") +tslang_add_test(NAME test-jit-00-generic-arrow-through-generic COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generic_arrow_through_generic.ts") +tslang_add_test(NAME test-jit-rc-00-generic-arrow-through-generic COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generic_arrow_through_generic.ts") +tslang_add_test(NAME test-compile-00-generic-arrow-through-generic COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generic_arrow_through_generic.ts") +tslang_add_test(NAME test-jit-00-generator-yield-star-throw COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw.ts") +tslang_add_test(NAME test-jit-rc-00-generator-yield-star-throw COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_yield_star_throw.ts") +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-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 new file mode 100644 index 000000000..fd4b0b48a --- /dev/null +++ b/tslang/test/tester/tests/00arguments_length_given.ts @@ -0,0 +1,51 @@ +// 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) { + return arguments.length; +} + +function d(a: number, b = 7, c?: string) { + return arguments.length; +} + +function z(a?: number) { + return arguments.length; +} + +function joined(a: number, b?: number) { + let s = ""; + for (const v of arguments) s += v; + return s; +} + +function sum(a: number, b?: number, c?: number) { + let t: number = 0; + for (let i = 0; i < arguments.length; i++) t += arguments[i]; + return t * 10 + arguments.length; +} + +function rest(a: number, ...xs: number[]) { + return arguments.length; +} + +function words(a: string, b?: string) { + let o = ""; + for (const v of arguments) o += v; + return o; +} + +function main() { + assert(h(1) == 1 && h(1, 2) == 2, "h"); + assert(d(1) == 1 && d(1, 2) == 2 && d(1, 2, "x") == 3, "d"); + assert(z() == 0 && z(5) == 1, "z"); + assert(joined(1) == "1" && joined(1, 2) == "12", "joined"); + assert(sum(1) == 11 && sum(1, 2) == 32 && sum(1, 2, 3) == 63, "sum"); + assert(rest(1) == 1 && rest(1, 2, 3) == 3, "rest"); + + // 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; + assert(t > 0, "words"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00generator_yield_star_throw.ts b/tslang/test/tester/tests/00generator_yield_star_throw.ts new file mode 100644 index 000000000..f2e64ddaa --- /dev/null +++ b/tslang/test/tester/tests/00generator_yield_star_throw.ts @@ -0,0 +1,117 @@ +// TSLANG 183: throw() of a generator paused in a `yield*` over a Generator is handed to the delegate's throw(), as in +// JavaScript (156): the delegate may catch the exception and go on yielding, or finish, and the generator goes on +// with what it gives; one that does not catch it throws it on, through the generator's own try/catch. +type IterateResult = { value: T, done: boolean }; +interface Generator { + next: (value?: TNext) => IterateResult; + return?: (value: T) => IterateResult; + throw?: (e: any) => IterateResult; +} + +let log = ""; + +// catches, and goes on yielding +function* catching(): Generator { + try { + yield 1; + yield 2; + } catch (e) { + log += "caught " + e + ";"; + } + yield 99; +} + +function* outer(): Generator { + yield* catching(); + yield 100; +} + +// does not catch: its finally runs, and the generator's own catch gets it +function* plain(): Generator { + try { + yield 1; + yield 2; + } finally { + log += "plain finally;"; + } +} + +function* guarded(): Generator { + try { + yield* plain(); + } catch (e) { + log += "guarded " + e + ";"; + } + yield 50; + yield 51; +} + +// catches, and finishes: the yield* is done +function* finishing(): Generator { + try { + yield 1; + } catch (e) { + log += "finishing;"; + } +} + +function* afterFinish(): Generator { + yield* finishing(); + yield 7; +} + +// through two yield*s +function* twice(): Generator { + yield* outer(); +} + +function main() { + const g = outer(); + assert(g.next().value == 1, "1"); + const r = g.throw!("boom"); + assert(!r.done && r.value == 99, "the delegate's next value"); + assert(log == "caught boom;", "the delegate caught it: " + log); + assert(g.next().value == 100, "then the generator's own"); + assert(g.next().done, "finished"); + + log = ""; + const h = guarded(); + assert(h.next().value == 1, "h 1"); + const r2 = h.throw!("x"); + assert(!r2.done && r2.value == 50, "the generator's catch: " + log); + assert(log == "plain finally;guarded x;", "the delegate's finally first: " + log); + assert(h.next().value == 51, "h 51"); + assert(h.next().done, "h finished"); + + log = ""; + const f = afterFinish(); + assert(f.next().value == 1, "f 1"); + const r3 = f.throw!("y"); + assert(!r3.done && r3.value == 7, "past the finished yield*"); + assert(log == "finishing;", "finishing: " + log); + + log = ""; + const t = twice(); + assert(t.next().value == 1, "t 1"); + assert(t.throw!("z").value == 99, "t through two"); + assert(log == "caught z;", "t: " + log); + assert(t.next().value == 100, "t 100"); + + // not thrown: as before + let sum: number = 0; + for (const v of outer()) sum += v; + assert(sum == 202, "to the end"); + + // thrown at a generator nothing catches in: thrown on + let threw = false; + const p = plain(); + p.next(); + try { + p.throw!("w"); + } catch (e) { + threw = true; + } + assert(threw, "thrown on"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00generic_arrow_through_generic.ts b/tslang/test/tester/tests/00generic_arrow_through_generic.ts new file mode 100644 index 000000000..7de6943a1 --- /dev/null +++ b/tslang/test/tester/tests/00generic_arrow_through_generic.ts @@ -0,0 +1,33 @@ +// TSLANG 183 (94): a generic arrow given to a parameter typed by a type parameter (`wrap((x: T) => x)`), and a +// function given where the type is `(...args: A) => T` with A inferred from it. +function wrap(x: X): { x: X } { + return { x }; +} + +function apply(f: F) { + return f; +} + +function call(x: { x: (...args: A) => T }, ...args: A): T { + return x.x(...args); +} + +function call2(f: (...args: A) => T, ...args: A): T { + return f(...args); +} + +const kept = call(wrap((x: T) => x), 1); + +function main() { + const w = wrap((x: T) => x); + assert(w.x(5) == 5, "wrap"); + + const g = apply((x: T) => x); + assert(g(5) == 5, "apply"); + + assert(call({ x: (n: number) => n + 1 }, 4) == 5, "call"); + assert(call2((n: number) => n + 1, 4) == 5, "call2"); + assert(kept == 1, "kept"); + + print("done."); +} From 0c136bf15396c8c7a65ff05fb2c41ec802f9831d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 14:58:19 +0000 Subject: [PATCH 2/2] wasm: skip 00generator_yield_star_throw.ts under own (throw() at a yield* is not handed to the delegate there yet) Co-Authored-By: Claude Opus 5.5 --- tslang/test/wasm/wasm_skips.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tslang/test/wasm/wasm_skips.txt b/tslang/test/wasm/wasm_skips.txt index 9eb1e83b4..542778c05 100644 --- a/tslang/test/wasm/wasm_skips.txt +++ b/tslang/test/wasm/wasm_skips.txt @@ -18,3 +18,4 @@ json.ts none # (default library) builds a 100000-character st 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) 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) +00generator_yield_star_throw.ts own # throw() at a yield* is not handed to the delegate under -mm=own yet: thrown at the yield (TSLANG 183, done in 184)