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
50 changes: 50 additions & 0 deletions Examples/card_game/code.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Foundation

// MARK: - Models
/// Represents a playing card in a standard 52-card deck
///
/// A card has a rank (2-10, J, Q, K, A) and a suit (hearts, diamonds, clubs, spades).
/// Each card can be compared to other cards based on its rank.
struct Card: Comparable {
/// The rank of the card (2-10, J, Q, K, A)
let rank: Rank
/// The suit of the card (hearts, diamonds, clubs, spades)
let suit: Suit
}

// MARK: - Enums
/// Represents the possible ranks of a playing card
enum Rank: Int, CaseIterable {
case two = 2
case three
case four
case five
case six
case seven
case eight
case nine
case ten
case jack
case queen
case king
case ace

/// Returns a string representation of the rank
var description: String {
switch self {
case .jack: return "J"
case .queen: return "Q"
case .king: return "K"
case .ace: return "A"
default: return "\(rawValue)"
}
}
}

/// Represents the four suits in a standard deck of cards
enum Suit: String, CaseIterable {
case hearts = "♥"
case diamonds = "♦"
case clubs = "♣"
case spades = "♠"
}
98 changes: 98 additions & 0 deletions Examples/card_game/dsl.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import SwiftBuilder

// Example of generating a BlackjackCard struct with a nested Suit enum
let structExample = Group {
Struct("Card") {
Variable(.let, name: "rank", type: "Rank")
.comment{
Line(.doc, "The rank of the card (2-10, J, Q, K, A)")
}
Variable(.let, name: "suit", type: "Suit")
.comment{
Line(.doc, "The suit of the card (hearts, diamonds, clubs, spades)")
}
}
.inherits("Comparable")
.comment{
Line("MARK: - Models")
Line(.doc, "Represents a playing card in a standard 52-card deck")
Line(.doc)
Line(.doc, "A card has a rank (2-10, J, Q, K, A) and a suit (hearts, diamonds, clubs, spades).")
Line(.doc, "Each card can be compared to other cards based on its rank.")
}

Enum("Rank") {
EnumCase("two").equals(2)
EnumCase("three")
EnumCase("four")
EnumCase("five")
EnumCase("six")
EnumCase("seven")
EnumCase("eight")
EnumCase("nine")
EnumCase("ten")
EnumCase("jack")
EnumCase("queen")
EnumCase("king")
EnumCase("ace")
Struct("Values") {
Variable(.let, name: "first", type: "Int")
Variable(.let, name: "second", type: "Int?")
}
ComputedProperty("description") {
Switch("self") {
SwitchCase(".jack") {
Return{
Literal("\"J\"")
}
}
SwitchCase(".queen") {
Return{
Literal("\"Q\"")
}
}
SwitchCase(".king") {
Return{
Literal("\"K\"")
}
}
SwitchCase(".ace") {
Return{
Literal("\"A\"")
}
}
Default {
Return{
Literal("\\(rawValue)")
}
}
}
}
.comment{
Line(.doc, "Returns a string representation of the rank")
}
}
.inherits("Int")
.inherits("CaseIterable")
.comment{
Line("MARK: - Enums")
Line(.doc, "Represents the possible ranks of a playing card")
}

Enum("Suit") {
EnumCase("spades").equals("♠")
EnumCase("hearts").equals("♡")
EnumCase("diamonds").equals("♢")
EnumCase("clubs").equals("♣")
}
.inherits("String")
.inherits("CaseIterable")
.comment{
Line(.doc, "Represents the possible suits of a playing card")
}

}


// Generate and print the code
print(structExample.generateCode())
1 change: 1 addition & 0 deletions Examples/card_game/syntax.json

Large diffs are not rendered by default.

120 changes: 120 additions & 0 deletions Examples/comments/code.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import Foundation

// MARK: - Single Line Comments
// This is a basic single-line comment
// You can use it for quick notes or explanations

// MARK: - Multi-line Comments
/*
This is a multi-line comment
It can span multiple lines
Useful for longer explanations
*/

// MARK: - Documentation Comments
/// A simple calculator that performs basic arithmetic operations
///
/// This class provides methods for addition, subtraction, multiplication,
/// and division. It also includes error handling for division by zero.
///
/// Example usage:
/// ```swift
/// let calc = Calculator()
/// let sum = calc.add(5, 3) // Returns 8
/// ```
class Calculator {
/// Adds two numbers together
/// - Parameters:
/// - a: The first number
/// - b: The second number
/// - Returns: The sum of the two numbers
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}

/// Subtracts the second number from the first
/// - Parameters:
/// - a: The number to subtract from
/// - b: The number to subtract
/// - Returns: The difference between the two numbers
func subtract(_ a: Int, _ b: Int) -> Int {
return a - b
}

/// Multiplies two numbers
/// - Parameters:
/// - a: The first number
/// - b: The second number
/// - Returns: The product of the two numbers
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}

/// Divides the first number by the second
/// - Parameters:
/// - a: The dividend
/// - b: The divisor
/// - Returns: The quotient of the division
/// - Throws: `CalculatorError.divisionByZero` if the divisor is zero
func divide(_ a: Int, _ b: Int) throws -> Double {
guard b != 0 else {
throw CalculatorError.divisionByZero
}
return Double(a) / Double(b)
}
}

// MARK: - Error Types
/// Errors that can occur during calculator operations
enum CalculatorError: Error {
/// Thrown when attempting to divide by zero
case divisionByZero
}

// MARK: - TODO Comments
// TODO: Add support for decimal numbers
// TODO: Implement square root function
// TODO: Add unit tests

// MARK: - FIXME Comments
// FIXME: Handle negative numbers in division
// FIXME: Add input validation

// MARK: - MARK Comments
// MARK: - Properties
// MARK: - Initialization
// MARK: - Public Methods
// MARK: - Private Methods

// MARK: - Section Comments
// ======================
// Section: Configuration
// ======================

// MARK: - Code Organization Comments
// Group: Math Operations
// Category: Arithmetic
// Module: Calculator

// MARK: - Usage Example
let calculator = Calculator()

// Example of using documented functions
do {
let sum = calculator.add(10, 5)
print("Sum: \(sum)") // Prints: Sum: 15

let difference = calculator.subtract(10, 5)
print("Difference: \(difference)") // Prints: Difference: 5

let product = calculator.multiply(10, 5)
print("Product: \(product)") // Prints: Product: 50

let quotient = try calculator.divide(10, 5)
print("Quotient: \(quotient)") // Prints: Quotient: 2.0

// This will throw an error
let error = try calculator.divide(10, 0)
} catch CalculatorError.divisionByZero {
print("Error: Division by zero is not allowed")
}
88 changes: 88 additions & 0 deletions Examples/concurrency/code.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import Foundation

// MARK: - Async Functions
func fetchUserData(id: Int) async throws -> String {
// Simulate network delay
try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
return "User data for ID: \(id)"
}

func fetchUserPosts(id: Int) async throws -> [String] {
// Simulate network delay
try await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return ["Post 1", "Post 2", "Post 3"]
}

// MARK: - Async Sequence
struct Countdown: AsyncSequence {
let start: Int

struct AsyncIterator: AsyncIteratorProtocol {
var count: Int

mutating func next() async -> Int? {
guard count > 0 else { return nil }
try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
let current = count
count -= 1
return current
}
}

func makeAsyncIterator() -> AsyncIterator {
AsyncIterator(count: start)
}
}

// MARK: - Task Groups
func fetchMultipleUsers(ids: [Int]) async throws -> [String] {
try await withThrowingTaskGroup(of: String.self) { group in
for id in ids {
group.addTask {
try await fetchUserData(id: id)
}
}

var results: [String] = []
for try await result in group {
results.append(result)
}
return results
}
}

// MARK: - Usage Example
@main
struct ConcurrencyExample {
static func main() async {
do {
// Demonstrate basic async/await
print("Fetching user data...")
let userData = try await fetchUserData(id: 1)
print(userData)

// Demonstrate concurrent tasks
print("\nFetching user data and posts concurrently...")
async let data = fetchUserData(id: 1)
async let posts = fetchUserPosts(id: 1)
let (fetchedData, fetchedPosts) = try await (data, posts)
print("Data: \(fetchedData)")
print("Posts: \(fetchedPosts)")

// Demonstrate async sequence
print("\nStarting countdown:")
for await number in Countdown(start: 3) {
print(number)
}
print("Liftoff!")

// Demonstrate task groups
print("\nFetching multiple users:")
let users = try await fetchMultipleUsers(ids: [1, 2, 3])
print(users)

} catch {
print("Error: \(error)")
}
}
}
Loading