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
9 changes: 9 additions & 0 deletions Sources/AnyLanguageModel/Generable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ public enum GeneratedContentConversionError: Error {
// MARK: - Macros

/// Conforms a type to ``Generable`` protocol.
///
/// This macro synthesizes a memberwise initializer
/// and an `init(_ generatedContent: GeneratedContent)` initializer
/// for the annotated type.
///
/// - Note: The synthesized memberwise initializer isn't visible inside other macro bodies,
/// such as `#Playground`.
/// As a workaround, use the `init(_ generatedContent:)` initializer
/// or define a factory method on the type.
@attached(extension, conformances: Generable, names: named(init(_:)), named(generatedContent))
@attached(member, names: arbitrary)
public macro Generable(description: String? = nil) =
Expand Down
37 changes: 37 additions & 0 deletions Tests/AnyLanguageModelTests/GenerableMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,40 @@ struct GenerableMacroTests {
#expect(args.asPartiallyGenerated().id == generationID)
}
}

// MARK: - #Playground Usage

// The `#Playground` macro doesn't see the memberwise initializer
// that `@Generable` expands. This is a limitation of how macros compose:
// one macro's expansion isn't visible within another macro's body.
//
// The following code demonstrates workarounds for this limitation.

#if canImport(Playgrounds)
import Playgrounds

// Use the `GeneratedContent` initializer explicitly.
#Playground {
let content = GeneratedContent(properties: [
"name": "Alice",
"age": 30,
])
let _ = try TestArguments(content)
}

// Define a factory method as an alternative to the memberwise initializer.
extension TestArguments {
static func create(name: String, age: Int) -> TestArguments {
try! TestArguments(
GeneratedContent(properties: [
"name": name,
"age": age,
])
)
}
}

#Playground {
let _ = TestArguments.create(name: "Bob", age: 42)
}
#endif // canImport(Playgrounds)