Skip to content

Accessor decl interpolation #1216

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 4 commits into from
Jan 11, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,7 @@ public let DECL_NODES: [Node] = [
traits: [
"Attributed"
],
parserFunction: "parseAccessorDecl",
children: [
Child(name: "Attributes",
kind: "AttributeList",
Expand Down
123 changes: 70 additions & 53 deletions Sources/SwiftParser/Declarations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1547,12 +1547,14 @@ extension Parser {
var token: RawTokenSyntax
}

mutating func parseAccessorIntroducer() -> AccessorIntroducer? {
mutating func parseAccessorIntroducer(
forcedKind: (AccessorKind, TokenConsumptionHandle)? = nil
) -> AccessorIntroducer? {
// Check there is an identifier before consuming
var look = self.lookahead()
let _ = look.consumeAttributeList()
let hasModifier = look.consume(ifAny: [.contextualKeyword(.mutating), .contextualKeyword(.nonmutating), .contextualKeyword(.__consuming)]) != nil
guard let (kind, handle) = look.at(anyIn: AccessorKind.self) else {
guard let (kind, handle) = look.at(anyIn: AccessorKind.self) ?? forcedKind else {
return nil
}

Expand Down Expand Up @@ -1615,15 +1617,18 @@ extension Parser {
return specifiers
}

/// Parse the body of a variable declaration. This can include explicit
/// getters, setters, and observers, or the body of a computed property.
/// Parse an accessor.
mutating func parseAccessorDecl() -> RawAccessorDeclSyntax {
let forcedHandle = TokenConsumptionHandle(tokenKind: .contextualKeyword(.get), missing: true)
let introducer = parseAccessorIntroducer(forcedKind: (.get, forcedHandle))!
return parseAccessorDecl(introducer: introducer)
}

/// Parse an accessor once we know we have an introducer
///
/// Grammar
/// =======
///
/// getter-setter-block → code-block
/// getter-setter-block → { getter-clause setter-clause opt }
/// getter-setter-block → { setter-clause getter-clause }
/// getter-clause → attributes opt mutation-modifier opt get code-block
/// setter-clause → attributes opt mutation-modifier opt set setter-name opt code-block
/// setter-name → ( identifier )
Expand All @@ -1635,6 +1640,63 @@ extension Parser {
/// willSet-didSet-block → { didSet-clause willSet-clause opt }
/// willSet-clause → attributes opt willSet setter-name opt code-block
/// didSet-clause → attributes opt didSet setter-name opt code-block
private mutating func parseAccessorDecl(
introducer: AccessorIntroducer
) -> RawAccessorDeclSyntax {
// 'set' and 'willSet' can have an optional name. This isn't valid in a
// protocol, but we parse and then reject it for better QoI.
//
// set-name ::= '(' identifier ')'
let parameter: RawAccessorParameterSyntax?
if [AccessorKind.set, .willSet, .didSet].contains(introducer.kind), let lparen = self.consume(if: .leftParen) {
let (unexpectedBeforeName, name) = self.expectIdentifier()
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
parameter = RawAccessorParameterSyntax(
leftParen: lparen,
unexpectedBeforeName,
name: name,
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena
)
} else {
parameter = nil
}

// Next, parse effects specifiers. While it's only valid to have them
// on 'get' accessors, we also emit diagnostics if they show up on others.
let asyncKeyword: RawTokenSyntax?
let throwsKeyword: RawTokenSyntax?
if self.at(anyIn: EffectsSpecifier.self) != nil {
asyncKeyword = self.parseEffectsSpecifier()
throwsKeyword = self.parseEffectsSpecifier()
} else {
asyncKeyword = nil
throwsKeyword = nil
}

let body = self.parseOptionalCodeBlock()
return RawAccessorDeclSyntax(
attributes: introducer.attributes,
modifier: introducer.modifier,
accessorKind: introducer.token,
parameter: parameter,
asyncKeyword: asyncKeyword,
throwsKeyword: throwsKeyword,
body: body,
arena: self.arena
)
}

/// Parse the body of a variable declaration. This can include explicit
/// getters, setters, and observers, or the body of a computed property.
///
/// Grammar
/// =======
///
/// getter-setter-block → code-block
/// getter-setter-block → { getter-clause setter-clause opt }
/// getter-setter-block → { setter-clause getter-clause }
@_spi(RawSyntax)
public mutating func parseGetSet() -> RawSubscriptDeclSyntax.Accessor {
// Parse getter and setter.
Expand Down Expand Up @@ -1689,52 +1751,7 @@ extension Parser {
)
}

// 'set' and 'willSet' can have an optional name. This isn't valid in a
// protocol, but we parse and then reject it for better QoI.
//
// set-name ::= '(' identifier ')'
let parameter: RawAccessorParameterSyntax?
if [AccessorKind.set, .willSet, .didSet].contains(introducer.kind), let lparen = self.consume(if: .leftParen) {
let (unexpectedBeforeName, name) = self.expectIdentifier()
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
parameter = RawAccessorParameterSyntax(
leftParen: lparen,
unexpectedBeforeName,
name: name,
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena
)
} else {
parameter = nil
}

// Next, parse effects specifiers. While it's only valid to have them
// on 'get' accessors, we also emit diagnostics if they show up on others.
let asyncKeyword: RawTokenSyntax?
let throwsKeyword: RawTokenSyntax?
if self.at(anyIn: EffectsSpecifier.self) != nil {
asyncKeyword = self.parseEffectsSpecifier()
throwsKeyword = self.parseEffectsSpecifier()
} else {
asyncKeyword = nil
throwsKeyword = nil
}

let body = self.parseOptionalCodeBlock()

elements.append(
RawAccessorDeclSyntax(
attributes: introducer.attributes,
modifier: introducer.modifier,
accessorKind: introducer.token,
parameter: parameter,
asyncKeyword: asyncKeyword,
throwsKeyword: throwsKeyword,
body: body,
arena: self.arena
)
)
elements.append(parseAccessorDecl(introducer: introducer))
}
}

Expand Down
8 changes: 8 additions & 0 deletions Sources/SwiftParser/generated/Parser+Entry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ public protocol SyntaxParseable: SyntaxProtocol {
static func parse(from parser: inout Parser) -> Self
}

extension AccessorDeclSyntax: SyntaxParseable {
public static func parse(from parser: inout Parser) -> Self {
let node = parser.parseAccessorDecl()
let raw = RawSyntax(parser.parseRemainder(into: node))
return Syntax(raw: raw).cast(Self.self)
}
}

extension AttributeSyntax: SyntaxParseable {
public static func parse(from parser: inout Parser) -> Self {
let node = parser.parseAttribute()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ extension SyntaxParseable {
}
}

extension AccessorDeclSyntax: SyntaxExpressibleByStringInterpolation {
extension AccessorDeclSyntax: SyntaxExpressibleByStringInterpolation {
public init(stringInterpolationOrThrow stringInterpolation: SyntaxStringInterpolation) throws {
self = try performParse(source: stringInterpolation.sourceText, parse: { parser in
return Self.parse(from: &parser)
})
}
}

extension ActorDeclSyntax: SyntaxExpressibleByStringInterpolation {
Expand Down
2 changes: 1 addition & 1 deletion Sources/_SwiftSyntaxMacros/PeerDeclarationMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public protocol PeerDeclarationMacro: DeclarationMacro {
/// particular expansion context.
///
/// The macro expansion can introduce "peer" declarations that sit alongside
/// the
/// the given declaration.
static func expansion(
of node: CustomAttributeSyntax,
attachedTo declaration: DeclSyntax,
Expand Down
18 changes: 18 additions & 0 deletions Tests/SwiftSyntaxBuilderTest/StringInterpolation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -421,4 +421,22 @@ final class StringInterpolationTests: XCTestCase {
"""
)
}

func testAccessorInterpolation() {
let setter: AccessorDeclSyntax =
"""
set(newValue) {
_storage = newValue
}
"""
XCTAssertTrue(setter.is(AccessorDeclSyntax.self))
AssertStringsEqualWithDiff(
setter.description,
"""
set(newValue) {
_storage = newValue
}
"""
)
}
}
1 change: 1 addition & 0 deletions gyb_syntax_support/DeclNodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@

Node('AccessorDecl', name_for_diagnostics='accessor', kind='Decl',
traits=['Attributed'],
parser_function='parseAccessorDecl',
children=[
Child('Attributes', kind='AttributeList', name_for_diagnostics='attributes',
collection_element_name='Attribute', is_optional=True),
Expand Down