diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 2cbae5c0d..32cd64219 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1868,6 +1868,225 @@ namespace mlirgen return mlirGenCall(location, actualFuncRefValue, operands, genContext); } + // How well an argument fits a parameter of an overload (resolveCppOverload, + // resolveConstructorOverload): 3 its type, 2 an integer for an integer or a float for a float, or + // a derived class for a base class, 1 any other conversion, 0 none + int MLIRGenImpl::overloadArgumentFit(mlir::Location location, mlir::Type argType, mlir::Type paramType) + { + // whether derivedClass is baseClass or derives from it + std::function isOrDerivesFrom = + [&](mlir_ts::ClassType derivedClass, mlir_ts::ClassType baseClass) { + if (derivedClass == baseClass) + { + return true; + } + + auto derivedInfo = getClassInfoByFullName(derivedClass.getName().getValue()); + return derivedInfo && llvm::any_of(derivedInfo->baseClasses, [&](ClassInfo::TypePtr base) { + return isOrDerivesFrom(base->classType, baseClass); + }); + }; + + if (argType == paramType) + { + return 3; + } + + auto literalType = dyn_cast(argType); + auto baseType = literalType ? literalType.getElementType() : argType; + // `number` is a C `double`, as f64 is + auto isDouble = [](mlir::Type type) { return isa(type) || type.isF64(); }; + if (baseType == paramType || (isDouble(baseType) && isDouble(paramType))) + { + return 3; + } + + // a class is a C++ pointer, and `T | null` the same pointer: a `T` fits it as `T` does, + // and a class derived from T as a derived-to-base conversion + if (auto argClass = dyn_cast(baseType)) + { + auto classFit = [&](mlir::Type type) { + auto paramClass = dyn_cast(type); + return !paramClass ? 0 : argClass == paramClass ? 3 : isOrDerivesFrom(argClass, paramClass) ? 2 : 0; + }; + + auto classBest = classFit(paramType); + if (auto unionType = dyn_cast(paramType)) + { + for (auto member : unionType.getTypes()) + { + classBest = std::max(classBest, classFit(member)); + } + } + + if (classBest) + { + return classBest; + } + } + + // an integer for an integer, a float for a float, before a conversion between the two + // (C++ ranks a promotion or an integral conversion above a floating-integral one) + auto isFloat = [&](mlir::Type type) { return isDouble(type) || isa(type); }; + if ((isa(baseType) && isa(paramType)) || (isFloat(baseType) && isFloat(paramType))) + { + return 2; + } + + if ((isPromotableNumeric(baseType) && isPromotableNumeric(paramType)) || mth.canCastFromTo(location, baseType, paramType)) + { + return 1; + } + + return 0; + } + + // `new C(...)` of a class with constructor overloads (mlirGenClassConstructorOverloadNames): the + // name of the one the arguments fit best, by their types before they are generated - an argument + // is generated for its parameter's type (an array literal for T[]), so the parameters have to be + // known first. A tie goes to the overload declared first, as `new C()` of two whose parameters + // all have defaults does; an empty name, with an error, when none fits. CONSTRUCTOR_NAME for a + // class with one constructor, or when an argument's type can't be known here. + std::string MLIRGenImpl::resolveConstructorOverload(mlir::Location location, ClassInfo::TypePtr classInfo, + NodeArray arguments, const GenContext &genContext) + { + SmallVector candidates; + for (auto [index, method] : llvm::enumerate(classInfo->methods)) + { + if (!method.isStatic && cppOverloadedName(method.name) == CONSTRUCTOR_NAME) + { + candidates.push_back(static_cast(index)); + } + } + + if (candidates.size() < 2) + { + return CONSTRUCTOR_NAME; + } + + // the declaration order: `constructor`, `constructor#1`, ... + auto overloadIndex = [&](int methodIndex) { + auto suffix = StringRef(classInfo->methods[methodIndex].name).split(CPP_OVERLOAD_SEPARATOR).second; + auto value = 0; + return suffix.getAsInteger(10, value) ? 0 : value; + }; + + llvm::sort(candidates, [&](int left, int right) { return overloadIndex(left) < overloadIndex(right); }); + + // a function argument is typed by its parameter, and a spread has no count: neither tells + SmallVector argumentTypes; + for (auto argument : arguments) + { + if (argument == SyntaxKind::SpreadElement || argument == SyntaxKind::ArrowFunction + || argument == SyntaxKind::FunctionExpression) + { + return CONSTRUCTOR_NAME; + } + + auto type = evaluate(argument, genContext); + if (!type) + { + return CONSTRUCTOR_NAME; + } + + argumentTypes.push_back(type); + } + + auto bestScore = -1; + auto best = -1; + for (auto candidate : candidates) + { + auto &method = classInfo->methods[candidate]; + auto funcType = method.declaredFuncType ? method.declaredFuncType : method.funcType; + // input 0 is `this` + auto params = funcType.getInputs().drop_front(); + auto isVarArg = funcType.isVarArg() && !params.empty(); + auto fixedParams = isVarArg ? params.drop_back() : params; + if (!isVarArg && argumentTypes.size() > params.size()) + { + continue; + } + + auto score = 0; + auto fits = true; + for (auto [index, param] : llvm::enumerate(fixedParams)) + { + if (index >= argumentTypes.size()) + { + // a parameter left out has to take `undefined` + fits &= isa(param); + continue; + } + + auto argFit = overloadArgumentFit(location, argumentTypes[index], param); + fits &= argFit > 0; + score += argFit; + } + + if (isVarArg) + { + auto restType = params.back(); + if (auto arrayType = dyn_cast(restType)) + { + restType = arrayType.getElementType(); + } + + for (auto index = fixedParams.size(); index < argumentTypes.size(); index++) + { + auto argFit = overloadArgumentFit(location, argumentTypes[index], restType); + fits &= argFit > 0; + score += argFit; + } + } + + // the first declared wins a tie + if (fits && score > bestScore) + { + bestScore = score; + best = candidate; + } + } + + if (best < 0) + { + // a partial resolve may not know the arguments' types yet: the full one reports it + if (genContext.allowPartialResolve) + { + return CONSTRUCTOR_NAME; + } + + auto diagnostic = emitError(location); + diagnostic << "no constructor of '" << classInfo->name << "' takes these arguments ("; + for (auto [index, type] : llvm::enumerate(argumentTypes)) + { + if (auto literalType = dyn_cast(type)) + { + type = literalType.getElementType(); + } + + diagnostic << (index ? ", " : "") << to_print(type); + } + + diagnostic << "); it has:"; + for (auto candidate : candidates) + { + auto &method = classInfo->methods[candidate]; + auto funcType = method.declaredFuncType ? method.declaredFuncType : method.funcType; + diagnostic << "\n constructor("; + for (auto [index, param] : llvm::enumerate(funcType.getInputs().drop_front())) + { + diagnostic << (index ? ", " : "") << to_print(param); + } + + diagnostic << ")"; + } + + return std::string(); + } + + return classInfo->methods[best].name; + } + // A call of a C++ overloaded method of a @cpp class (mlirGenClassCppOverloadNames): the member // access found the first method of that name; this picks the one the arguments fit best, from // the class and its bases, as C++ would at compile time. funcRefValue itself for any other @@ -1960,76 +2179,7 @@ namespace mlirgen return funcRefValue; } - // whether derivedClass is baseClass or derives from it - std::function isOrDerivesFrom = - [&](mlir_ts::ClassType derivedClass, mlir_ts::ClassType baseClass) { - if (derivedClass == baseClass) - { - return true; - } - - auto derivedInfo = getClassInfoByFullName(derivedClass.getName().getValue()); - return derivedInfo && llvm::any_of(derivedInfo->baseClasses, [&](ClassInfo::TypePtr base) { - return isOrDerivesFrom(base->classType, baseClass); - }); - }; - - // how well an argument fits a parameter: 3 its type, 2 an integer for an integer or a float - // for a float, or a derived class for a base class, 1 any other conversion, 0 none - auto fit = [&](mlir::Type argType, mlir::Type paramType) -> int { - if (argType == paramType) - { - return 3; - } - - auto literalType = dyn_cast(argType); - auto baseType = literalType ? literalType.getElementType() : argType; - // `number` is a C `double`, as f64 is - auto isDouble = [](mlir::Type type) { return isa(type) || type.isF64(); }; - if (baseType == paramType || (isDouble(baseType) && isDouble(paramType))) - { - return 3; - } - - // a class is a C++ pointer, and `T | null` the same pointer: a `T` fits it as `T` does, - // and a class derived from T as a derived-to-base conversion - if (auto argClass = dyn_cast(baseType)) - { - auto classFit = [&](mlir::Type type) { - auto paramClass = dyn_cast(type); - return !paramClass ? 0 : argClass == paramClass ? 3 : isOrDerivesFrom(argClass, paramClass) ? 2 : 0; - }; - - auto classBest = classFit(paramType); - if (auto unionType = dyn_cast(paramType)) - { - for (auto member : unionType.getTypes()) - { - classBest = std::max(classBest, classFit(member)); - } - } - - if (classBest) - { - return classBest; - } - } - - // an integer for an integer, a float for a float, before a conversion between the two - // (C++ ranks a promotion or an integral conversion above a floating-integral one) - auto isFloat = [&](mlir::Type type) { return isDouble(type) || isa(type); }; - if ((isa(baseType) && isa(paramType)) || (isFloat(baseType) && isFloat(paramType))) - { - return 2; - } - - if ((isPromotableNumeric(baseType) && isPromotableNumeric(paramType)) || mth.canCastFromTo(location, baseType, paramType)) - { - return 1; - } - - return 0; - }; + auto fit = [&](mlir::Type argType, mlir::Type paramType) { return overloadArgumentFit(location, argType, paramType); }; auto bestScore = -1; SmallVector best; @@ -2551,7 +2701,8 @@ namespace mlirgen mlir::LogicalResult MLIRGenImpl::mlirGenCallConstructor(mlir::Location location, ClassInfo::TypePtr classInfo, mlir::Value thisValue, SmallVector &operands, - bool castThisValueToClass, const GenContext &genContext) + bool castThisValueToClass, const GenContext &genContext, + const std::string &constructorName) { assert(classInfo); @@ -2577,7 +2728,7 @@ namespace mlirgen } auto propAccess = - mlirGenPropertyAccessExpression(location, effectiveThisValue, CONSTRUCTOR_NAME, false, genContext); + mlirGenPropertyAccessExpression(location, effectiveThisValue, constructorName, false, genContext); if (!propAccess && !genContext.allowPartialResolve) { @@ -2673,7 +2824,15 @@ namespace mlirgen GenContext thisTypeGenContext(genContext); thisTypeGenContext.thisType = mlir::cast(newOp.getType()); - auto funcValueRef = evaluateProperty(location, newOp, CONSTRUCTOR_NAME, thisTypeGenContext); + // with constructor overloads, the one the arguments pick: they are generated for its + // parameters + auto constructorName = resolveConstructorOverload(location, classInfo, arguments, genContext); + if (constructorName.empty()) + { + return mlir::failure(); + } + + auto funcValueRef = evaluateProperty(location, newOp, constructorName, thisTypeGenContext); if (funcValueRef) { SmallVector operands; @@ -2684,7 +2843,7 @@ namespace mlirgen } assert(newOp); - auto result = mlirGenCallConstructor(location, classInfo, newOp, operands, false, genContext); + auto result = mlirGenCallConstructor(location, classInfo, newOp, operands, false, genContext, constructorName); EXIT_IF_FAILED(result) } } diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 7266ff6ff..94a457abd 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -221,6 +221,8 @@ namespace mlirgen mlirGenClassCppOverloadNames(classDeclarationAST, newClassPtr, classGenContext); } + mlirGenClassConstructorOverloadNames(classDeclarationAST); + if (mlir::failed(mlirGenClassCppVTableCheck(location, classDeclarationAST, newClassPtr, classGenContext))) { setProcessingState(newClassPtr, ProcessingStages::ErrorInStorageClass, genContext); @@ -575,6 +577,38 @@ namespace mlirgen } } + // Constructor overloads: a class may implement several constructors, each a function of its own. + // The first is `constructor`, as with one, so whatever looks the constructor up by name (super + // calls, a default constructor, a cast) finds it; any other is renamed `constructor#1`, + // `constructor#2`, ... as C++ overloads are, and `new` picks one by its arguments + // (resolveConstructorOverload). Run again on the same declaration (a specialization of a generic + // class, an import), it leaves the names as they are. + void MLIRGenImpl::mlirGenClassConstructorOverloadNames(ClassLikeDeclaration classDeclarationAST) + { + NodeFactory nf(NodeFactoryFlags::None); + auto index = 0; + for (auto &classMember : classDeclarationAST->members) + { + // an overload signature (no body) is a type only, not a constructor of its own + if (classMember != SyntaxKind::Constructor || hasModifier(classMember, SyntaxKind::StaticKeyword) + || !classMember.as()->body) + { + continue; + } + + auto constructorDeclaration = classMember.as(); + if (index++ == 0 || constructorDeclaration->name) + { + continue; + } + + auto renamed = nf.createIdentifier(stows(std::string(CONSTRUCTOR_NAME CPP_OVERLOAD_SEPARATOR) + std::to_string(index - 1))); + renamed->pos = constructorDeclaration->pos; + renamed->_end = constructorDeclaration->_end; + constructorDeclaration->name = renamed; + } + } + // The name a C++ overload was declared with: `write#1` is `write` StringRef MLIRGenImpl::cppOverloadedName(StringRef methodName) { @@ -1805,6 +1839,12 @@ namespace mlirgen isPrivate |= strAttr.getValue().starts_with("#"); } + // a field of another constructor overload's parameter property already + if (llvm::any_of(fieldInfos, [&](mlir_ts::FieldInfo &fieldInfo) { return fieldInfo.id == fieldId; })) + { + continue; + } + auto layoutField = valueLayoutField(newClassPtr->isValue, newClassPtr->fullName, newClassPtr->name, loc(parameter), MLIRHelper::getName(parameter->name)); auto [type, init, typeProvided] = evaluateTypeAndInit(parameter, genContext); @@ -3427,7 +3467,7 @@ genContext); } // adding missing statements - generateConstructorStatements(classDeclarationAST, classMethodMemberInfo.isStatic, funcGenContext); + generateConstructorStatements(classDeclarationAST, classMethodMemberInfo.isStatic, classMember, funcGenContext); } // process dynamic import @@ -3616,7 +3656,7 @@ genContext); } mlir::LogicalResult MLIRGenImpl::generateConstructorStatements(ClassLikeDeclaration classDeclarationAST, bool staticConstructor, - const GenContext &genContext) + ClassElement constructorMember, const GenContext &genContext) { NodeFactory nf(NodeFactoryFlags::None); @@ -3677,7 +3717,9 @@ genContext); const_cast(genContext).generatedStatements.push_back(expr_statement.as()); } - if (classMember == SyntaxKind::Constructor) + // the parameter properties of this constructor only: another overload's parameters + // aren't in scope here (`this.data = data` in `constructor(count: int)`) + if (classMember == SyntaxKind::Constructor && classMember == constructorMember) { if (isStatic != staticConstructor) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 48760fd72..25b879f81 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -10032,7 +10032,8 @@ class MLIRGenImpl mlir::LogicalResult mlirGenCallConstructor(mlir::Location location, ClassInfo::TypePtr classInfo, mlir::Value thisValue, SmallVector &operands, - bool castThisValueToClass, const GenContext &genContext); + bool castThisValueToClass, const GenContext &genContext, + const std::string &constructorName = CONSTRUCTOR_NAME); // TODO: refactor it, somehow when NewClassInstanceAsMethodCallOp calling Ctor and NewClassInstanceLogicAsOp is not ValueOrLogicalResult NewClassInstance(mlir::Location location, mlir::Value value, NodeArray arguments, @@ -12478,11 +12479,18 @@ class MLIRGenImpl void mlirGenClassCppOverloadNames(ClassLikeDeclaration classDeclarationAST, ClassInfo::TypePtr newClassPtr, const GenContext &genContext); + void mlirGenClassConstructorOverloadNames(ClassLikeDeclaration classDeclarationAST); + static StringRef cppOverloadedName(StringRef methodName); mlir::Value resolveCppOverload(mlir::Location location, mlir::Value funcRefValue, mlir::ArrayRef operands, const GenContext &genContext); + int overloadArgumentFit(mlir::Location location, mlir::Type argType, mlir::Type paramType); + + std::string resolveConstructorOverload(mlir::Location location, ClassInfo::TypePtr classInfo, + NodeArray arguments, const GenContext &genContext); + mlir::Value cppMethodAccessAgain(mlir::Location location, mlir::Value optFuncRefValue, mlir::Value funcRefValue, const GenContext &genContext); @@ -13319,7 +13327,7 @@ class MLIRGenImpl mlir::LogicalResult createGlobalConstructor(ClassElement classMember, const GenContext &genContext); mlir::LogicalResult generateConstructorStatements(ClassLikeDeclaration classDeclarationAST, bool staticConstructor, - const GenContext &genContext); + ClassElement constructorMember, const GenContext &genContext); bool isConstValue(Expression expr, const GenContext &genContext) { diff --git a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp index 0c83149fd..348dd32ed 100644 --- a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp +++ b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp @@ -1664,7 +1664,8 @@ namespace mlirgen } else { - methodName = std::string(CONSTRUCTOR_NAME); + // a constructor overload after the first is `constructor#N` (mlirGenClassConstructorOverloadNames) + methodName = methodSignature->name ? MLIRHelper::getName(methodSignature->name) : std::string(CONSTRUCTOR_NAME); } } else if (kind == SyntaxKind::ConstructSignature) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 3e7c359bc..f8ee97ae6 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -611,6 +611,7 @@ tslang_add_test(NAME test-compile-00-class-implicit-constructor COMMAND test-run tslang_add_test(NAME test-compile-00-class-super-static COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_super_static.ts") tslang_add_test(NAME test-compile-00-class-default-constructor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_def_constr.ts") tslang_add_test(NAME test-compile-00-class-constructor-fields COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_constr_fields.ts") +tslang_add_test(NAME test-compile-00-class-constructor-overloads COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_constructor_overloads.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-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_iface.ts") @@ -1216,6 +1217,7 @@ tslang_add_test(NAME test-jit-00-class-super-static COMMAND test-runner -jit "${ tslang_add_test(NAME test-jit-00-class-default-constructor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_def_constr.ts") tslang_add_test(NAME test-jit-00-class-static-constructor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_static_constr.ts") tslang_add_test(NAME test-jit-00-class-constructor-fields COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_constr_fields.ts") +tslang_add_test(NAME test-jit-00-class-constructor-overloads COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_constructor_overloads.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-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") @@ -2155,6 +2157,7 @@ set(TSLANG_CORPUS 00class_accessor.ts 00class_accessor2.ts 00class_constr_fields.ts + 00class_constructor_overloads.ts 00class_deconst.ts 00class_def_constr.ts 00class_discover_types.ts diff --git a/tslang/test/tester/tests/00class_constructor_overloads.ts b/tslang/test/tester/tests/00class_constructor_overloads.ts new file mode 100644 index 000000000..5630689c0 --- /dev/null +++ b/tslang/test/tester/tests/00class_constructor_overloads.ts @@ -0,0 +1,58 @@ +// Constructor overloads: a class may implement several constructors, and `new` picks one by its +// arguments. The parameter properties of one constructor are not assigned in another (`this.data = +// data` in `constructor(count: int)` was "can't resolve name: data"), and a tie - `new A()` of two +// constructors whose parameters all have defaults - goes to the one declared first. + +class A { + constructor(private data: T[] = []) { + } + + constructor(count: int = 0) { + this.data = []; + this.data.length = count; + } + + get length() { + return this.data.length; + } +} + +class B { + private s: string; + private n = 7; + + constructor(s: string = "x") { + this.s = s; + } + + constructor(count: int, extra: string) { + this.s = extra; + this.n = count; + } + + get v() { + return this.s; + } + + get k() { + return this.n; + } +} + +function main() { + const a0 = new A(); + const a1 = new A(10); + const a2 = new A([1, 2]); + assert(a0.length == 0); + assert(a1.length == 10); + assert(a2.length == 2); + + const b0 = new B(); + const b1 = new B("q"); + const b2 = new B(3, "e"); + assert(b0.v == "x" && b0.k == 7); + assert(b1.v == "q" && b1.k == 7); + assert(b2.v == "e" && b2.k == 3); + + print("done."); +}