|
| 1 | +import SwiftCompilerPlugin |
| 2 | +import SwiftSyntax |
| 3 | +import SwiftSyntaxBuilder |
| 4 | +import SwiftSyntaxMacros |
| 5 | +import Foundation |
| 6 | + |
| 7 | +public struct URLPathMacro: PeerMacro { |
| 8 | + struct CaseParam: Hashable { |
| 9 | + let index: Int |
| 10 | + let name: String |
| 11 | + } |
| 12 | + |
| 13 | + struct PatternPathItem { |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | + public static func expansion( |
| 18 | + of node: AttributeSyntax, |
| 19 | + providingPeersOf declaration: some DeclSyntaxProtocol, |
| 20 | + in context: some MacroExpansionContext |
| 21 | + ) throws -> [DeclSyntax] { |
| 22 | + guard |
| 23 | + let enumCase = declaration.as(EnumCaseDeclSyntax.self), |
| 24 | + let element = enumCase.elements.first |
| 25 | + else { |
| 26 | + throw MacroError.message("URLPatternPath macro can only be applied to enum cases") |
| 27 | + } |
| 28 | + |
| 29 | + guard |
| 30 | + let argument = node.arguments?.as(LabeledExprListSyntax.self)?.first, |
| 31 | + let pathString = argument.expression.as(StringLiteralExprSyntax.self)?.segments.first?.description |
| 32 | + else { |
| 33 | + throw MacroError.message("Invalid path") |
| 34 | + } |
| 35 | + |
| 36 | + guard let pathURL = URL(string: pathString) else { |
| 37 | + throw MacroError.message("URLPatternPath macro requires a string literal path") |
| 38 | + } |
| 39 | + |
| 40 | + let patternPaths = pathURL.pathComponents |
| 41 | + |
| 42 | + let pathComponents = pathURL.pathComponents |
| 43 | + let parameters = pathComponents.enumerated() |
| 44 | + .filter { index, value in value.isURLPathParam } |
| 45 | + .map { CaseParam(index: $0.offset, name: String($0.element.dropFirst().dropLast())) } |
| 46 | + |
| 47 | + if Set(parameters).count != parameters.count { |
| 48 | + throw MacroError.message("변수 이름은 중복되서는 안됩니다.") |
| 49 | + } |
| 50 | + |
| 51 | + let staticMethod = try FunctionDeclSyntax(""" |
| 52 | + static func \(element.name)(_ url: URL) -> Self? { |
| 53 | + let inputPaths = url.pathComponents |
| 54 | + let patternPaths = \(raw: patternPaths) |
| 55 | + |
| 56 | + guard isValidURLPaths(inputPaths: inputPaths, patternPaths: patternPaths) else { return nil } |
| 57 | + |
| 58 | + \(raw: parameters.map { param in |
| 59 | + """ |
| 60 | + let \(param.name) = inputPaths[\(param.index)] |
| 61 | + """ |
| 62 | + }.joined(separator: "\n")) |
| 63 | + |
| 64 | + return .\(raw: element.name.text)(\(raw: parameters.map { "\($0.name): \($0.name)" }.joined(separator: ", "))) |
| 65 | + } |
| 66 | + """ |
| 67 | + ) |
| 68 | + |
| 69 | + return [DeclSyntax(staticMethod)] |
| 70 | + } |
| 71 | +} |
0 commit comments