diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index e4f39aecf..1d0ef665b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -195,6 +195,11 @@ struct GenContext mlir::Type thisType; mlir_ts::ClassType thisClassType; mlir::Type receiverFuncType; + // the numeric result of the base class's method a method overrides without a return type of its own + // (`f() { return 3; }`, s32, for `f(): number`): its vtable slot calls it as the base's; for that + // declaration only, not for a function nested in it + mlir::Type overriddenReturnType; + const void *overriddenReturnFor = nullptr; mlir::Type receiverType; mlir::StringRef receiverName; bool isGlobalVarReceiver = false; diff --git a/tslang/include/TypeScript/TypeScriptPassContext.h b/tslang/include/TypeScript/TypeScriptPassContext.h index b7ce52985..118520341 100644 --- a/tslang/include/TypeScript/TypeScriptPassContext.h +++ b/tslang/include/TypeScript/TypeScriptPassContext.h @@ -191,6 +191,19 @@ template class TsPattern : public OpRewritePattern } protected: + // a call an op lowers to (an accessor's) unwinds where the op does: to the handler a try recorded for it + template + CallOpTy createCall(PatternRewriter &rewriter, Operation *from, Args &&...args) const + { + auto call = rewriter.create(std::forward(args)...); + if (auto unwind = tsContext->unwind.lookup(from)) + { + tsContext->unwind[call] = unwind; + } + + return call; + } + TSContext *tsContext; TSFunctionContext *tsFuncContext; }; diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index e14606be7..38c2bf85b 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -893,6 +893,14 @@ struct SwitchOpLowering : public TsPattern } }; +// an op a try's handler catches what it throws: a call, a throw, or an accessor, lowered later to calls +static bool unwindsToHandler(Operation *op) +{ + return isa(op); +} + struct AccessorOpLowering : public TsPattern { using TsPattern::TsPattern; @@ -909,7 +917,7 @@ struct AccessorOpLowering : public TsPattern return mlir::failure(); } - auto callRes = rewriter.create(loc, accessorOp.getSetAccessor().value(), + auto callRes = createCall(rewriter, accessorOp, loc, accessorOp.getSetAccessor().value(), mlir::TypeRange{}, mlir::ValueRange{accessorOp.getSetValue()}); } @@ -921,7 +929,7 @@ struct AccessorOpLowering : public TsPattern return failure(); } - auto callRes = rewriter.create(loc, accessorOp.getGetAccessor().value(), + auto callRes = createCall(rewriter, accessorOp, loc, accessorOp.getGetAccessor().value(), TypeRange{accessorOp.getType(0)}, ValueRange{}); rewriter.replaceOp(accessorOp, callRes.getResult(0)); @@ -951,7 +959,7 @@ struct ThisAccessorOpLowering : public TsPattern return mlir::failure(); } - rewriter.create(loc, thisAccessorOp.getSetAccessor().value(), + createCall(rewriter, thisAccessorOp, loc, thisAccessorOp.getSetAccessor().value(), mlir::TypeRange{}, mlir::ValueRange{thisAccessorOp.getThisVal(), thisAccessorOp.getSetValue()}); } @@ -964,7 +972,7 @@ struct ThisAccessorOpLowering : public TsPattern } auto callRes = - rewriter.create(loc, thisAccessorOp.getGetAccessor().value(), + createCall(rewriter, thisAccessorOp, loc, thisAccessorOp.getGetAccessor().value(), TypeRange{thisAccessorOp.getType(0)}, ValueRange{thisAccessorOp.getThisVal()}); rewriter.replaceOp(thisAccessorOp, callRes.getResult(0)); @@ -995,7 +1003,7 @@ struct ThisIndirectAccessorOpLowering : public TsPattern(loc, TypeRange{}, + createCall(rewriter, thisIndirectAccessorOp, loc, TypeRange{}, thisIndirectAccessorOp.getSetAccessor(), ValueRange{thisIndirectAccessorOp.getThisVal(), thisIndirectAccessorOp.getSetValue()}); } @@ -1009,7 +1017,7 @@ struct ThisIndirectAccessorOpLowering : public TsPattern(loc, TypeRange{thisIndirectAccessorOp.getType(0)}, + auto callRes = createCall(rewriter, thisIndirectAccessorOp, loc, TypeRange{thisIndirectAccessorOp.getType(0)}, thisIndirectAccessorOp.getGetAccessor(), ValueRange{thisIndirectAccessorOp.getThisVal()}); rewriter.replaceOp(thisIndirectAccessorOp, callRes.getResult(0)); @@ -1039,7 +1047,7 @@ struct ThisIndexAccessorOpLowering : public TsPattern(loc, thisIndexAccessorOp.getSetAccessor().value(), + createCall(rewriter, thisIndexAccessorOp, loc, thisIndexAccessorOp.getSetAccessor().value(), mlir::TypeRange{}, mlir::ValueRange{thisIndexAccessorOp.getThisVal(), thisIndexAccessorOp.getIndex(), thisIndexAccessorOp.getSetValue()}); } @@ -1053,7 +1061,7 @@ struct ThisIndexAccessorOpLowering : public TsPattern(loc, thisIndexAccessorOp.getGetAccessor().value(), + createCall(rewriter, thisIndexAccessorOp, loc, thisIndexAccessorOp.getGetAccessor().value(), TypeRange{thisIndexAccessorOp.getType(0)}, ValueRange{thisIndexAccessorOp.getThisVal(), thisIndexAccessorOp.getIndex()}); @@ -1084,7 +1092,7 @@ struct ThisIndirectIndexAccessorOpLowering : public TsPattern(loc, TypeRange{}, thisIndirectIndexAccessorOp.getSetAccessor(), + createCall(rewriter, thisIndirectIndexAccessorOp, loc, TypeRange{}, thisIndirectIndexAccessorOp.getSetAccessor(), mlir::ValueRange{thisIndirectIndexAccessorOp.getThisVal(), thisIndirectIndexAccessorOp.getIndex(), thisIndirectIndexAccessorOp.getSetValue()}); } @@ -1098,7 +1106,7 @@ struct ThisIndirectIndexAccessorOpLowering : public TsPattern(loc, TypeRange{thisIndirectIndexAccessorOp.getType(0)}, thisIndirectIndexAccessorOp.getGetAccessor(), + createCall(rewriter, thisIndirectIndexAccessorOp, loc, TypeRange{thisIndirectIndexAccessorOp.getType(0)}, thisIndirectIndexAccessorOp.getGetAccessor(), ValueRange{thisIndirectIndexAccessorOp.getThisVal(), thisIndirectIndexAccessorOp.getIndex()}); rewriter.replaceOp(thisIndirectIndexAccessorOp, callRes.getResult(0)); @@ -1139,7 +1147,7 @@ struct BoundIndirectAccessorOpLowering : public TsPattern(loc, opaqueType, boundIndirectAccessorOp.getSetAccessor()); auto methodOp = rewriter.create(loc, funcType, boundIndirectAccessorOp.getSetAccessor()); - rewriter.create(loc, TypeRange{}, + createCall(rewriter, boundIndirectAccessorOp, loc, TypeRange{}, methodOp, ValueRange{thisOp, boundIndirectAccessorOp.getSetValue()}); } @@ -1161,7 +1169,7 @@ struct BoundIndirectAccessorOpLowering : public TsPattern(loc, opaqueType, boundIndirectAccessorOp.getGetAccessor()); auto methodOp = rewriter.create(loc, funcType, boundIndirectAccessorOp.getGetAccessor()); - auto callRes = rewriter.create(loc, TypeRange{boundIndirectAccessorOp.getType(0)}, + auto callRes = createCall(rewriter, boundIndirectAccessorOp, loc, TypeRange{boundIndirectAccessorOp.getType(0)}, methodOp, ValueRange{thisOp}); rewriter.replaceOp(boundIndirectAccessorOp, callRes.getResult(0)); @@ -1201,7 +1209,7 @@ struct BoundIndirectIndexAccessorOpLowering : public TsPattern(loc, opaqueType, boundIndirectIndexAccessorOp.getSetAccessor()); auto methodOp = rewriter.create(loc, funcType, boundIndirectIndexAccessorOp.getSetAccessor()); - rewriter.create(loc, TypeRange{}, methodOp, mlir::ValueRange{thisOp, + createCall(rewriter, boundIndirectIndexAccessorOp, loc, TypeRange{}, methodOp, mlir::ValueRange{thisOp, boundIndirectIndexAccessorOp.getIndex(), boundIndirectIndexAccessorOp.getSetValue()}); } @@ -1223,7 +1231,7 @@ struct BoundIndirectIndexAccessorOpLowering : public TsPattern(loc, funcType, boundIndirectIndexAccessorOp.getGetAccessor()); auto callRes = - rewriter.create(loc, TypeRange{boundIndirectIndexAccessorOp.getType(0)}, + createCall(rewriter, boundIndirectIndexAccessorOp, loc, TypeRange{boundIndirectIndexAccessorOp.getType(0)}, methodOp, ValueRange{thisOp, boundIndirectIndexAccessorOp.getIndex()}); rewriter.replaceOp(boundIndirectIndexAccessorOp, callRes.getResult(0)); @@ -1890,15 +1898,7 @@ struct TryOpLowering : public TsPattern return; } - if (auto callOp = dyn_cast_or_null(op)) - { - tsContext->unwind[op] = landingBlock; - } - else if (auto callIndirectOp = dyn_cast_or_null(op)) - { - tsContext->unwind[op] = landingBlock; - } - else if (auto throwOp = dyn_cast_or_null(op)) + if (unwindsToHandler(op)) { tsContext->unwind[op] = landingBlock; } @@ -2097,15 +2097,7 @@ struct TryOpLowering : public TsPattern // point all throw in catch block to clean up block auto visitorCallOpContinueCleanup = [&](Operation *op) { - if (auto callOp = dyn_cast_or_null(op)) - { - tsContext->unwind[op] = finallyBlock; - } - else if (auto callIndirectOp = dyn_cast_or_null(op)) - { - tsContext->unwind[op] = finallyBlock; - } - else if (auto throwOp = dyn_cast_or_null(op)) + if (unwindsToHandler(op)) { tsContext->unwind[op] = finallyBlock; } diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index c8a0e249b..cb4009957 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -1158,6 +1158,8 @@ namespace mlirgen } } + mlirGenClassGetterOnlyForBase(newClassPtr, classDeclarationAST); + if (newClassPtr->getHasVirtualTableVariable()) { auto fieldId = MLIRHelper::TupleFieldName(VTABLE_NAME, builder.getContext()); @@ -1616,33 +1618,58 @@ namespace mlirgen return mlir::success(); } - // A field implementing an abstract accessor of a base class (`abstract prop: T` there, or - // `abstract get prop(): T`): the class gets accessors over the field, which fill the base's slots, so a - // read through the base reads the field. Through the class itself the field is read, found first. - void MLIRGenImpl::mlirGenClassFieldAccessorsForBase(ClassInfo::TypePtr newClassPtr, PropertyDeclaration propertyDeclaration) + // the numeric result of the nearest base class's method (or accessor) of the name, which a method of the same + // name without a return type overrides: `f() { return 3; }` infers s32, but its slot is called as returning + // the base's `number` + mlir::Type MLIRGenImpl::overriddenNumericReturnType(ClassInfo::TypePtr classInfo, StringRef methodName) { - auto nameStr = MLIRHelper::getName(propertyDeclaration->name); + for (auto &base : classInfo->baseClasses) + { + auto index = base->getMethodIndex(methodName); + if (index >= 0) + { + auto funcType = base->methods[index].funcType; + return funcType && funcType.getNumResults() > 0 && mth.isNumericType(funcType.getResult(0)) + ? funcType.getResult(0) + : mlir::Type(); + } - // the nearest base class's accessor of the name: one implemented on the way is not abstract - std::function nearestAccessor = [&](ClassInfo::TypePtr classInfo) -> AccessorInfo * { - for (auto &base : classInfo->baseClasses) + if (auto found = overriddenNumericReturnType(base, methodName)) { - auto index = base->getAccessorIndex(nameStr); - if (index >= 0) - { - return &base->accessors[index]; - } + return found; + } + } - if (auto *found = nearestAccessor(base)) - { - return found; - } + return mlir::Type(); + } + + // the nearest base class's accessor of the name: one implemented on the way is not abstract + static AccessorInfo *nearestBaseAccessor(ClassInfo::TypePtr classInfo, StringRef name) + { + for (auto &base : classInfo->baseClasses) + { + auto index = base->getAccessorIndex(name); + if (index >= 0) + { + return &base->accessors[index]; } - return nullptr; - }; + if (auto *found = nearestBaseAccessor(base, name)) + { + return found; + } + } + + return nullptr; + } - auto *accessor = nearestAccessor(newClassPtr); + // A field implementing an abstract accessor of a base class (`abstract prop: T` there, or + // `abstract get prop(): T`): the class gets accessors over the field, which fill the base's slots, so a + // read through the base reads the field. Through the class itself the field is read, found first. + void MLIRGenImpl::mlirGenClassFieldAccessorsForBase(ClassInfo::TypePtr newClassPtr, PropertyDeclaration propertyDeclaration) + { + auto nameStr = MLIRHelper::getName(propertyDeclaration->name); + auto *accessor = nearestBaseAccessor(newClassPtr, nameStr); if (!accessor || accessor->isStatic || !accessor->isAbstract) { return; @@ -1652,6 +1679,81 @@ namespace mlirgen mlirGenClassSynthAccessors(newClassPtr, propertyDeclaration, type, !!accessor->get, !!accessor->set, false); } + // A getter alone implementing an abstract accessor pair of a base class (`abstract prop: T` there): a write + // through the base fills the setter's slot, so the class gets a setter that throws, as JavaScript's write to a + // property with only a getter does - a TypeError, or a failing assert without the default library. + void MLIRGenImpl::mlirGenClassGetterOnlyForBase(ClassInfo::TypePtr newClassPtr, ClassLikeDeclaration classDeclarationAST) + { + for (auto &classMember : classDeclarationAST->members) + { + if (classMember != SyntaxKind::GetAccessor || hasModifier(classMember, SyntaxKind::StaticKeyword)) + { + continue; + } + + auto name = classMember.as()->name; + auto nameStr = MLIRHelper::getName(name); + auto hasMember = [&](NodeArray members, SyntaxKind kind) { + return llvm::any_of(members, [&](ClassElement member) { + return member == kind && MLIRHelper::getName(member.as()->name) == nameStr; + }); + }; + + if (hasMember(classDeclarationAST->members, SyntaxKind::SetAccessor) + || hasMember(newClassPtr->extraMembersPost, SyntaxKind::SetAccessor)) + { + continue; + } + + auto *accessor = nearestBaseAccessor(newClassPtr, nameStr); + if (!accessor || accessor->isStatic || !accessor->isAbstract || !accessor->set) + { + continue; + } + + NodeFactory nf(NodeFactoryFlags::None); + + auto typeAlias = StringRef("." + newClassPtr->fullName.str() + "." + nameStr + ".accessor").copy(stringAllocator); + getTypeAliasMap()[typeAlias] = { accessor->set.funcType.getInput(1), undefined }; + + auto message = nf.createStringLiteral( + stows("Cannot set property " + nameStr + " of " + newClassPtr->name.str() + " which has only a getter")); + + NodeArray statements; + if (getClassInfoByFullName("TypeError")) + { + NodeArray arguments; + arguments.push_back(message); + statements.push_back(nf.createThrowStatement( + nf.createNewExpression(nf.createIdentifier(S("TypeError")), undefined, arguments))); + } + else + { + NodeArray arguments; + arguments.push_back(nf.createToken(SyntaxKind::FalseKeyword)); + arguments.push_back(message); + statements.push_back(nf.createExpressionStatement( + nf.createCallExpression(nf.createIdentifier(S("assert")), undefined, arguments))); + } + + NodeArray modifiers; + for (auto modifier : classMember.as()->modifiers) + { + if (modifier == SyntaxKind::PublicKeyword || modifier == SyntaxKind::ProtectedKeyword + || modifier == SyntaxKind::PrivateKeyword) + { + modifiers.push_back(modifier); + } + } + + newClassPtr->extraMembersPost.push_back(nf.createSetAccessorDeclaration( + modifiers, name, + {nf.createParameterDeclaration(undefined, undefined, nf.createIdentifier(S("value")), undefined, + nf.createTypeReferenceNode(nf.createIdentifier(stows(typeAlias.str())), undefined))}, + nf.createBlock(statements, /*multiLine*/ false))); + } + } + std::pair MLIRGenImpl::mlirGenClassDataFieldType(mlir::Location location, PropertyDeclaration propertyDeclaration, const GenContext &genContext) { @@ -3785,6 +3887,14 @@ genContext); funcGenContext.clearScopeVars(); funcGenContext.thisType = newClassPtr->classType; funcGenContext.thisClassType = newClassPtr->classType; + if (!classMethodMemberInfo.isStatic && !classMethodMemberInfo.isConstructor && !funcLikeDeclaration->type) + { + if (auto baseReturnType = overriddenNumericReturnType(newClassPtr, classMethodMemberInfo.methodName)) + { + funcGenContext.overriddenReturnType = baseReturnType; + funcGenContext.overriddenReturnFor = funcLikeDeclaration.operator->(); + } + } // `this` of a @value class: in the constructor the slot `new` made, whose fields it assigns // (the variable `this` is that slot: mlirGenFunctionParams); in a method or a getter the value // itself, a copy. A static member's `this` is the class. diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 8a113390e..7bb217ab8 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -587,6 +587,12 @@ namespace mlirgen auto returnType = getType(typeParameter, funcProtoGenContext); funcProto->setReturnType(returnType); } + else if (funcProtoGenContext.overriddenReturnType + && funcProtoGenContext.overriddenReturnFor == functionLikeDeclarationBaseAST.operator->() + && mth.isNumericType(funcProto->getReturnType())) + { + funcProto->setReturnType(funcProtoGenContext.overriddenReturnType); + } else if (funcProtoGenContext.receiverFuncType) { // rewrite ret type with actual value diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 041b90bb0..8d58a77dc 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7046,36 +7046,7 @@ class MLIRGenImpl return mlir::failure(); } - // A length is an integer in [0, 2^32 - 1] (TypeScript throws a RangeError). A number is - // checked here, before its conversion to an index drops a fraction and makes a negative - // or a NaN a huge size; an integer is checked against the upper bound where it is - // lowered (SetLengthOfOpLowering), which a negative one exceeds once sign-extended. A - // failed check stops the program as a failing assert does (#483). - if (isa(savingValue.getType())) - { - auto numberConstant = [&](double value) -> mlir::Value { -#ifdef NUMBER_F64 - return builder.create(location, getNumberType(), builder.getF64FloatAttr(value)); -#else - return builder.create(location, getNumberType(), builder.getF32FloatAttr(value)); -#endif - }; - - auto checkLength = [&](SyntaxKind opCode, mlir::Value left, mlir::Value right) { - auto holds = builder.create( - location, getBooleanType(), builder.getI32IntegerAttr((int)opCode), left, right); - builder.create(location, holds, mlir::Value(), - builder.getStringAttr("Invalid array length")); - }; - - checkLength(SyntaxKind::GreaterThanEqualsToken, savingValue, numberConstant(0)); - checkLength(SyntaxKind::LessThanEqualsToken, savingValue, numberConstant(4294967295.0)); - - // an integer survives the round trip through an index - CAST_A(asIndex, location, builder.getIndexType(), savingValue, genContext); - CAST_A(backToNumber, location, getNumberType(), asIndex, genContext); - checkLength(SyntaxKind::EqualsEqualsToken, backToNumber, savingValue); - } + EXIT_IF_FAILED(mlirGenArrayLengthCheck(location, savingValue, genContext)); // special case to resize array syncSavingValue(lengthOf.getResult().getType()); @@ -7813,6 +7784,101 @@ class MLIRGenImpl return (leftIsBoolean != rightIsBoolean) || (leftIsString != rightIsString) || (leftIsNumeric != rightIsNumeric); } + // A check TypeScript answers with a RangeError: `holds` false throws `new RangeError(message)`, which a + // `catch` can take, through `__range_check`, generated once from source so that the error object is + // made and given up as any `throw` makes it under every model. Without the default library there is + // no RangeError: a failed check stops the program as a failing assert does (#483). + mlir::LogicalResult mlirGenRangeCheck(mlir::Location location, mlir::Value holds, StringRef message, + const GenContext &genContext) + { + if (!getClassInfoByFullName("RangeError")) + { + builder.create(location, holds, mlir::Value(), builder.getStringAttr(message)); + return mlir::success(); + } + + // info, we add "_" extra as scanner append "_" in front of "__"; + auto funcName = "___range_check"; + if (!theModule.lookupSymbol(funcName)) + { + // see castPrimitiveTypeFromAny: the call site is the location until the call instantiates it + MLIRLocationGuard vgLoc(overwriteLoc); + overwriteLoc = location; + + if (mlir::failed(parsePartialStatements( + S("function __range_check(holds: boolean, message: string) {\n" + "if (!holds) throw new RangeError(message);\n}\n")))) + { + return mlir::failure(); + } + } + + auto funcResult = resolveIdentifier(location, funcName, genContext); + if (!funcResult) + { + return mlir::failure(); + } + + auto messageValue = builder.create(location, getStringType(), getStringAttr(message.str())); + SmallVector operands{holds, messageValue}; + auto result = mlirGenCallExpression(location, funcResult, {}, operands, genContext); + EXIT_IF_FAILED(result) + return mlir::success(); + } + + // A length - `a.length = n`, `new Array(n)` - is an integer in [0, 2^32 - 1]; any other is a RangeError + // (mlirGenRangeCheck). A number is checked before its conversion to an index drops a fraction and makes + // a negative or a NaN a huge size; a signed integer is checked for a negative, one wider than 32 bits + // for the upper bound too. The lowering checks what reaches it again (ArrayLayout), as a failing + // assert: an `index` count made by the compiler itself is not checked here. + mlir::LogicalResult mlirGenArrayLengthCheck(mlir::Location location, mlir::Value length, const GenContext &genContext) + { + auto checkLength = [&](SyntaxKind opCode, mlir::Value left, mlir::Value right) { + auto holds = builder.create( + location, getBooleanType(), builder.getI32IntegerAttr((int)opCode), left, right); + return mlirGenRangeCheck(location, holds, "Invalid array length", genContext); + }; + + auto type = length.getType(); + if (isa(type)) + { + auto numberConstant = [&](double value) -> mlir::Value { +#ifdef NUMBER_F64 + return builder.create(location, getNumberType(), builder.getF64FloatAttr(value)); +#else + return builder.create(location, getNumberType(), builder.getF32FloatAttr(value)); +#endif + }; + + EXIT_IF_FAILED(checkLength(SyntaxKind::GreaterThanEqualsToken, length, numberConstant(0))); + EXIT_IF_FAILED(checkLength(SyntaxKind::LessThanEqualsToken, length, numberConstant(4294967295.0))); + + // an integer survives the round trip through an index + CAST_A(asIndex, location, builder.getIndexType(), length, genContext); + CAST_A(backToNumber, location, getNumberType(), asIndex, genContext); + return checkLength(SyntaxKind::EqualsEqualsToken, backToNumber, length); + } + + if (auto intType = dyn_cast(type)) + { + auto intConstant = [&](int64_t value) -> mlir::Value { + return builder.create(location, intType, builder.getIntegerAttr(intType, value)); + }; + + if (!intType.isUnsigned()) + { + EXIT_IF_FAILED(checkLength(SyntaxKind::GreaterThanEqualsToken, length, intConstant(0))); + } + + if (intType.getWidth() > 32) + { + EXIT_IF_FAILED(checkLength(SyntaxKind::LessThanEqualsToken, length, intConstant(4294967295ll))); + } + } + + return mlir::success(); + } + // TODO: review it, seems like big hack mlir::LogicalResult adjustTypesForBinaryOp(mlir::Location location, SyntaxKind opCode, mlir::Value &leftExpressionValue, mlir::Value &rightExpressionValue, const GenContext &genContext) @@ -7887,23 +7953,22 @@ class MLIRGenImpl CAST(rightExpressionValue, location, getBigIntType(), rightExpressionValue, genContext); } - // TypeScript throws a RangeError for a bigint divided by 0n or raised to a negative power; - // a failed check stops the program as a failing assert does (#483), where the division - // was a hardware fault and a negative power was 1n. + // TypeScript throws a RangeError for a bigint divided by 0n or raised to a negative power + // (mlirGenRangeCheck), where the division was a hardware fault and a negative power was 1n. auto checkRight = [&](SyntaxKind checkCode, StringRef message) { auto zero = builder.create(location, getBigIntType(), builder.getI64IntegerAttr(0)); auto holds = builder.create( location, getBooleanType(), builder.getI32IntegerAttr((int)checkCode), rightExpressionValue, zero); - builder.create(location, holds, mlir::Value(), builder.getStringAttr(message)); + return mlirGenRangeCheck(location, holds, message, genContext); }; if (opCode == SyntaxKind::SlashToken || opCode == SyntaxKind::PercentToken) { - checkRight(SyntaxKind::ExclamationEqualsToken, "Division by zero"); + EXIT_IF_FAILED(checkRight(SyntaxKind::ExclamationEqualsToken, "Division by zero")); } else if (opCode == SyntaxKind::AsteriskAsteriskToken) { - checkRight(SyntaxKind::GreaterThanEqualsToken, "Exponent must be non-negative"); + EXIT_IF_FAILED(checkRight(SyntaxKind::GreaterThanEqualsToken, "Exponent must be non-negative")); } } @@ -10437,7 +10502,8 @@ class MLIRGenImpl { auto result = mlirGen(arguments.front(), genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) - count = V(result); + count = V(result); + EXIT_IF_FAILED(mlirGenArrayLengthCheck(location, count, genContext)); } else { @@ -13079,6 +13145,10 @@ class MLIRGenImpl void mlirGenClassFieldAccessorsForBase(ClassInfo::TypePtr newClassPtr, PropertyDeclaration propertyDeclaration); + mlir::Type overriddenNumericReturnType(ClassInfo::TypePtr classInfo, StringRef methodName); + + void mlirGenClassGetterOnlyForBase(ClassInfo::TypePtr newClassPtr, ClassLikeDeclaration classDeclarationAST); + mlir_ts::AccessLevel getAccessLevel(Node node) { return hasModifier(node, SyntaxKind::PrivateKeyword) ? mlir_ts::AccessLevel::Private diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index bafe08564..d6844db6a 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -606,6 +606,7 @@ tslang_add_test(NAME test-compile-00-class-discover-types COMMAND test-runner "$ tslang_add_test(NAME test-compile-00-class-accessor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor.ts") tslang_add_test(NAME test-compile-00-class-accessor-2 COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor2.ts") tslang_add_test(NAME test-compile-00-class-accessor-super COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_super.ts") +tslang_add_test(NAME test-compile-00-class-accessor-getter-only-abstract COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_getter_only_abstract.ts") tslang_add_test(NAME test-compile-00-class-accessor-virtual COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts") tslang_add_test(NAME test-compile-00-class-accessor-implements-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts") tslang_add_test(NAME test-compile-00-object-literal-contextual-lambda COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts") @@ -621,6 +622,7 @@ tslang_add_test(NAME test-compile-00-generic-default-no-inference COMMAND test-r tslang_add_test(NAME test-compile-00-promise-type COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00promise_type.ts") tslang_add_test(NAME test-compile-00-class-static-constructor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_static_constr.ts") tslang_add_test(NAME test-compile-00-class-abstract COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_abstract.ts") +tslang_add_test(NAME test-compile-00-class-override-inferred-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_override_inferred_return.ts") tslang_add_test(NAME test-compile-00-class-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_iface.ts") tslang_add_test(NAME test-compile-00-class-generic COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_generic.ts") tslang_add_test(NAME test-compile-00-class-generic-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_generic_iface.ts") @@ -739,6 +741,7 @@ tslang_add_test(NAME test-compile-00-try-finally-return COMMAND test-runner "${P tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") tslang_add_test(NAME test-compile-00-try-finally-break-continue COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_break_continue.ts") tslang_add_test(NAME test-compile-00-try-catch-rethrow COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_rethrow.ts") +tslang_add_test(NAME test-compile-00-try-catch-accessor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_accessor.ts") tslang_add_test(NAME test-compile-00-try-catch-mismatch-rethrow COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_mismatch_rethrow.ts") tslang_add_test(NAME test-compile-00-try-catch-return-dispose COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return_dispose.ts") tslang_add_test(NAME test-compile-01-try-catch-return-dispose COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_catch_return_dispose.ts") @@ -1228,6 +1231,7 @@ tslang_add_test(NAME test-jit-00-class-discover-types COMMAND test-runner -jit " tslang_add_test(NAME test-jit-00-class-accessor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor.ts") tslang_add_test(NAME test-jit-00-class-accessor-2 COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor2.ts") tslang_add_test(NAME test-jit-00-class-accessor-super COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_super.ts") +tslang_add_test(NAME test-jit-00-class-accessor-getter-only-abstract COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_getter_only_abstract.ts") tslang_add_test(NAME test-jit-00-class-accessor-virtual COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts") tslang_add_test(NAME test-jit-00-class-accessor-implements-field COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts") tslang_add_test(NAME test-jit-00-object-literal-contextual-lambda COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_literal_contextual_lambda.ts") @@ -1243,6 +1247,7 @@ tslang_add_test(NAME test-jit-00-callback-result-ignored COMMAND test-runner -ji tslang_add_test(NAME test-jit-00-generic-default-no-inference COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generic_default_no_inference.ts") tslang_add_test(NAME test-jit-00-promise-type COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00promise_type.ts") tslang_add_test(NAME test-jit-00-class-abstract COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_abstract.ts") +tslang_add_test(NAME test-jit-00-class-override-inferred-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_override_inferred_return.ts") tslang_add_test(NAME test-jit-00-class-interface COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_iface.ts") tslang_add_test(NAME test-jit-00-class-generic COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_generic.ts") tslang_add_test(NAME test-jit-00-class-generic-interface COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_generic_iface.ts") @@ -1359,6 +1364,7 @@ tslang_add_test(NAME test-jit-00-try-finally-return COMMAND test-runner -jit "${ tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") tslang_add_test(NAME test-jit-00-try-finally-break-continue COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_break_continue.ts") tslang_add_test(NAME test-jit-00-try-catch-rethrow COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_rethrow.ts") +tslang_add_test(NAME test-jit-00-try-catch-accessor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_accessor.ts") # pre-existing JIT limitation (reproduces on unmodified main too): the JIT's # Windows SEH landing pad/personality plumbing exits with code 3 and no # output on a typed-catch mismatch that must unwind past a function boundary, @@ -2187,8 +2193,10 @@ set(TSLANG_CORPUS 00catch_value.ts 00catch_value_minimal.ts 00class_abstract.ts + 00class_override_inferred_return.ts 00class_access_control.ts 00class_accessor_super.ts + 00class_accessor_getter_only_abstract.ts 00class_accessor_virtual.ts 00class_accessor_implements_field.ts 00object_literal_contextual_lambda.ts @@ -2457,6 +2465,7 @@ set(TSLANG_CORPUS 00toplevel_no_main_with_helpers.ts 00try_catch_mismatch_rethrow.ts 00try_catch_rethrow.ts + 00try_catch_accessor.ts 00try_catch_return_dispose.ts 00try_catch_return.ts 00try_catch_sequence_and_nesting.ts @@ -5073,7 +5082,7 @@ set_tests_properties(test-jit-assert-message-failing FAIL_REGULAR_EXPRESSION "Stack dump|unlinked") # An invalid array length stops the program with a message, after the output printed before it, -# under every model (#483). The JIT reports it itself on every platform, as for a failing assert. +# under every model (#483), when there is no default library: with one it throws a RangeError. The JIT reports it itself on every platform, as for a failing assert. foreach(array_length_name negative huge fraction negative_integer new_negative) foreach(array_length_model gc rc none own) add_test(NAME test-jit-${array_length_model}-array-length-${array_length_name} @@ -5087,7 +5096,8 @@ foreach(array_length_name negative huge fraction negative_integer new_negative) endforeach() # A bigint divided by 0n or raised to a negative power stops the program with a message, after the -# output printed before it, under every model: TypeScript throws a RangeError. +# output printed before it, under every model, when there is no default library: with one it throws a +# RangeError a `catch` takes (DefaultLib's range_error_caught). foreach(bigint_range_name division remainder power) if(bigint_range_name STREQUAL "power") set(bigint_range_message "Exponent must be non-negative") diff --git a/tslang/test/tester/tests/00bigint_ops.ts b/tslang/test/tester/tests/00bigint_ops.ts index dcaf19bb0..e8983b539 100644 --- a/tslang/test/tester/tests/00bigint_ops.ts +++ b/tslang/test/tester/tests/00bigint_ops.ts @@ -2,7 +2,7 @@ // so `x ?? 7n` of an optional bigint is a bigint (it was `bigint | i64`, and the null test an i64 against a // pointer), and `5n` given for `bigint | string` is its bigint member (an invalid cast). `/`, `%`, shifts // and bitwise operators stay 64-bit integers: `10n / 3n` was 3.33333 through a number, and `1n << 40n` -// shifted by 40 mod 32 through an i32. A division by 0n or a negative power stops the program (RangeError). +// shifted by 40 mod 32 through an i32. A division by 0n or a negative power throws a RangeError. function orSeven(x?: bigint) { return x ?? 7n; } diff --git a/tslang/test/tester/tests/00class_accessor_getter_only_abstract.ts b/tslang/test/tester/tests/00class_accessor_getter_only_abstract.ts new file mode 100644 index 000000000..2c15e9b7d --- /dev/null +++ b/tslang/test/tester/tests/00class_accessor_getter_only_abstract.ts @@ -0,0 +1,35 @@ +// A getter alone implements an abstract field (`abstract name: T`), as TypeScript allows: a read through the base +// calls it. The field's setter slot gets a setter that throws a TypeError, as JavaScript's write to a property with +// only a getter does (a failing assert without the default library). It was an error naming a missing 'set_name'. +abstract class Shape { + abstract name: string; + abstract readonly sides: number; + + describe() { + return this.name + " " + this.sides; + } +} + +class Triangle extends Shape { + get name() { return "triangle"; } + get sides() { return 3; } +} + +class Square extends Shape { + private n = "square"; + get name() { return this.n; } + set name(v: string) { this.n = v; } + get sides() { return 4; } +} + +function main() { + const t: Shape = new Triangle(); + assert(t.name == "triangle" && t.sides == 3, "read through the base"); + assert(t.describe() == "triangle 3", "read through this"); + + const s: Shape = new Square(); + s.name = "box"; + assert(s.describe() == "box 4", "a getter and a setter"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00class_override_inferred_return.ts b/tslang/test/tester/tests/00class_override_inferred_return.ts new file mode 100644 index 000000000..3600a7ac7 --- /dev/null +++ b/tslang/test/tester/tests/00class_override_inferred_return.ts @@ -0,0 +1,36 @@ +// A method or getter overriding one that returns a number, with no return type of its own, returns the base's type: +// `f() { return 3; }` infers s32 (an integer literal), and its vtable slot, called as the base's `f(): number`, +// read 0 through the base. +abstract class Shape { + abstract area(): number; + abstract get sides(): number; + abstract readonly corners: number; + + scale(): number { + return 1.5; + } +} + +class Square extends Shape { + area() { return 4; } + get sides() { return 4; } + get corners() { return 4; } + override scale() { return 2; } +} + +class Big extends Square { + override area() { return 16; } +} + +function main() { + const s: Shape = new Square(); + assert(s.area() == 4 && s.sides == 4 && s.corners == 4 && s.scale() == 2, "through the base"); + + const q = new Square(); + assert(q.area() == 4 && q.scale() == 2, "through the class"); + + const b: Shape = new Big(); + assert(b.area() == 16 && b.sides == 4, "two levels down"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00try_catch_accessor.ts b/tslang/test/tester/tests/00try_catch_accessor.ts new file mode 100644 index 000000000..c02d0f437 --- /dev/null +++ b/tslang/test/tester/tests/00try_catch_accessor.ts @@ -0,0 +1,86 @@ +// An accessor that throws inside `try` is caught there: its call is lowered after the `try`, which recorded only +// the calls and throws already in its body, so a get or set reached the caller uncaught. +class Fail { + constructor(public where: string) {} +} + +class A { + private n = 1; + get v() { if (this.n < 0) throw new Fail("get"); return this.n; } + set v(x: number) { if (x < 0) throw new Fail("set"); this.n = x; } + + static get s() { throw new Fail("static get"); return 0; } + static set s(x: number) { throw new Fail("static set"); } +} + +class B extends A { + override get v() { return super.v + 100; } + override set v(x: number) { super.v = x; } +} + +abstract class Shape { + abstract size: number; +} + +class Square extends Shape { + get size() { throw new Fail("abstract get"); return 0; } + set size(v: number) { throw new Fail("abstract set"); } +} + +function caught(f: () => void) { + try { + f(); + } catch (e: Fail) { + return e.where; + } + + return ""; +} + +function main() { + const a = new A(); + let where = ""; + try { a.v = -1; } catch (e: Fail) { where = e.where; } + assert(where == "set", "set"); + + a.v = 5; + assert(a.v == 5, "a set that does not throw"); + + where = ""; + try { a.v = -2; print("not reached"); } catch (e: Fail) { where = e.where; } + assert(where == "set" && a.v == 5, "set, the statement after it skipped"); + + where = ""; + try { A.s = 1; } catch (e: Fail) { where = e.where; } + assert(where == "static set", "static set"); + + where = ""; + try { print(A.s); } catch (e: Fail) { where = e.where; } + assert(where == "static get", "static get"); + + const b: A = new B(); + where = ""; + try { b.v = -1; } catch (e: Fail) { where = e.where; } + assert(where == "set", "virtual set"); + + const shape: Shape = new Square(); + where = ""; + try { print(shape.size); } catch (e: Fail) { where = e.where; } + assert(where == "abstract get", "get through an abstract field"); + where = ""; + try { shape.size = 1; } catch (e: Fail) { where = e.where; } + assert(where == "abstract set", "set through an abstract field"); + + // a finally still runs + let finallyRan = false; + try { + try { a.v = -3; } finally { finallyRan = true; } + } catch (e: Fail) { + where = e.where; + } + assert(finallyRan && where == "set", "finally"); + + assert(caught(() => { a.v = -4; }) == "set", "in a function"); + + print("done."); +}