How apple/swift-play-experimental works
Project type and purpose
• This is an open-source Swift tooling library (Swift Play Experimental) that provides:
• A compile-time macro plugin (#Playground) to mark runnable code blocks in any Swift file
• A runtime library for discovering and running those playgrounds
• A Tools API for external tools or IDEs to enumerate and invoke playgrounds
• (Optional) A Swift Package Manager “swift play” prototype CLI that drives the Tools API
• Goal: Enable embedding and launching mini “playgrounds” in production code, without requiring separate .playground bundles.
File structure
• Top Level
• Package.swift – SwiftPM manifest
• README, CONTRIBUTING, LICENSE, etc.
• Sources/
• PlaygroundMacros/
– PlaygroundMacro.swift: Macro definition
– PlaygroundMacrosMain.swift: Plugin entry point
• Playgrounds/
– Discoverable: Defines PlaygroundContent protocols/registrations
– ToolsAPI/EntryPoints: SwiftPMEntryPoint for CLI integration
– ToolsAPI/Playground.swift: Runtime API surface
• Tests/ – Unit tests for both macro expansion and Tools API
README for additional insights
• Feature overview shows how you annotate code with #Playground("Name"){…}
• Tools API exposes functions like __allPlaygrounds(), __getPlayground(named:), __run()
• Example SwiftPM extension uses a swift play command that:
1. Triggers a build (invokes macro plugin)
2. Uses Tools API in the built binary to list/run playgrounds
a. Main components
• Swift compiler + Macro plugin (compile-time)
• PlaygroundMacros module (compiler plugin code)
• Swift code with #Playground annotations
• Playgrounds runtime library (linked into the binary)
• Tools API module (runtime functions for discovery & execution)
• SwiftPM “swift play” CLI or any external tool/IDE
b. Relationships & interactions
1. Developer writes Swift code + #Playground
2. Swift compiler loads the macro plugin (PlaygroundMacros)
– Plugin expands #Playground into registration calls
– Generates synthesized code for registration with Discoverable subsystem
3. Compiler links Playgrounds runtime library into the binary
4. External tool (e.g., swift play) invokes the built binary, calls Tools API
5. Tools API queries internal registry (via Discoverable)
6. Selected playground’s closure is invoked on the runtime side
c. Architectural patterns & principles
• Compiler-plugin + code-generation pattern
• Modular separation: compile-time (macros) vs runtime (library/API)
• Discoverable registry for extensibility
• Clean API boundary for tooling integration
d. Key technologies/frameworks
• Swift Macros system (Swift 5.9+)
• Swift Package Manager plugin/EntryPoint
• Swift Concurrency (async/await) for __run()
• Standard Swift library for runtime
Detail and component separation
• Break out sub-packages (Discoverable vs ToolsAPI)
• Data flow: registration metadata → in-memory registry
• Call out async interactions (e.g., CLI → __run() → user code)
• Platform boundary (macOS support) and future extension points