Skip to content

Commit

Permalink
WIP: Make convenience initializers with CodeGeneration
Browse files Browse the repository at this point in the history
  • Loading branch information
natikgadzhi committed Sep 2, 2023
1 parent 29c1564 commit 03c20f8
Show file tree
Hide file tree
Showing 6 changed files with 192 additions and 21 deletions.
8 changes: 8 additions & 0 deletions CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ public let ATTRIBUTE_NODES: [Node] = [
nameForDiagnostics: "attribute",
documentation: "An `@` attribute.",
parserFunction: "parseAttribute",
rules: [
NodeInitRule(
nonOptionalChildName: "arguments",
childDefaultValues: [
"leftParen": .leftParen,
"rightParen": .rightParen
])
],
children: [
Child(
name: "atSign",
Expand Down
16 changes: 16 additions & 0 deletions CodeGeneration/Sources/SyntaxSupport/Node.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ public class Node {
return kind.varOrCaseName
}

/// List of convenience initializer rules for this node.
public let rules: [NodeInitRule]

/// If this is a layout node, return a view of the node that provides access
/// to the layout-node specific properties.
public var layoutNode: LayoutNode? {
Expand Down Expand Up @@ -112,6 +115,7 @@ public class Node {
documentation: String? = nil,
parserFunction: TokenSyntax? = nil,
traits: [String] = [],
rules: [NodeInitRule] = [],
children: [Child] = []
) {
precondition(base != .syntaxCollection)
Expand All @@ -124,6 +128,11 @@ public class Node {
self.documentation = docCommentTrivia(from: documentation)
self.parserFunction = parserFunction


// FIXME: We should validate rules and check that all referenced children
// elements in fact exist on that node.
self.rules = rules

let childrenWithUnexpected: [Child]
if children.isEmpty {
childrenWithUnexpected = [
Expand Down Expand Up @@ -229,6 +238,7 @@ public class Node {
isExperimental: Bool = false,
nameForDiagnostics: String?,
documentation: String? = nil,
rules: [NodeInitRule] = [],
parserFunction: TokenSyntax? = nil,
elementChoices: [SyntaxNodeKind]
) {
Expand All @@ -239,6 +249,7 @@ public class Node {
self.nameForDiagnostics = nameForDiagnostics
self.documentation = docCommentTrivia(from: documentation)
self.parserFunction = parserFunction
self.rules = rules

assert(!elementChoices.isEmpty)
self.data = .collection(choices: elementChoices)
Expand Down Expand Up @@ -380,3 +391,8 @@ fileprivate extension Child {
fileprivate extension Node {

}

public struct NodeInitRule {
public let nonOptionalChildName: String
public let childDefaultValues: [String: Token]
}
2 changes: 1 addition & 1 deletion CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public extension Child {

/// If the child node has a default value, return an expression of the form
/// ` = default_value` that can be used as the default value to for a
/// function parameter. Otherwise, return `nil`.
/// function parameter. Otherwise, return `nil`.]
var defaultInitialization: InitializerClauseSyntax? {
if let defaultValue {
return InitializerClauseSyntax(equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space), value: defaultValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,52 +16,114 @@ import SyntaxSupport
import Utils

extension LayoutNode {
func generateInitializerDeclHeader(useDeprecatedChildName: Bool = false) -> SyntaxNodeString {

func makeChildParamType(for child: Child, isOptional: Bool = false) -> TypeSyntax {
var paramType: TypeSyntax

if !child.kind.isNodeChoicesEmpty {
paramType = "\(child.syntaxChoicesType)"
} else if child.hasBaseType {
paramType = "some \(child.syntaxNodeKind.protocolType)"
} else {
paramType = child.syntaxNodeKind.syntaxType
}

if isOptional {
if paramType.is(SomeOrAnyTypeSyntax.self) {
paramType = "(\(paramType))?"
} else {
paramType = "\(paramType)?"
}
}

return paramType
}

/// Generates a memberwise SyntaxNode initializer `SyntaxNodeString`.
///
/// - parameters:
/// - rule: The ``NodeInitRule`` to use for generating the initializer. Applying a rule will make some children non-optional, and set default values for other children.
/// - useDeprecatedChildName: Whether to use the deprecated child name for the initializer parameter.
func generateInitializerDeclHeader(for rule: NodeInitRule? = nil, useDeprecatedChildName: Bool = false) -> SyntaxNodeString {
if children.isEmpty {
return "public init()"
}

func createFunctionParameterSyntax(for child: Child) -> FunctionParameterSyntax {
var paramType: TypeSyntax
if !child.kind.isNodeChoicesEmpty {
paramType = "\(child.syntaxChoicesType)"
} else if child.hasBaseType {
paramType = "some \(child.syntaxNodeKind.protocolType)"
func childParameterName(for child: Child) -> TokenSyntax {
let parameterName: TokenSyntax

if useDeprecatedChildName, let deprecatedVarName = child.deprecatedVarName {
parameterName = deprecatedVarName
} else {
paramType = child.syntaxNodeKind.syntaxType
parameterName = child.varOrCaseName
}
return parameterName
}

if child.isOptional {
if paramType.is(SomeOrAnyTypeSyntax.self) {
paramType = "(\(paramType))?"
func ruleBasedChildIsOptional(for child: Child, with rule: NodeInitRule?) -> Bool? {
if let rule = rule {
if rule.nonOptionalChildName == child.name {
return false
} else {
paramType = "\(paramType)?"
return child.isOptional
}
} else {
return nil
}
}

let parameterName: TokenSyntax
func ruleBasedChildDefaultValue(for child: Child, with rule: NodeInitRule?) -> InitializerClauseSyntax? {
if let rule, let defaultValue = rule.childDefaultValues[child.name] {
return InitializerClauseSyntax(
equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space),
value: ExprSyntax(".\(defaultValue.spec.varOrCaseName)Token()")
)
} else {
return nil
}
}

if useDeprecatedChildName, let deprecatedVarName = child.deprecatedVarName {
parameterName = deprecatedVarName
func ruleBasedShouldOverrideDefault(for child: Child, with rule: NodeInitRule?) -> Bool {
if let rule {
// If the rule provides a default for this child, override it and set the rule-based default.
if rule.childDefaultValues[child.name] != nil {
return true
}

// For the non-optional rule-based parameter, strip the default value (override, but there will be no default)
return rule.nonOptionalChildName == child.name
} else {
parameterName = child.varOrCaseName
return false
}
}

func createFunctionParameterSyntax(for child: Child, overrideOptional: Bool? = nil, shouldOverrideDefault: Bool = false, overrideDefaultValue: InitializerClauseSyntax? = nil) -> FunctionParameterSyntax {

let parameterName = childParameterName(for: child)

return FunctionParameterSyntax(
leadingTrivia: .newline,
firstName: child.isUnexpectedNodes ? .wildcardToken(trailingTrivia: .space) : parameterName,
secondName: child.isUnexpectedNodes ? parameterName : nil,
colon: .colonToken(),
type: paramType,
defaultValue: child.defaultInitialization
type: makeChildParamType(for: child, isOptional: overrideOptional ?? child.isOptional),
defaultValue: shouldOverrideDefault ? overrideDefaultValue : child.defaultInitialization
)
}

// For convenience initializers, we don't need unexpected tokens in the arguments list
// because convenience initializers are meant to be used bo developers manually
// hence there should be no unexpected tokens
let childrenToIterate = rule != nil ? nonUnexpectedChildren : children

let params = FunctionParameterListSyntax {
FunctionParameterSyntax("leadingTrivia: Trivia? = nil")

for child in children {
createFunctionParameterSyntax(for: child)
for child in childrenToIterate {
createFunctionParameterSyntax(for: child,
overrideOptional: ruleBasedChildIsOptional(for: child, with: rule),
shouldOverrideDefault: ruleBasedShouldOverrideDefault(for: child, with: rule),
overrideDefaultValue: ruleBasedChildDefaultValue(for: child, with: rule))
}

FunctionParameterSyntax("trailingTrivia: Trivia? = nil")
Expand All @@ -75,6 +137,14 @@ extension LayoutNode {
"""
}

func generateRuleBasedDefaultValuesDocComment(for rule: NodeInitRule) -> SwiftSyntax.Trivia {
var params = ""
for (childName, defaultValue) in rule.childDefaultValues {
params += " - `\(childName)`: `TokenSyntax.\(defaultValue.spec.varOrCaseName)Token()`\n"
}
return docCommentTrivia(from: params)
}

func generateInitializerDocComment() -> SwiftSyntax.Trivia {
func generateParamDocComment(for child: Child) -> String? {
if child.documentationAbstract.isEmpty {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,55 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
"""
)

for rule in node.rules {
try! InitializerDeclSyntax(
"""
/// A convenience initializer for ``\(node.kind.syntaxType)``
/// that takes a non-optional value for `\(raw: rule.nonOptionalChildName)` parameter,
/// and adds the following default values:
\(node.generateRuleBasedDefaultValuesDocComment(for: rule))
\(node.generateInitializerDeclHeader(for: rule))
"""
) {
// Convenience initializer just calls the full initializer
// with certain child parameters specified as optional types
// and providing the rule-based default value for the affected
// parameters.
FunctionCallExprSyntax(
calledExpression: ExprSyntax("self.init"),
leftParen: .leftParenToken(),
arguments: LabeledExprListSyntax {
LabeledExprSyntax(
label: TokenSyntax("leadingTrivia"),
colon: .colonToken(),
expression: ExprSyntax("leadingTrivia"),
trailingComma: .commaToken()
)

for child in node.nonUnexpectedChildren {
LabeledExprSyntax(
label: child.varOrCaseName,
colon: .colonToken(),
expression: rule.nonOptionalChildName == child.name ? ExprSyntax("\(child.varOrCaseName.backtickedIfNeeded) as \(node.makeChildParamType(for: child, isOptional: true))") : ExprSyntax("\(child.varOrCaseName.backtickedIfNeeded)"),
trailingComma: .commaToken()
)
}

LabeledExprSyntax(
label: TokenSyntax("trailingTrivia"),
colon: .colonToken(),
expression: ExprSyntax("trailingTrivia")
)
},
rightParen: .rightParenToken()
)
}
}

// The main member-wise initializer
// generateInitializerDocComment renders DocC comment
// generateInitializerDeclHeader renders the actual init declaration
// and lists out all it's parameters and their default values
try! InitializerDeclSyntax(
"""
\(node.generateInitializerDocComment())
Expand All @@ -100,6 +149,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
)
)
)

let layoutList = ArrayExprSyntax {
for child in node.children {
ArrayElementSyntax(
Expand Down
27 changes: 27 additions & 0 deletions Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2575,6 +2575,33 @@ public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable {
self._syntaxNode = Syntax(data)
}

/// A convenience initializer for ``AttributeSyntax``
/// that takes a non-optional value for `arguments` parameter,
/// and adds the following default values:
/// - `rightParen`: `TokenSyntax.rightParenToken()`
/// - `leftParen`: `TokenSyntax.leftParenToken()`
///
public init(
leadingTrivia: Trivia? = nil,
atSign: TokenSyntax = .atSignToken(),
attributeName: some TypeSyntaxProtocol,
leftParen: TokenSyntax? = .leftParenToken(),
arguments: Arguments,
rightParen: TokenSyntax? = .rightParenToken(),
trailingTrivia: Trivia? = nil

) {
self.init(
leadingTrivia: leadingTrivia,
atSign: atSign,
attributeName: attributeName,
leftParen: leftParen,
arguments: arguments as Arguments?,
rightParen: rightParen,
trailingTrivia: trailingTrivia
)
}

/// - Parameters:
/// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored.
/// - atSign: The `@` sign.
Expand Down

0 comments on commit 03c20f8

Please sign in to comment.