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 1, 2023
1 parent 29c1564 commit 2d01e9c
Show file tree
Hide file tree
Showing 6 changed files with 150 additions and 13 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,12 +16,65 @@ import SyntaxSupport
import Utils

extension LayoutNode {
func generateInitializerDeclHeader(useDeprecatedChildName: Bool = false) -> SyntaxNodeString {
/// 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 {
func childParameterName(for child: Child) -> TokenSyntax {
let parameterName: TokenSyntax

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

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

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
}
}

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 {
return false
}
}

func createFunctionParameterSyntax(for child: Child, overrideOptional: Bool? = nil, shouldOverrideDefault: Bool = false, overrideDefaultValue: InitializerClauseSyntax? = nil) -> FunctionParameterSyntax {
var paramType: TypeSyntax
if !child.kind.isNodeChoicesEmpty {
paramType = "\(child.syntaxChoicesType)"
Expand All @@ -31,37 +84,34 @@ extension LayoutNode {
paramType = child.syntaxNodeKind.syntaxType
}

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

let parameterName: TokenSyntax

if useDeprecatedChildName, let deprecatedVarName = child.deprecatedVarName {
parameterName = deprecatedVarName
} else {
parameterName = child.varOrCaseName
}
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
defaultValue: shouldOverrideDefault ? overrideDefaultValue : child.defaultInitialization
)
}

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

for child in children {
createFunctionParameterSyntax(for: child)
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 +125,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,35 @@ 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 {
// generate the list of children for the call site.
},
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 +129,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax {
)
)
)

let layoutList = ArrayExprSyntax {
for child in node.children {
ArrayElementSyntax(
Expand Down
25 changes: 25 additions & 0 deletions Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2575,6 +2575,31 @@ 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`: `rightParen`
/// - `leftParen`: `leftParen`
///
public init(
leadingTrivia: Trivia? = nil,
_ unexpectedBeforeAtSign: UnexpectedNodesSyntax? = nil,
atSign: TokenSyntax = .atSignToken(),
_ unexpectedBetweenAtSignAndAttributeName: UnexpectedNodesSyntax? = nil,
attributeName: some TypeSyntaxProtocol,
_ unexpectedBetweenAttributeNameAndLeftParen: UnexpectedNodesSyntax? = nil,
leftParen: TokenSyntax? = .leftParenToken(),
_ unexpectedBetweenLeftParenAndArguments: UnexpectedNodesSyntax? = nil,
arguments: Arguments,
_ unexpectedBetweenArgumentsAndRightParen: UnexpectedNodesSyntax? = nil,
rightParen: TokenSyntax? = .rightParenToken(),
_ unexpectedAfterRightParen: UnexpectedNodesSyntax? = nil,
trailingTrivia: Trivia? = nil

) {
self.init()
}

/// - 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 2d01e9c

Please sign in to comment.