Skip to content

Commit 7f6f0fd

Browse files
committed
Add a public API to look up an infix operator by name.
1 parent c045238 commit 7f6f0fd

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Sources/SwiftOperators/OperatorTable.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,19 @@ public struct OperatorTable {
8383
}
8484

8585
extension OperatorTable {
86+
/// Returns the ``Operator`` corresponding to the given infix operator, or
87+
/// `nil` if it is not defined in the operator table.
88+
public func infixOperator(named operatorName: OperatorName) -> Operator? {
89+
return infixOperators[operatorName]
90+
}
91+
8692
/// Look for the precedence group corresponding to the given operator.
8793
func lookupOperatorPrecedenceGroupName(
8894
_ operatorName: OperatorName,
8995
referencedFrom syntax: Syntax,
9096
errorHandler: OperatorErrorHandler = { throw $0 }
9197
) rethrows -> PrecedenceGroupName? {
92-
guard let op = infixOperators[operatorName] else {
98+
guard let op = infixOperator(named: operatorName) else {
9399
try errorHandler(
94100
.missingOperator(operatorName, referencedFrom: syntax))
95101
return nil

Tests/SwiftOperatorsTest/OperatorTableTests.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,4 +388,21 @@ public class OperatorPrecedenceTests: XCTestCase {
388388
try opPrecedence.assertExpectedFold(
389389
"await x + y + z", "await ((x + y) + z)")
390390
}
391+
392+
func testInfixOperatorLookup() throws {
393+
let opPrecedence = OperatorTable.standardOperators
394+
do {
395+
let op = try XCTUnwrap(opPrecedence.infixOperator(named: "+"))
396+
XCTAssertEqual(op.kind, .infix)
397+
XCTAssertEqual(op.name, "+")
398+
XCTAssertEqual(op.precedenceGroup, "AdditionPrecedence")
399+
}
400+
do {
401+
let op = try XCTUnwrap(opPrecedence.infixOperator(named: "..."))
402+
XCTAssertEqual(op.kind, .infix)
403+
XCTAssertEqual(op.name, "...")
404+
XCTAssertEqual(op.precedenceGroup, "RangeFormationPrecedence")
405+
}
406+
XCTAssertNil(opPrecedence.infixOperator(named: "^*^"))
407+
}
391408
}

0 commit comments

Comments
 (0)