Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,24 +48,8 @@ extension Optional {
case let .some(value):
return value
case .none:
throw MacroError(message())
throw MacroExpansionErrorMessage(message())
}
}

}

struct MacroError: Error, CustomStringConvertible {

init(
_ message: String = "Macro Expansion Failed"
) {
self.message = message
}

let message: String

var description: String {
message
}

}
113 changes: 92 additions & 21 deletions Sources/CalligraphyCompilerPlugin/EntryMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,14 @@ public struct EntryMacro: AccessorMacro, PeerMacro {
in context: some MacroExpansionContext
) throws -> [AccessorDeclSyntax] {
let attribute = attributeName(of: node)
let binding = try binding(from: declaration, attribute: attribute)
let name = try identifier(from: binding, attribute: attribute).text
let binding = try binding(
from: declaration,
attribute: attribute
)
let name = try identifier(
from: binding,
attribute: attribute
).text
let keyName = "__Key_\(name)"
return [
"""
Expand All @@ -54,8 +60,14 @@ public struct EntryMacro: AccessorMacro, PeerMacro {
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
let attribute = attributeName(of: node)
let binding = try binding(from: declaration, attribute: attribute)
let name = try identifier(from: binding, attribute: attribute).text
let binding = try binding(
from: declaration,
attribute: attribute
)
let name = try identifier(
from: binding,
attribute: attribute
).text
let typeAnnotation = try binding.typeAnnotation
.mustExist("\(attribute) requires an explicit type annotation")
.type
Expand All @@ -65,18 +77,30 @@ public struct EntryMacro: AccessorMacro, PeerMacro {
} else if isOptional(typeAnnotation) {
defaultValue = "nil"
} else {
throw MacroError("\(attribute) requires an initial value for non-optional types")
throw MacroExpansionErrorMessage("\(attribute) requires an initial value for non-optional types")
}
let keyName = "__Key_\(name)"
return [
"""
private struct \(raw: keyName): EnvironmentKey {
static let defaultValue: \(typeAnnotation.trimmed) = \(defaultValue.trimmed)
}
"""
]
#if compiler(>=6.3) && canImport(SwiftSyntax603)
return [
"""
private struct \(raw: keyName): Calligraphy::EnvironmentKey {
static let defaultValue: \(typeAnnotation.trimmed) = \(defaultValue.trimmed)
}
"""
]
#else
return [
"""
private struct \(raw: keyName): Calligraphy.EnvironmentKey {
static let defaultValue: \(typeAnnotation.trimmed) = \(defaultValue.trimmed)
}
"""
]
#endif
}

// MARK: - Private

private static func attributeName(
of node: AttributeSyntax
) -> String {
Expand All @@ -102,17 +126,64 @@ public struct EntryMacro: AccessorMacro, PeerMacro {
.identifier
}

private static func isOptional(_ type: TypeSyntax) -> Bool {
if type.is(OptionalTypeSyntax.self) {
return true
private static func isOptional(
_ type: TypeSyntax
) -> Bool {
if type.is(OptionalTypeSyntax.self) || type.is(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
true
} else if let identifier = type.as(IdentifierTypeSyntax.self) {
identifier.name.text == "Optional" && isSwiftQualified(identifier)
} else if let member = type.as(MemberTypeSyntax.self),
let base = member.baseType.as(IdentifierTypeSyntax.self) {
member.name.text == "Optional"
&& isUnqualified(member)
&& base.name.text == "Swift"
&& isUnqualified(base)
&& base.genericArgumentClause == nil
} else {
false
}
if type.is(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
return true
}

#if canImport(SwiftSyntax603)
private static func isSwiftQualified(
_ identifier: IdentifierTypeSyntax
) -> Bool {
guard let selector = identifier.moduleSelector else {
return true
}
return selector.moduleName.text == "Swift"
}
if let identifier = type.as(IdentifierTypeSyntax.self), identifier.name.text == "Optional" {
return true

private static func isUnqualified(
_ identifier: IdentifierTypeSyntax
) -> Bool {
identifier.moduleSelector == nil
}
return false
}

private static func isUnqualified(
_ member: MemberTypeSyntax
) -> Bool {
member.moduleSelector == nil
}
#else
private static func isSwiftQualified(
_ identifier: IdentifierTypeSyntax
) -> Bool {
true
}

private static func isUnqualified(
_ identifier: IdentifierTypeSyntax
) -> Bool {
true
}

private static func isUnqualified(
_ member: MemberTypeSyntax
) -> Bool {
true
}
#endif

}
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ public struct FilePermissionsOctalMacro: ExpressionMacro {
}
}

let arrayLiteral = if parts.isEmpty {
"[] as FilePermissions" // make the type clear when empty
} else {
"[" + parts.joined(separator: ", ") + "]"
}
let arrayLiteral = "[" + parts.joined(separator: ", ") + "]"
#if compiler(>=6.3) && canImport(SwiftSyntax603)
let fullyFormed = "Calligraphy::FilePermissions(arrayLiteral: \(arrayLiteral))"
#else
let fullyFormed = "Calligraphy.FilePermissions(arrayLiteral: \(arrayLiteral))"
#endif

return ExprSyntax(stringLiteral: arrayLiteral)
return ExprSyntax(stringLiteral: fullyFormed)
}

}
29 changes: 10 additions & 19 deletions Sources/CalligraphyCompilerPlugin/FilePermissionsStringMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
// Expect exactly one string literal argument like "rwxr-xr-x".
// Also accept optional whitespace separators (e.g. "rwx r-x r-x") and an optional leading file type char (e.g. "-rwxr-xr-x").
guard node.arguments.count == 1 else {
throw MacroExpansionErrorMessage("filePermissions requires a single string literal argument, e.g. \"rwxr-xr-x\"")
}
Expand All @@ -47,29 +45,26 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
.as(StringLiteralExprSyntax.self)
.mustExist()

// Ensure no interpolation and capture the raw content
guard stringLiteral.segments.count == 1,
let first = stringLiteral.segments.first,
let segment = first.as(StringSegmentSyntax.self) else {
throw MacroExpansionErrorMessage("filePermissions string must be a simple, static string literal without interpolation")
}

// Normalize by removing all whitespace
let raw = segment.content.text
var normalized = String(raw.filter { !$0.isWhitespace })

// If there's a leading file type character, strip it (e.g., '-', 'd', 'l', 'c', 'b', 's', 'p')
let fileTypeChars: Set<Character> = ["-", "d", "l", "c", "b", "s", "p"]
if normalized.count == 10, let firstChar = normalized.first, fileTypeChars.contains(firstChar) {
if normalized.count == 10,
let firstChar = normalized.first,
fileTypeChars.contains(firstChar) {
normalized.removeFirst()
}

// Validate the symbolic permission string (9 characters: u=rwx, g=rwx, o=rwx)
guard normalized.count == 9 else {
throw MacroExpansionErrorMessage("filePermissions string must describe exactly 9 permission characters (optionally preceded by a file type), e.g. \"rwxr-xr-x\" or \"-rwxr-xr-x\"")
}

/// Helper to index into the string safely
func char(at i: Int) -> Character {
normalized[normalized.index(normalized.startIndex, offsetBy: i)]
}
Expand All @@ -93,10 +88,8 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
}
}

// Build the list of FilePermissions option names based on the string
var parts: [String] = []

// Special bits first for readability
let ux = char(at: 2)
if ux == "s" || ux == "S" {
parts.append(".setUserID")
Expand All @@ -112,7 +105,6 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
parts.append(".sticky")
}

// User bits
if char(at: 0) == "r" {
parts.append(".readUser")
}
Expand All @@ -123,7 +115,6 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
parts.append(".executeUser")
}

// Group bits
if char(at: 3) == "r" {
parts.append(".readGroup")
}
Expand All @@ -134,7 +125,6 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
parts.append(".executeGroup")
}

// Other bits
if char(at: 6) == "r" {
parts.append(".readOther")
}
Expand All @@ -145,13 +135,14 @@ public struct FilePermissionsStringMacro: ExpressionMacro {
parts.append(".executeOther")
}

let arrayLiteral = if parts.isEmpty {
"[] as FilePermissions"
} else {
"[" + parts.joined(separator: ", ") + "]"
}
let arrayLiteral = "[" + parts.joined(separator: ", ") + "]"
#if compiler(>=6.3) && canImport(SwiftSyntax603)
let fullyFormed = "Calligraphy::FilePermissions(arrayLiteral: \(arrayLiteral))"
#else
let fullyFormed = "Calligraphy.FilePermissions(arrayLiteral: \(arrayLiteral))"
#endif

return ExprSyntax(stringLiteral: arrayLiteral)
return ExprSyntax(stringLiteral: fullyFormed)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,48 @@

import Testing

// 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.
#if canImport(CalligraphyCompilerPlugin)
@testable import CalligraphyCompilerPlugin
#endif

#if !canImport(SwiftSyntax604)
import SwiftSyntaxMacroExpansion
import SwiftSyntaxMacrosGenericTestSupport

func assertMacroExpansion(
_ originalSource: String,
expandedSource: String,
diagnostics: [DiagnosticSpec] = [],
macroSpecs: [String: MacroSpec],
fileID: StaticString = #fileID,
filePath: StaticString = #filePath,
line: UInt = #line,
column: UInt = #column
) {
SwiftSyntaxMacrosGenericTestSupport.assertMacroExpansion(
originalSource,
expandedSource: expandedSource,
diagnostics: diagnostics,
macroSpecs: macroSpecs,
failureHandler: { failure in
Issue.record(
Comment(rawValue: failure.message),
sourceLocation: SourceLocation(
fileID: failure.location.fileID,
filePath: failure.location.filePath,
line: failure.location.line,
column: failure.location.column
)
)
},
fileID: fileID,
filePath: filePath,
line: line,
column: column
)
}
#endif

@Test("Compiler plugin tests")
func calligraphyCompilerPluginTests() {
#if canImport(CalligraphyCompilerPlugin)
Expand Down
Loading
Loading