@@ -717,3 +717,48 @@ public struct ObservablePropertyMacro: AccessorMacro {
717717 return [ getAccessor, setAccessor]
718718 }
719719}
720+
721+ extension DeclModifierSyntax {
722+ fileprivate var isNeededAccessLevelModifier : Bool {
723+ switch self . name. tokenKind {
724+ case . keyword( . public) : return true
725+ default : return false
726+ }
727+ }
728+ }
729+
730+ extension SyntaxStringInterpolation {
731+ fileprivate mutating func appendInterpolation< Node: SyntaxProtocol > ( _ node: Node ? ) {
732+ if let node {
733+ appendInterpolation ( node)
734+ }
735+ }
736+ }
737+
738+ public struct NewTypeMacro : MemberMacro {
739+ public static func expansion(
740+ of node: AttributeSyntax ,
741+ providingMembersOf declaration: some DeclGroupSyntax ,
742+ in context: some MacroExpansionContext
743+ ) throws -> [ DeclSyntax ] {
744+ guard let type = node. attributeName. as ( SimpleTypeIdentifierSyntax . self) ,
745+ let genericArguments = type. genericArgumentClause? . arguments,
746+ genericArguments. count == 1 ,
747+ let rawType = genericArguments. first
748+ else {
749+ throw CustomError . message ( #"@NewType requires the raw type as an argument, in the form "<RawType>"."# )
750+ }
751+
752+ guard let declaration = declaration. as ( StructDeclSyntax . self) else {
753+ throw CustomError . message ( " @NewType can only be applied to a struct declarations. " )
754+ }
755+
756+ let access = declaration. modifiers? . first ( where: \. isNeededAccessLevelModifier)
757+
758+ return [
759+ " \( access) typealias RawValue = \( rawType) " ,
760+ " \( access) var rawValue: RawValue " ,
761+ " \( access) init(_ rawValue: RawValue) { self.rawValue = rawValue } " ,
762+ ]
763+ }
764+ }
0 commit comments