Skip to content

Commit

Permalink
Add support for function modifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
rocxteady committed Oct 24, 2023
1 parent 9809ce6 commit d26ccbf
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
10 changes: 9 additions & 1 deletion Sources/ThrowPublisherMacros/ThrowPublisherMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ public struct ThrowPublisherMacro: PeerMacro {
throw ThrowPublisherError.noThrow
}

let modifiers = functionDecl.modifiers.map {
$0.name.text
}.joined(separator: " ")

let returnType: String
if let name = functionDecl.signature.returnClause?.type.as(IdentifierTypeSyntax.self)?.name {
returnType = name.text
Expand Down Expand Up @@ -101,8 +105,12 @@ public struct ThrowPublisherMacro: PeerMacro {
returnPart += " \(genericPart)"
}

var startOfFunction = "func"
if !modifiers.isEmpty {
startOfFunction = "\(modifiers) \(startOfFunction)"
}
let hop = """
func \(newFunctionName)\(parameters)-> \(returnPart) {
\(startOfFunction) \(newFunctionName)\(parameters)-> \(returnPart) {
func getResult() -> Result<\(returnType), Error> {
do {
\(resultString)
Expand Down
36 changes: 35 additions & 1 deletion Tests/ThrowPublisherTests/ThrowPublisherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ final class ThrowPublisherTests: XCTestCase {
#endif
}


func testMacroWithWhere() throws {
#if canImport(ThrowPublisherMacros)
assertMacroExpansion(
Expand Down Expand Up @@ -258,6 +257,41 @@ final class ThrowPublisherTests: XCTestCase {
#endif
}

func testMacroWithStatic() throws {
#if canImport(ThrowPublisherMacros)
assertMacroExpansion(
"""
@ThrowPublisher
static func someFunc(arg1: String, arg2: Int) throws -> String {
"something"
}
""",
expandedSource: """
static func someFunc(arg1: String, arg2: Int) throws -> String {
"something"
}
static func someFunc_publisher(arg1: String, arg2: Int) -> AnyPublisher<String, Error> {
func getResult() -> Result<String, Error> {
do {
let result = try someFunc(arg1: arg1, arg2: arg2)
return .success(result)
} catch {
return .failure(error)
}
}
return getResult()
.publisher
.eraseToAnyPublisher()
}
""",
macros: testMacros
)
#else
throw XCTSkip("macros are only supported when running tests for the host platform")
#endif
}

func testMacroWithNotFunction() throws {
#if canImport(ThrowPublisherMacros)
assertMacroExpansion(
Expand Down

0 comments on commit d26ccbf

Please sign in to comment.