Skip to content
Open
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
60 changes: 60 additions & 0 deletions Sources/StructuredQueriesSQLite/Macros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,63 @@ public macro DatabaseFunction<R: QueryBindable>(
module: "StructuredQueriesSQLiteMacros",
type: "DatabaseFunctionMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck<each Input, Output>(
collation: (repeat each Input) throws -> Output
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "IsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck<each Input, Output>(
collation: @MainActor (repeat each Input) throws -> Output
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "MainActorIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck<each Input, Output>(
function: (repeat each Input) throws -> Output
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "IsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck<each Input, Output>(
function: @MainActor (repeat each Input) throws -> Output
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "MainActorIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck(
property: () -> Void
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "IsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro StructuredQueriesIsolationCheck(
property: @MainActor () -> Void
) =
#externalMacro(
module: "StructuredQueriesSQLiteMacros",
type: "MainActorIsolationCheckMacro"
)
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@ func exclaim(_ string: String) -> String {
This defines a "scalar" function, which is called on a value for each row in a query, returning its
result.

> Note: If your project is using [default main actor isolation] then you further need to annotate
> your function as `nonisolated`.

[default main actor isolation]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0466-control-default-actor-isolation.md

Once defined, the function is immediately callable in a query by prefixing the function with `$`:

```swift
Expand Down
94 changes: 67 additions & 27 deletions Sources/StructuredQueriesSQLiteMacros/DatabaseFunctionMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,23 @@ extension DatabaseFunctionMacro: PeerMacro {
"\(functionTypeName) { \(raw: getter.throws ? "try " : "")\(rawDeclarationName.trimmed) }"
}

let probeName = context.makeUniqueName("\(declarationName)IsolationProbe")
let isolation: TokenSyntax? =
declaration.modifiers.contains { $0.name.tokenKind == .keyword(.nonisolated) }
? .keyword(.nonisolated, trailingTrivia: .space)
: nil
let check = isolationCheck("property", probeName.text, for: node, in: context)

return [
"""
#if DEBUG
\(isolation)\(`static`)func \(probeName)() {}
#endif
""",
"""
\(attributes)\(access)\(`static`)\(nonisolated)var $\(raw: declarationName): \
\(functionTypeName) {
\(projectedCallSyntax)
\(raw: check)return \(projectedCallSyntax)
}
""",
"""
Expand Down Expand Up @@ -672,32 +684,60 @@ extension DatabaseFunctionMacro: PeerMacro {
)
}

return [
"""
\(attributes)\(access)\(`static`)\(nonisolated)var $\(raw: declarationName): \
\(functionTypeName) {
\(projectedCallSyntax)
}
""",
"""
\(attributes)\(access)\(nonisolated)struct \(functionTypeName): \
StructuredQueriesSQLiteCore.\(raw: isAggregate ? "Aggregate" : "Scalar")DatabaseFunction {
public typealias Input = \(raw: representableInputType)
public typealias Output = \(representableOutputType)
public let name = \(databaseFunctionName)
public var argumentCount: Int? {
\(raw: argumentCount)
}
public let isDeterministic = \(raw: isDeterministic)
public let body: \(raw: bodyType)
public init(_ body: @escaping \(raw: bodyType)) {
self.body = body
}
\(raw: methods.map(\.description).joined(separator: "\n"))\
\(raw: canThrowInvalidInvocation ? "\nprivate struct InvalidInvocation: Error {}" : "")
}
""",
]
var decls: [DeclSyntax] = []
let check: String
if isAggregate {
let probeName = context.makeUniqueName("\(declarationName)IsolationProbe")
let isolation: TokenSyntax? =
declaration.modifiers.contains { $0.name.tokenKind == .keyword(.nonisolated) }
? .keyword(.nonisolated, trailingTrivia: .space)
: nil
decls.append(
"""
#if DEBUG
\(isolation)\(`static`)func \(probeName)() {}
#endif
"""
)
check = isolationCheck("function", probeName.text, for: node, in: context)
} else {
check = isolationCheck(
"function",
declaration.name.trimmedDescription,
for: node,
in: context
)
}

decls.append(
contentsOf: [
"""
\(attributes)\(access)\(`static`)\(nonisolated)var $\(raw: declarationName): \
\(functionTypeName) {
\(raw: check)return \(projectedCallSyntax)
}
""",
"""
\(attributes)\(access)\(nonisolated)struct \(functionTypeName): \
StructuredQueriesSQLiteCore.\(raw: isAggregate ? "Aggregate" : "Scalar")DatabaseFunction {
public typealias Input = \(raw: representableInputType)
public typealias Output = \(representableOutputType)
public let name = \(databaseFunctionName)
public var argumentCount: Int? {
\(raw: argumentCount)
}
public let isDeterministic = \(raw: isDeterministic)
public let body: \(raw: bodyType)
public init(_ body: @escaping \(raw: bodyType)) {
self.body = body
}
\(raw: methods.map(\.description).joined(separator: "\n"))\
\(raw: canThrowInvalidInvocation ? "\nprivate struct InvalidInvocation: Error {}" : "")
}
""",
]
)
return decls
}
}

Expand Down
69 changes: 69 additions & 0 deletions Sources/StructuredQueriesSQLiteMacros/IsolationCheckMacro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import SwiftDiagnostics
public import SwiftSyntax
public import SwiftSyntaxMacros

public enum IsolationCheckMacro {}

extension IsolationCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
[]
}
}

public enum MainActorIsolationCheckMacro {}

extension MainActorIsolationCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
let subject: String
switch node.arguments.first?.label?.text {
case "collation":
subject = "'@DatabaseCollation' function"
case "property":
subject = "'@DatabaseFunction' property"
default:
subject = "'@DatabaseFunction' function"
}
context.diagnose(
Diagnostic(
node: node,
message: MacroExpansionErrorMessage(
"\(subject) must be 'nonisolated' when default isolation is '@MainActor'"
)
)
)
return []
}
}

func isolationCheck(
_ label: String,
_ reference: String,
for node: AttributeSyntax,
in context: some MacroExpansionContext
) -> String {
let check = "#StructuredQueriesIsolationCheck(\(label): \(reference))"
guard
let location = context.location(of: node, at: .afterLeadingTrivia, filePathMode: .filePath)
else {
return """
#if DEBUG
\(check)
#endif

"""
}
return """
#if DEBUG
#sourceLocation(file: \(location.file), line: \(location.line))
\(check)
#sourceLocation()
#endif

"""
}
4 changes: 3 additions & 1 deletion Sources/StructuredQueriesSQLiteMacros/Plugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import SwiftSyntaxMacros
@main
struct StructuredQueriesPlugin: CompilerPlugin {
let providingMacros: [any Macro.Type] = [
DatabaseFunctionMacro.self
DatabaseFunctionMacro.self,
IsolationCheckMacro.self,
MainActorIsolationCheckMacro.self,
]
}
Loading