Skip to content

Add a public API to look up an infix operator by name. #810

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 1 commit into from
Sep 18, 2022
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
8 changes: 7 additions & 1 deletion Sources/SwiftOperators/OperatorTable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,19 @@ public struct OperatorTable {
}

extension OperatorTable {
/// Returns the ``Operator`` corresponding to the given infix operator, or
/// `nil` if it is not defined in the operator table.
public func infixOperator(named operatorName: OperatorName) -> Operator? {
return infixOperators[operatorName]
}

/// Look for the precedence group corresponding to the given operator.
func lookupOperatorPrecedenceGroupName(
_ operatorName: OperatorName,
referencedFrom syntax: Syntax,
errorHandler: OperatorErrorHandler = { throw $0 }
) rethrows -> PrecedenceGroupName? {
guard let op = infixOperators[operatorName] else {
guard let op = infixOperator(named: operatorName) else {
try errorHandler(
.missingOperator(operatorName, referencedFrom: syntax))
return nil
Expand Down
17 changes: 17 additions & 0 deletions Tests/SwiftOperatorsTest/OperatorTableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -388,4 +388,21 @@ public class OperatorPrecedenceTests: XCTestCase {
try opPrecedence.assertExpectedFold(
"await x + y + z", "await ((x + y) + z)")
}

func testInfixOperatorLookup() throws {
let opPrecedence = OperatorTable.standardOperators
do {
let op = try XCTUnwrap(opPrecedence.infixOperator(named: "+"))
XCTAssertEqual(op.kind, .infix)
XCTAssertEqual(op.name, "+")
XCTAssertEqual(op.precedenceGroup, "AdditionPrecedence")
}
do {
let op = try XCTUnwrap(opPrecedence.infixOperator(named: "..."))
XCTAssertEqual(op.kind, .infix)
XCTAssertEqual(op.name, "...")
XCTAssertEqual(op.precedenceGroup, "RangeFormationPrecedence")
}
XCTAssertNil(opPrecedence.infixOperator(named: "^*^"))
}
}