Skip to content
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
10 changes: 10 additions & 0 deletions .swiftpm/xcode/xcshareddata/xcschemes/ReerCodable.xcscheme
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "ReerCodableMainActorIsolationTests"
BuildableName = "ReerCodableMainActorIsolationTests"
BlueprintName = "ReerCodableMainActorIsolationTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
Expand Down
9 changes: 9 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,14 @@ let package = Package(
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
]
),
.testTarget(
name: "ReerCodableMainActorIsolationTests",
dependencies: [
"ReerCodable",
],
swiftSettings: [
.unsafeFlags(["-default-isolation", "MainActor"])
]
),
],
)
146 changes: 96 additions & 50 deletions Sources/ReerCodableMacros/MacroImplementations/CodableImpl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,70 @@ private func parameterMatchesType(
return String(identifier) == baseName
}

private func normalizedInheritedTypeNames(_ type: TypeSyntax) -> [String] {
let normalized = type.trimmedDescription
.split(whereSeparator: \.isWhitespace)
.filter { token in
token != "nonisolated" && !token.hasPrefix("@")
}
.joined(separator: " ")

return normalized
.split(separator: "&")
.map { component in
component
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
.split(separator: ".")
.last
.map(String.init) ?? ""
}
.filter { !$0.isEmpty }
}

private func hasInheritedType(
in declaration: some DeclGroupSyntax,
matching predicate: (String) -> Bool
) -> Bool {
guard let inheritedTypes = declaration.inheritanceClause?.inheritedTypes else { return false }
return inheritedTypes.contains { inheritedType in
normalizedInheritedTypeNames(inheritedType.type).contains(where: predicate)
}
}

private func hasNonisolatedModifier(_ declaration: some DeclGroupSyntax) -> Bool {
let modifiers: DeclModifierListSyntax?
if let structDecl = declaration.as(StructDeclSyntax.self) {
modifiers = structDecl.modifiers
} else if let classDecl = declaration.as(ClassDeclSyntax.self) {
modifiers = classDecl.modifiers
} else if let enumDecl = declaration.as(EnumDeclSyntax.self) {
modifiers = enumDecl.modifiers
} else {
modifiers = nil
}
return modifiers?.contains(where: { $0.name.text == "nonisolated" }) == true
}

private func extensionIsolationModifier(for declaration: some DeclGroupSyntax) -> String {
hasNonisolatedModifier(declaration) ? "nonisolated " : ""
}

private func makeConformanceExtension(
for type: some TypeSyntaxProtocol,
declaration: some DeclGroupSyntax,
conformances: [String]
) -> ExtensionDeclSyntax? {
guard !conformances.isEmpty else { return nil }
let isolationModifier = extensionIsolationModifier(for: declaration)
let conformanceList = conformances.joined(separator: ", ")
let extensionDecl: DeclSyntax =
"""
\(raw: isolationModifier)extension \(type.trimmed): \(raw: conformanceList) {}
"""
return extensionDecl.cast(ExtensionDeclSyntax.self)
}

extension RECodable: ExtensionMacro {
public static func expansion(
of node: SwiftSyntax.AttributeSyntax,
Expand All @@ -56,22 +120,16 @@ extension RECodable: ExtensionMacro {
throw MacroError(text: "@Codable macro is only for `struct`, `class` or `enum`.")
}

var codableExisted = false
if let inheritedType = declaration.inheritanceClause?.inheritedTypes,
inheritedType.contains(where: { $0.type.trimmedDescription == "Codable" }) {
codableExisted = true
}
var delegateExisted = false
if let inheritedType = declaration.inheritanceClause?.inheritedTypes,
inheritedType.contains(where: { $0.type.trimmedDescription == "ReerCodableDelegate" }) {
delegateExisted = true
}
if codableExisted && delegateExisted { return [] }
let extensionDecl: DeclSyntax =
"""
extension \(type.trimmed):\(raw: codableExisted ? "" : "Codable,") ReerCodableDelegate {}
"""
return [extensionDecl.cast(ExtensionDeclSyntax.self)]
let codableExisted = hasInheritedType(in: declaration) { $0 == "Codable" }
let delegateExisted = hasInheritedType(in: declaration) { $0 == "ReerCodableDelegate" }
let conformances = [
codableExisted ? nil : "Codable",
delegateExisted ? nil : "ReerCodableDelegate"
].compactMap(\.self)
guard let extensionDecl = makeConformanceExtension(for: type, declaration: declaration, conformances: conformances) else {
return []
}
return [extensionDecl]
}
}

Expand Down Expand Up @@ -166,24 +224,18 @@ extension REDecodable: ExtensionMacro {
throw MacroError(text: "@Decodable macro is only for `struct`, `class` or `enum`.")
}

var decodableExisted = false
if let inheritedTypeClause = declaration.inheritanceClause {
decodableExisted = inheritedTypeClause.inheritedTypes.contains { inheritedType in
let typeName = inheritedType.type.trimmedDescription
return typeName == "Decodable" || typeName == "Codable"
}
let decodableExisted = hasInheritedType(in: declaration) {
$0 == "Decodable" || $0 == "Codable"
}
let delegateExisted = hasInheritedType(in: declaration) { $0 == "ReerCodableDelegate" }
let conformances = [
decodableExisted ? nil : "Decodable",
delegateExisted ? nil : "ReerCodableDelegate"
].compactMap(\.self)
guard let extensionDecl = makeConformanceExtension(for: type, declaration: declaration, conformances: conformances) else {
return []
}
var delegateExisted = false
if let inheritedType = declaration.inheritanceClause?.inheritedTypes,
inheritedType.contains(where: { $0.type.trimmedDescription == "ReerCodableDelegate" }) {
delegateExisted = true
}
if decodableExisted && delegateExisted { return [] }
let extensionDecl: DeclSyntax =
"""
extension \(type.trimmed): \(raw: decodableExisted ? "" : "Decodable, ")ReerCodableDelegate {}
"""
return [extensionDecl.cast(ExtensionDeclSyntax.self)]
return [extensionDecl]
}
}

Expand Down Expand Up @@ -271,24 +323,18 @@ extension REEncodable: ExtensionMacro {
throw MacroError(text: "@Encodable macro is only for `struct`, `class` or `enum`.")
}

var encodableExisted = false
if let inheritedTypeClause = declaration.inheritanceClause {
encodableExisted = inheritedTypeClause.inheritedTypes.contains { inheritedType in
let typeName = inheritedType.type.trimmedDescription
return typeName == "Encodable" || typeName == "Codable"
}
let encodableExisted = hasInheritedType(in: declaration) {
$0 == "Encodable" || $0 == "Codable"
}
let delegateExisted = hasInheritedType(in: declaration) { $0 == "ReerCodableDelegate" }
let conformances = [
encodableExisted ? nil : "Encodable",
delegateExisted ? nil : "ReerCodableDelegate"
].compactMap(\.self)
guard let extensionDecl = makeConformanceExtension(for: type, declaration: declaration, conformances: conformances) else {
return []
}
var delegateExisted = false
if let inheritedType = declaration.inheritanceClause?.inheritedTypes,
inheritedType.contains(where: { $0.type.trimmedDescription == "ReerCodableDelegate" }) {
delegateExisted = true
}
if encodableExisted && delegateExisted { return [] }
let extensionDecl: DeclSyntax =
"""
extension \(type.trimmed): \(raw: encodableExisted ? "" : "Encodable, ")ReerCodableDelegate {}
"""
return [extensionDecl.cast(ExtensionDeclSyntax.self)]
return [extensionDecl]
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Foundation
import ReerCodable
import Testing

@Codable
nonisolated struct MainActorDefaultCodableModel: Sendable {
let id: Int
let name: String
}

@Decodable
nonisolated struct MainActorDefaultDecodableModel: Sendable {
let id: Int
}

@Encodable
nonisolated struct MainActorDefaultEncodableModel: Sendable {
let id: Int
}

private func acceptsCodableSendable<T: Codable & Sendable>(_ type: T.Type) {}

private func acceptsDecodableSendable<T: Decodable & Sendable>(_ type: T.Type) {}

private func acceptsEncodableSendable<T: Encodable & Sendable>(_ type: T.Type) {}

@Test
func nonisolatedCodableConformanceSatisfiesNonisolatedGenericRequirement() throws {
acceptsCodableSendable(MainActorDefaultCodableModel.self)

let original = MainActorDefaultCodableModel(id: 1, name: "Reer")
let data = try JSONEncoder().encode(original)
let decoded = try JSONDecoder().decode(MainActorDefaultCodableModel.self, from: data)

#expect(decoded.id == original.id)
#expect(decoded.name == original.name)
}

@Test
func nonisolatedDecodableConformanceSatisfiesNonisolatedGenericRequirement() throws {
acceptsDecodableSendable(MainActorDefaultDecodableModel.self)

let data = #"{"id":2}"#.data(using: .utf8)!
let decoded = try JSONDecoder().decode(MainActorDefaultDecodableModel.self, from: data)

#expect(decoded.id == 2)
}

@Test
func nonisolatedEncodableConformanceSatisfiesNonisolatedGenericRequirement() throws {
acceptsEncodableSendable(MainActorDefaultEncodableModel.self)

let data = try JSONEncoder().encode(MainActorDefaultEncodableModel(id: 3))
let value = try #require(data.stringAnyDictionary?["id"] as? Int)

#expect(value == 3)
}

private extension Data {
var stringAnyDictionary: [String: Any]? {
try? JSONSerialization.jsonObject(with: self) as? [String: Any]
}
}
Loading
Loading