Skip to content

Commit

Permalink
Add a macro helper to get string literal value
Browse files Browse the repository at this point in the history
  • Loading branch information
alexdeem committed Dec 4, 2024
1 parent cf23d67 commit b3f8925
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 6 deletions.
27 changes: 27 additions & 0 deletions Sources/ScreamURITemplateCompilerPlugin/ExprSyntax+Literals.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2018-2024 Alex Deem
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SwiftSyntax

extension ExprSyntax {
func stringLiteral() -> String? {
guard let segments = self.as(StringLiteralExprSyntax.self)?.segments,
segments.count == 1,
case let .stringSegment(literalSegment)? = segments.first else {
return nil
}

return literalSegment.content.text
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,19 @@ public struct URITemplateMacro: ExpressionMacro {
of node: some FreestandingMacroExpansionSyntax,
in _: some MacroExpansionContext) throws -> ExprSyntax {
guard let argument = node.arguments.first?.expression,
let segments = argument.as(StringLiteralExprSyntax.self)?.segments,
segments.count == 1,
case let .stringSegment(literalSegment)? = segments.first
let uriTemplateString = argument.stringLiteral()
else {
throw DiagnosticsError(diagnostics: [
Diagnostic(node: node,
message: MacroExpansionErrorMessage("#URITemplate requires a static string literal")),
])
}

let uriTemplateString = literalSegment.content.text
do {
_ = try URITemplate(string: uriTemplateString)
} catch {
throw DiagnosticsError(diagnostics: [
Diagnostic(node: literalSegment,
Diagnostic(node: argument,
message: MacroExpansionErrorMessage("Invalid URI template: \(error.reason) at \"\(uriTemplateString.suffix(from: error.position).prefix(50))\"")),
])
}
Expand Down
2 changes: 1 addition & 1 deletion Tests/ScreamURITemplateTests/MacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
#URITemplate("https://api.github.com/repos/{}/{repo}")
"""#,
diagnostics: [
DiagnosticSpec(message: "Invalid URI template: Empty Variable Name at \"}/{repo}\"", line: 1, column: 15),
DiagnosticSpec(message: "Invalid URI template: Empty Variable Name at \"}/{repo}\"", line: 1, column: 14),
],
macros: testMacros)
}
Expand Down

0 comments on commit b3f8925

Please sign in to comment.