Skip to content

[cxx-interop] Add CxxVector protocol #67772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/swift/AST/KnownProtocols.def
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ PROTOCOL(CxxSet)
PROTOCOL(CxxRandomAccessCollection)
PROTOCOL(CxxSequence)
PROTOCOL(CxxUniqueSet)
PROTOCOL(CxxVector)
PROTOCOL(UnsafeCxxInputIterator)
PROTOCOL(UnsafeCxxMutableInputIterator)
PROTOCOL(UnsafeCxxRandomAccessIterator)
Expand Down
1 change: 1 addition & 0 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,7 @@ ProtocolDecl *ASTContext::getProtocol(KnownProtocolKind kind) const {
case KnownProtocolKind::CxxSet:
case KnownProtocolKind::CxxSequence:
case KnownProtocolKind::CxxUniqueSet:
case KnownProtocolKind::CxxVector:
case KnownProtocolKind::UnsafeCxxInputIterator:
case KnownProtocolKind::UnsafeCxxMutableInputIterator:
case KnownProtocolKind::UnsafeCxxRandomAccessIterator:
Expand Down
44 changes: 44 additions & 0 deletions lib/ClangImporter/ClangDerivedConformances.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -927,3 +927,47 @@ void swift::conformToCxxDictionaryIfNeeded(
insert->getResultInterfaceType());
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxDictionary});
}

void swift::conformToCxxVectorIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl) {
PrettyStackTraceDecl trace("conforming to CxxVector", decl);

assert(decl);
assert(clangDecl);
ASTContext &ctx = decl->getASTContext();

// Only auto-conform types from the C++ standard library. Custom user types
// might have a similar interface but different semantics.
if (!isStdDecl(clangDecl, {"vector"}))
return;

auto valueType = lookupDirectSingleWithoutExtensions<TypeAliasDecl>(
decl, ctx.getIdentifier("value_type"));
auto iterType = lookupDirectSingleWithoutExtensions<TypeAliasDecl>(
decl, ctx.getIdentifier("const_iterator"));
if (!valueType || !iterType)
return;

ProtocolDecl *cxxRandomAccessIteratorProto =
ctx.getProtocol(KnownProtocolKind::UnsafeCxxRandomAccessIterator);
if (!cxxRandomAccessIteratorProto)
return;

auto rawIteratorTy = iterType->getUnderlyingType();

// Check if RawIterator conforms to UnsafeCxxRandomAccessIterator.
ModuleDecl *module = decl->getModuleContext();
auto rawIteratorConformanceRef =
module->lookupConformance(rawIteratorTy, cxxRandomAccessIteratorProto);
if (!isConcreteAndValid(rawIteratorConformanceRef, module))
return;

impl.addSynthesizedTypealias(decl, ctx.Id_Element,
valueType->getUnderlyingType());
impl.addSynthesizedTypealias(decl, ctx.Id_ArrayLiteralElement,
valueType->getUnderlyingType());
impl.addSynthesizedTypealias(decl, ctx.getIdentifier("RawIterator"),
rawIteratorTy);
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxVector});
}
6 changes: 6 additions & 0 deletions lib/ClangImporter/ClangDerivedConformances.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ void conformToCxxDictionaryIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl);

/// If the decl is an instantiation of C++ `std::vector`, synthesize a
/// conformance to CxxVector, which is defined in the Cxx module.
void conformToCxxVectorIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl);

} // namespace swift

#endif // SWIFT_CLANG_DERIVED_CONFORMANCES_H
1 change: 1 addition & 0 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2797,6 +2797,7 @@ namespace {
conformToCxxDictionaryIfNeeded(Impl, nominalDecl, decl);
conformToCxxPairIfNeeded(Impl, nominalDecl, decl);
conformToCxxOptionalIfNeeded(Impl, nominalDecl, decl);
conformToCxxVectorIfNeeded(Impl, nominalDecl, decl);
}

if (auto *ntd = dyn_cast<NominalTypeDecl>(result))
Expand Down
1 change: 1 addition & 0 deletions lib/IRGen/GenMeta.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6310,6 +6310,7 @@ SpecialProtocol irgen::getSpecialProtocolID(ProtocolDecl *P) {
case KnownProtocolKind::CxxSet:
case KnownProtocolKind::CxxSequence:
case KnownProtocolKind::CxxUniqueSet:
case KnownProtocolKind::CxxVector:
case KnownProtocolKind::UnsafeCxxInputIterator:
case KnownProtocolKind::UnsafeCxxMutableInputIterator:
case KnownProtocolKind::UnsafeCxxRandomAccessIterator:
Expand Down
1 change: 1 addition & 0 deletions stdlib/public/Cxx/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ add_swift_target_library(swiftCxx ${SWIFT_CXX_LIBRARY_KIND} NO_LINK_NAME IS_STDL
CxxSet.swift
CxxRandomAccessCollection.swift
CxxSequence.swift
CxxVector.swift
UnsafeCxxIterators.swift

SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS}
Expand Down
47 changes: 47 additions & 0 deletions stdlib/public/Cxx/CxxVector.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// A C++ type that represents a vector of values.
///
/// C++ standard library type `std::vector` conforms to this protocol.
public protocol CxxVector<Element>: ExpressibleByArrayLiteral {
associatedtype Element
associatedtype RawIterator: UnsafeCxxRandomAccessIterator
where RawIterator.Pointee == Element

init()

mutating func push_back(_ element: Element)
}

extension CxxVector {
/// Creates a C++ vector containing the elements of a Swift Sequence.
///
/// This initializes the vector by copying every element of the sequence.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the Swift
/// sequence
@inlinable
public init<S: Sequence>(_ sequence: __shared S) where S.Element == Element {
self.init()
for item in sequence {
self.push_back(item)
}
}
}

extension CxxVector {
@inlinable
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
4 changes: 4 additions & 0 deletions test/Interop/Cxx/stdlib/Inputs/std-vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ using VectorOfString = std::vector<std::string>;

inline Vector initVector() { return {}; }

inline std::string takesVectorOfString(const VectorOfString &v) {
return v.front();
}

#endif // TEST_INTEROP_CXX_STDLIB_INPUTS_STD_VECTOR_H
42 changes: 42 additions & 0 deletions test/Interop/Cxx/stdlib/use-std-vector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,48 @@ StdVectorTestSuite.test("VectorOfInt.init") {
expectTrue(v.empty())
}

StdVectorTestSuite.test("VectorOfInt.init(sequence)") {
let v = Vector([])
expectEqual(v.size(), 0)
expectTrue(v.empty())

let v2 = Vector([1, 2, 3])
expectEqual(v2.size(), 3)
expectFalse(v2.empty())
expectEqual(v2[0], 1)
expectEqual(v2[1], 2)
expectEqual(v2[2], 3)
}

StdVectorTestSuite.test("VectorOfString.init(sequence)") {
let v = VectorOfString([])
expectEqual(v.size(), 0)
expectTrue(v.empty())

let v2 = VectorOfString(["", "ab", "abc"])
expectEqual(v2.size(), 3)
expectFalse(v2.empty())
expectEqual(v2[0], "")
expectEqual(v2[1], "ab")
expectEqual(v2[2], "abc")

let first = takesVectorOfString(["abc", "qwe"])
expectEqual(first, "abc")
}

StdVectorTestSuite.test("VectorOfInt as ExpressibleByArrayLiteral") {
let v: Vector = []
expectEqual(v.size(), 0)
expectTrue(v.empty())

let v2: Vector = [1, 2, 3]
expectEqual(v2.size(), 3)
expectFalse(v2.empty())
expectEqual(v2[0], 1)
expectEqual(v2[1], 2)
expectEqual(v2[2], 3)
}

StdVectorTestSuite.test("VectorOfInt.push_back") {
var v = Vector()
let _42: CInt = 42
Expand Down