|
| 1 | +import SwiftDiagnostics |
| 2 | +import SwiftSyntax |
| 3 | +import SwiftSyntaxMacros |
| 4 | + |
| 5 | +/// OS 버전에 따라 Logger의 호출이 달라지므로, 조건에 따라 변경이 필요함 |
| 6 | +public struct LoggingExpressionMacros: ExpressionMacro { |
| 7 | + public static func expansion( |
| 8 | + of node: some FreestandingMacroExpansionSyntax, |
| 9 | + in context: some MacroExpansionContext |
| 10 | + ) -> ExprSyntax { |
| 11 | + let argumentList = node.argumentList |
| 12 | + guard |
| 13 | + argumentList.count == 2, |
| 14 | + let firstElement = argumentList.first, |
| 15 | + let secondElement = argumentList.last |
| 16 | + else { |
| 17 | + fatalError("compiler bug: the macro does not have any arguments") |
| 18 | + } |
| 19 | + |
| 20 | + let oslogType = firstElement.expression |
| 21 | + .as(MemberAccessExprSyntax.self)? |
| 22 | + .declName.baseName.text |
| 23 | + let msg = secondElement.expression |
| 24 | + .as(StringLiteralExprSyntax.self)? |
| 25 | + .segments.first? |
| 26 | + .as(StringSegmentSyntax.self)? |
| 27 | + .content.text |
| 28 | + |
| 29 | + guard |
| 30 | + let oslogType, let msg |
| 31 | + else { |
| 32 | + fatalError("compiler bug: the macro does not have any arguments") |
| 33 | + } |
| 34 | + |
| 35 | + return "\(raw: generateExpr(oslogType: oslogType, msg: msg))" |
| 36 | + } |
| 37 | + |
| 38 | + private static func generateExpr(oslogType: String, msg: String) -> String { |
| 39 | + """ |
| 40 | + { |
| 41 | + #if os(iOS) |
| 42 | + if #available(iOS 14.0, *) { |
| 43 | + Logger(logger).log(level: .\(oslogType), "\(msg)") |
| 44 | + } else { |
| 45 | + \(debug(oslogType: oslogType, msg: msg)) |
| 46 | + } |
| 47 | + #else |
| 48 | + \(debug(oslogType: oslogType, msg: msg)) |
| 49 | + #endif |
| 50 | + }() |
| 51 | + """ |
| 52 | + } |
| 53 | + |
| 54 | + private static func debug(oslogType: String, msg: String) -> String { |
| 55 | + """ |
| 56 | + os_log(.\(oslogType), log: logger, "\(msg)") |
| 57 | + """ |
| 58 | + } |
| 59 | +} |
0 commit comments