Skip to content

Adding Class and Protocol #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 18, 2025
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
150 changes: 150 additions & 0 deletions Sources/SyntaxKit/Class.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//
// Class.swift
// SyntaxKit
//
// Created by Leo Dion.
// Copyright © 2025 BrightDigit.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//

import SwiftSyntax

/// A Swift `class` declaration.
public struct Class: CodeBlock {
private let name: String
private let members: [CodeBlock]
private var inheritance: [String] = []
private var genericParameters: [String] = []
private var isFinal: Bool = false

/// Creates a `class` declaration.
/// - Parameters:
/// - name: The name of the class.
/// - generics: A list of generic parameters for the class.
/// - content: A ``CodeBlockBuilder`` that provides the members of the class.
public init(
_ name: String,
generics: [String] = [],
@CodeBlockBuilderResult _ content: () -> [CodeBlock]
) {
self.name = name
self.members = content()
self.genericParameters = generics
}

/// Sets one or more inherited types (superclass first followed by any protocols).
/// - Parameter types: The list of types to inherit from.
/// - Returns: A copy of the class with the inheritance set.
public func inherits(_ types: String...) -> Self {
var copy = self
copy.inheritance = types
return copy
}

/// Marks the class declaration as `final`.
/// - Returns: A copy of the class marked as `final`.
public func final() -> Self {
var copy = self
copy.isFinal = true
return copy
}

public var syntax: SyntaxProtocol {
let classKeyword = TokenSyntax.keyword(.class, trailingTrivia: .space)
let identifier = TokenSyntax.identifier(name)

// Generic parameter clause
var genericParameterClause: GenericParameterClauseSyntax?
if !genericParameters.isEmpty {
let parameterList = GenericParameterListSyntax(
genericParameters.enumerated().map { idx, name in
var param = GenericParameterSyntax(name: .identifier(name))
if idx < genericParameters.count - 1 {
param = param.with(
\.trailingComma,
TokenSyntax.commaToken(trailingTrivia: .space)
)
}
return param
}
)
genericParameterClause = GenericParameterClauseSyntax(
leftAngle: .leftAngleToken(),
parameters: parameterList,
rightAngle: .rightAngleToken()
)
}

// Inheritance clause
var inheritanceClause: InheritanceClauseSyntax?
if !inheritance.isEmpty {
let inheritedTypes = inheritance.map { type in
InheritedTypeSyntax(type: IdentifierTypeSyntax(name: .identifier(type)))
}
inheritanceClause = InheritanceClauseSyntax(
colon: .colonToken(),
inheritedTypes: InheritedTypeListSyntax(
inheritedTypes.enumerated().map { idx, inherited in
var inheritedType = inherited
if idx < inheritedTypes.count - 1 {
inheritedType = inheritedType.with(
\.trailingComma,
TokenSyntax.commaToken(trailingTrivia: .space)
)
}
return inheritedType
}
)
)
}

// Member block
let memberBlock = MemberBlockSyntax(
leftBrace: .leftBraceToken(leadingTrivia: .space, trailingTrivia: .newline),
members: MemberBlockItemListSyntax(
members.compactMap { member in
guard let decl = member.syntax.as(DeclSyntax.self) else { return nil }
return MemberBlockItemSyntax(decl: decl, trailingTrivia: .newline)
}
),
rightBrace: .rightBraceToken(leadingTrivia: .newline)
)

// Modifiers
var modifiers: DeclModifierListSyntax = []
if isFinal {
modifiers = DeclModifierListSyntax([
DeclModifierSyntax(name: .keyword(.final, trailingTrivia: .space))
])
}

return ClassDeclSyntax(
modifiers: modifiers,
classKeyword: classKeyword,
name: identifier,
genericParameterClause: genericParameterClause,
inheritanceClause: inheritanceClause,
memberBlock: memberBlock
)
}
}
8 changes: 8 additions & 0 deletions Sources/SyntaxKit/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,14 @@ struct BlackjackCard {
- ``VariableDecl``
- ``Let``
- ``Variable``
- ``Extension``
- ``Class``
- ``Protocol``
- ``Tuple``
- ``TypeAlias``
- ``Infix``
- ``PropertyRequirement``
- ``FunctionRequirement``

### Expressions & Statements
- ``Assignment``
Expand Down
147 changes: 147 additions & 0 deletions Sources/SyntaxKit/FunctionRequirement.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//
// FunctionRequirement.swift
// SyntaxKit
//
// Created by Leo Dion.
// Copyright © 2025 BrightDigit.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//

import SwiftSyntax

/// A function requirement within a protocol declaration (no body).
public struct FunctionRequirement: CodeBlock {
private let name: String
private let parameters: [Parameter]
private let returnType: String?
private var isStatic: Bool = false
private var isMutating: Bool = false

/// Creates a parameterless function requirement.
/// - Parameters:
/// - name: The function name.
/// - returnType: Optional return type.
public init(_ name: String, returns returnType: String? = nil) {
self.name = name
self.parameters = []
self.returnType = returnType
}

/// Creates a function requirement with parameters.
/// - Parameters:
/// - name: The function name.
/// - returnType: Optional return type.
/// - params: A ParameterBuilderResult providing the parameters.
public init(
_ name: String, returns returnType: String? = nil,
@ParameterBuilderResult _ params: () -> [Parameter]
) {
self.name = name
self.parameters = params()
self.returnType = returnType
}

/// Marks the function requirement as `static`.
public func `static`() -> Self {
var copy = self
copy.isStatic = true
return copy
}

/// Marks the function requirement as `mutating`.
public func mutating() -> Self {
var copy = self
copy.isMutating = true
return copy
}

public var syntax: SyntaxProtocol {
let funcKeyword = TokenSyntax.keyword(.func, trailingTrivia: .space)
let identifier = TokenSyntax.identifier(name)

// Parameters
let paramList: FunctionParameterListSyntax
if parameters.isEmpty {
paramList = FunctionParameterListSyntax([])
} else {
paramList = FunctionParameterListSyntax(
parameters.enumerated().compactMap { index, param in
guard !param.name.isEmpty, !param.type.isEmpty else { return nil }
var paramSyntax = FunctionParameterSyntax(
firstName: param.isUnnamed
? .wildcardToken(trailingTrivia: .space) : .identifier(param.name),
secondName: param.isUnnamed ? .identifier(param.name) : nil,
colon: .colonToken(leadingTrivia: .space, trailingTrivia: .space),
type: IdentifierTypeSyntax(name: .identifier(param.type)),
defaultValue: param.defaultValue.map {
InitializerClauseSyntax(
equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space),
value: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier($0)))
)
}
)
if index < parameters.count - 1 {
paramSyntax = paramSyntax.with(\.trailingComma, .commaToken(trailingTrivia: .space))
}
return paramSyntax
})
}

// Return clause
var returnClause: ReturnClauseSyntax?
if let returnType = returnType {
returnClause = ReturnClauseSyntax(
arrow: .arrowToken(leadingTrivia: .space, trailingTrivia: .space),
type: IdentifierTypeSyntax(name: .identifier(returnType))
)
}

// Modifiers
var modifiers: DeclModifierListSyntax = []
if isStatic {
modifiers = DeclModifierListSyntax([
DeclModifierSyntax(name: .keyword(.static, trailingTrivia: .space))
])
}
if isMutating {
modifiers = DeclModifierListSyntax(
modifiers + [DeclModifierSyntax(name: .keyword(.mutating, trailingTrivia: .space))]
)
}

return FunctionDeclSyntax(
attributes: AttributeListSyntax([]),
modifiers: modifiers,
funcKeyword: funcKeyword,
name: identifier,
signature: FunctionSignatureSyntax(
parameterClause: FunctionParameterClauseSyntax(
leftParen: .leftParenToken(), parameters: paramList, rightParen: .rightParenToken()
),
effectSpecifiers: nil,
returnClause: returnClause
),
body: nil
)
}
}
Loading
Loading