├── Sources ├── URLClient │ └── main.swift ├── URL │ └── URL.swift └── URLMacros │ └── URLMacro.swift ├── .gitignore ├── .swiftpm └── xcode │ └── package.xcworkspace │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── Package.resolved ├── README.md ├── LICENSE ├── Package.swift └── Tests └── URLTests └── URLTests.swift /Sources/URLClient/main.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import URL 3 | 4 | let url = #URL("https://www.apple.com") 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "swift-syntax", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/apple/swift-syntax.git", 7 | "state" : { 8 | "revision" : "303e5c5c36d6a558407d364878df131c3546fad8", 9 | "version" : "510.0.2" 10 | } 11 | } 12 | ], 13 | "version" : 2 14 | } 15 | -------------------------------------------------------------------------------- /Sources/URL/URL.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// An freestanding macro that provides an unwrapped `Foundation URL` for the string literal argument. 4 | /// The macro checks the validity of the literal and throws an error if it does not represent a valid `Foundation URL`. 5 | /// 6 | /// Creating a `URL` from a string literal like this 7 | /// 8 | /// let url = #URL("https://www.apple.com") 9 | /// 10 | /// results in the following code automatically 11 | /// 12 | /// URL(string: "https://www.apple.com")! 13 | @freestanding(expression) 14 | public macro URL(_ str: String) -> URL = #externalMacro(module: "URLMacros", type: "URLMacro") 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # URL 2 | 3 | `URL` is a freestanding Swift macro that provides an unwrapped `Foundation URL` for the string literal argument. 4 | The macro checks the validity of the literal and throws an error if it does not represent a valid `Foundation URL`. 5 | 6 | ## Usage 7 | 8 | ```swift 9 | import URL 10 | 11 | let url = #URL("https://www.apple.com") 12 | ``` 13 | 14 | This will automatically generate the following code: 15 | 16 | ```swift 17 | URL(string: "https://www.apple.com")! 18 | ``` 19 | 20 | ## Installation 21 | 22 | The package can be installed using [Swift Package Manager](https://swift.org/package-manager/). To add `URL` to your Xcode project, select *File > Add Package Dependancies...* and search for the repository URL: `https://github.com/davidsteppenbeck/URL.git`. 23 | 24 | ## License 25 | 26 | `URL` is available under the MIT license. See the LICENSE file for more info. 27 | 28 | ## Acknowledgements 29 | 30 | The `URL` macro example is described in detail in Antoine v.d. Lee's [blog post](https://www.avanderlee.com/swift/macros). 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 David Steppenbeck 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Sources/URLMacros/URLMacro.swift: -------------------------------------------------------------------------------- 1 | import SwiftCompilerPlugin 2 | import SwiftSyntax 3 | import SwiftSyntaxBuilder 4 | import SwiftSyntaxMacros 5 | import Foundation 6 | 7 | public struct URLMacro: ExpressionMacro { 8 | 9 | public static func expansion( 10 | of node: some FreestandingMacroExpansionSyntax, 11 | in context: some MacroExpansionContext 12 | ) throws -> ExprSyntax { 13 | guard let argument = node.arguments.first else { 14 | throw URLError.noArguments 15 | } 16 | 17 | guard let stringLiteralExpr = argument.expression.as(StringLiteralExprSyntax.self), 18 | let segment = stringLiteralExpr.segments.first?.as(StringSegmentSyntax.self), 19 | stringLiteralExpr.segments.count == 1 20 | else { 21 | throw URLError.mustBeValidStringLiteral 22 | } 23 | 24 | let text = segment.content.text 25 | 26 | if URL(string: text) != nil { 27 | return #"URL(string: "\#(raw: text)")!"# 28 | } else { 29 | throw URLError.invalid 30 | } 31 | } 32 | 33 | } 34 | 35 | enum URLError: Error, CustomStringConvertible { 36 | case noArguments 37 | case mustBeValidStringLiteral 38 | case invalid 39 | 40 | var description: String { 41 | switch self { 42 | case .noArguments: 43 | return "The macro does not have any arguments" 44 | case .mustBeValidStringLiteral: 45 | return "Argument must be a string literal" 46 | case .invalid: 47 | return "The string does not represent a valid URL" 48 | } 49 | } 50 | } 51 | 52 | @main 53 | struct URLPlugin: CompilerPlugin { 54 | let providingMacros: [Macro.Type] = [ 55 | URLMacro.self, 56 | ] 57 | } 58 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.10 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | import CompilerPluginSupport 6 | 7 | let package = Package( 8 | name: "URL", 9 | platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .macCatalyst(.v13)], 10 | products: [ 11 | // Products define the executables and libraries a package produces, making them visible to other packages. 12 | .library( 13 | name: "URL", 14 | targets: ["URL"] 15 | ), 16 | .executable( 17 | name: "URLClient", 18 | targets: ["URLClient"] 19 | ), 20 | ], 21 | dependencies: [ 22 | // Depend on the latest Swift 5.10 release of SwiftSyntax 23 | .package(url: "https://github.com/apple/swift-syntax.git", from: "510.0.0"), 24 | ], 25 | targets: [ 26 | // Targets are the basic building blocks of a package, defining a module or a test suite. 27 | // Targets can depend on other targets in this package and products from dependencies. 28 | // Macro implementation that performs the source transformation of a macro. 29 | .macro( 30 | name: "URLMacros", 31 | dependencies: [ 32 | .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), 33 | .product(name: "SwiftCompilerPlugin", package: "swift-syntax") 34 | ] 35 | ), 36 | 37 | // Library that exposes a macro as part of its API, which is used in client programs. 38 | .target(name: "URL", dependencies: ["URLMacros"]), 39 | 40 | // A client of the library, which is able to use the macro in its own code. 41 | .executableTarget(name: "URLClient", dependencies: ["URL"]), 42 | 43 | // A test target used to develop the macro implementation. 44 | .testTarget( 45 | name: "URLTests", 46 | dependencies: [ 47 | "URLMacros", 48 | .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"), 49 | ] 50 | ), 51 | ] 52 | ) 53 | -------------------------------------------------------------------------------- /Tests/URLTests/URLTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntaxMacros 2 | import SwiftSyntaxMacrosTestSupport 3 | import XCTest 4 | 5 | // Macro implementations build for the host, so the corresponding module is not available when cross-compiling. Cross-compiled tests may still make use of the macro itself in end-to-end tests. 6 | #if canImport(URLMacros) 7 | import URLMacros 8 | 9 | let testMacros: [String: Macro.Type] = [ 10 | "URL": URLMacro.self, 11 | ] 12 | #endif 13 | 14 | final class URLTests: XCTestCase { 15 | 16 | func testURL() throws { 17 | #if canImport(URLMacros) 18 | assertMacroExpansion( 19 | """ 20 | #URL("https://www.apple.com/iphone") 21 | """, 22 | expandedSource: 23 | """ 24 | URL(string: "https://www.apple.com/iphone")! 25 | """, 26 | macros: testMacros 27 | ) 28 | #else 29 | throw XCTSkip("macros are only supported when running tests for the host platform") 30 | #endif 31 | } 32 | 33 | func testURLWithNoArguments() throws { 34 | #if canImport(URLMacros) 35 | assertMacroExpansion( 36 | """ 37 | #URL() 38 | """, 39 | expandedSource: 40 | """ 41 | #URL() 42 | """, 43 | diagnostics: [ 44 | DiagnosticSpec(message: "The macro does not have any arguments", line: 1, column: 1) 45 | ], 46 | macros: testMacros 47 | ) 48 | #else 49 | throw XCTSkip("macros are only supported when running tests for the host platform") 50 | #endif 51 | } 52 | 53 | func testURLWithNonStringLiteral() throws { 54 | #if canImport(URLMacros) 55 | assertMacroExpansion( 56 | #""" 57 | let str = "/iphone" 58 | #URL("https://www.apple.com\(str)") 59 | """#, 60 | expandedSource: 61 | #""" 62 | let str = "/iphone" 63 | #URL("https://www.apple.com\(str)") 64 | """#, 65 | diagnostics: [ 66 | DiagnosticSpec(message: "Argument must be a string literal", line: 2, column: 1) 67 | ], 68 | macros: testMacros 69 | ) 70 | #else 71 | throw XCTSkip("macros are only supported when running tests for the host platform") 72 | #endif 73 | } 74 | 75 | func testURLWithInvalidStringLiteral() throws { 76 | #if canImport(URLMacros) 77 | assertMacroExpansion( 78 | """ 79 | #URL(" https:// www.apple.com/ iphone") 80 | """, 81 | expandedSource: 82 | """ 83 | #URL(" https:// www.apple.com/ iphone") 84 | """, 85 | diagnostics: [ 86 | DiagnosticSpec(message: "The string does not represent a valid URL", line: 1, column: 1) 87 | ], 88 | macros: testMacros 89 | ) 90 | #else 91 | throw XCTSkip("macros are only supported when running tests for the host platform") 92 | #endif 93 | } 94 | 95 | } 96 | --------------------------------------------------------------------------------