[ConstraintSystem] C++ Interop: Binding a string literal to std.string shouldn't increase the score

Since this is a C++ stdlib type we need make sure that any overloads
that use it are preferred over custom types that also conform to
`ExpressibleByStringLiteral` when argument is a string literal.

This is important for operators like `==` which could be heterogenous
and have a custom C++ type that conforms to `ExpressibleByStringLiteral`
on either side together with `std.string` i.e.
`==(std.string, const CustomString &)`, such overloads should only
be selected if argument passed to `CustomString` is non-literal because
literals are convered by a stdlib `==(std.string, std.string)` overload.
This commit is contained in:
Pavel Yaskevich
2025-07-24 00:45:11 -07:00
parent 2e8f74f011
commit cd9c37cac6
6 changed files with 75 additions and 4 deletions

View File

@@ -34,6 +34,7 @@ IDENTIFIER(Any)
IDENTIFIER(ArrayLiteralElement)
IDENTIFIER(asLocalActor)
IDENTIFIER(atIndexedSubscript)
IDENTIFIER(basic_string)
IDENTIFIER_(bridgeToObjectiveC)
IDENTIFIER(buildArray)
IDENTIFIER(buildBlock)

View File

@@ -1094,6 +1094,9 @@ public:
/// on macOS or Foundation on Linux.
bool isCGFloat();
/// Check if this is a std.string type from C++.
bool isCxxString();
/// Check if this is either an Array, Set or Dictionary collection type defined
/// at the top level of the Swift module
bool isKnownStdlibCollectionType();

View File

@@ -43,6 +43,7 @@
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Compiler.h"
#include "clang/AST/DeclCXX.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
@@ -1280,6 +1281,21 @@ bool TypeBase::isCGFloat() {
NTD->getName().is("CGFloat");
}
bool TypeBase::isCxxString() {
auto *nominal = getAnyNominal();
if (!nominal)
return false;
auto *clangDecl =
dyn_cast_or_null<clang::CXXRecordDecl>(nominal->getClangDecl());
if (!clangDecl)
return false;
auto &ctx = nominal->getASTContext();
return clangDecl->isInStdNamespace() && clangDecl->getIdentifier() &&
ctx.Id_basic_string.is(clangDecl->getName());
}
bool TypeBase::isKnownStdlibCollectionType() {
if (isArray() || isDictionary() || isSet()) {
return true;

View File

@@ -256,11 +256,28 @@ void ConstraintSystem::assignFixedType(TypeVariableType *typeVar, Type type,
// If the protocol has a default type, check it.
if (auto defaultType = TypeChecker::getDefaultType(literalProtocol, DC)) {
// Check whether the nominal types match. This makes sure that we
// properly handle Array vs. Array<T>.
if (defaultType->getAnyNominal() != type->getAnyNominal()) {
auto isDefaultType = [&literalProtocol, &defaultType](Type type) {
// Treat `std.string` as a default type just like we do
// Swift standard library `String`. This helps to disambiguate
// operator overloads that use `std.string` vs. a custom C++
// type that conforms to `ExpressibleByStringLiteral` as well.
//
// This doesn't clash with String because inference won't attempt
// C++ types unless we discover them from a constraint and the
// optimizer and old hacks always prefer the actual default type.
if (literalProtocol->getKnownProtocolKind() ==
KnownProtocolKind::ExpressibleByStringLiteral &&
type->isCxxString()) {
return true;
}
// Check whether the nominal types match. This makes sure that we
// properly handle Array vs. Array<T>.
return defaultType->getAnyNominal() == type->getAnyNominal();
};
if (!isDefaultType(type))
increaseScore(SK_NonDefaultLiteral, locator);
}
}
break;

View File

@@ -6,3 +6,15 @@ struct HasMethodThatReturnsString {
};
inline std::string takesStringWithDefaultArg(std::string s = "abc") { return s; }
struct StringBox {
std::string value;
friend bool operator==(const StringBox &lhs, const std::string &rhs) {
return lhs.value == rhs;
}
friend bool operator==(const std::string &lhs, const StringBox &rhs) {
return rhs == lhs;
}
};

View File

@@ -0,0 +1,22 @@
// RUN: %target-swift-emit-silgen -verify -I %S/Inputs -cxx-interoperability-mode=upcoming-swift %s | %FileCheck %s
import CxxStdlib
import StdString
extension StringBox: @retroactive ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.value = std.string(value)
}
}
// CHECK-LABEL: sil hidden [ossa] @$s4main4testyyF
// CHECK: // function_ref static std{{.*}}basic_string<CChar, std{{.*}}char_traits<CChar>, std{{.*}}allocator<CChar>>.== infix(_:_:)
// CHECK: // function_ref static std{{.*}}basic_string<CChar, std{{.*}}char_traits<CChar>, std{{.*}}allocator<CChar>>.== infix(_:_:)
// CHECK: // function_ref static String.== infix(_:_:)
// CHECK: } // end sil function '$s4main4testyyF'
func test() {
let cxxString: std.string = ""
let _ = cxxString == "def" // Ok
let _ = "def" == cxxString // Ok
let _ = "def" == "hello" // Ok
}