Skip to content

Commit 1552f52

Browse files
committed
Add the ability to synthesize syntax for an operator
1 parent 701340b commit 1552f52

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//===------------------ SyntaxSynthesis.swift -----------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import SwiftSyntax
14+
15+
extension Operator {
16+
/// Synthesize a syntactic representation of this operator based on its
17+
/// semantic definition.
18+
public func synthesizedSyntax() -> OperatorDeclSyntax {
19+
let modifiers = ModifierListSyntax(
20+
[DeclModifierSyntax(name: .identifier("\(kind)"), detail: nil)]
21+
)
22+
let operatorKeyword = TokenSyntax.operatorKeyword(leadingTrivia: .spaces(1))
23+
let identifierSyntax =
24+
TokenSyntax.identifier(name, leadingTrivia: .spaces(1))
25+
let precedenceGroupSyntax = precedenceGroup.map { groupName in
26+
OperatorPrecedenceAndTypesSyntax(
27+
colon: .colonToken(),
28+
precedenceGroupAndDesignatedTypes: IdentifierListSyntax(
29+
[.identifier(groupName, leadingTrivia: .spaces(1))]
30+
)
31+
)
32+
}
33+
34+
return OperatorDeclSyntax(
35+
attributes: nil, modifiers: modifiers, operatorKeyword: operatorKeyword,
36+
identifier: identifierSyntax,
37+
operatorPrecedenceAndTypes: precedenceGroupSyntax
38+
)
39+
}
40+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//===------------------ SyntaxSynthesisTests.swift ------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
import XCTest
13+
import SwiftSyntax
14+
import SwiftOperators
15+
16+
public class SyntaxSynthesisTests: XCTestCase {
17+
func testInfixOperator() {
18+
let plus = Operator(
19+
kind: .infix, name: "+", precedenceGroup: "AdditivePrecedence")
20+
let plusSyntax = plus.synthesizedSyntax()
21+
XCTAssertEqual(
22+
plusSyntax.description, "infix operator +: AdditivePrecedence")
23+
}
24+
}

0 commit comments

Comments
 (0)