Skip to content
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

Using @rethrows protocols in rethrows functions allow the throws function to be called without try #73503

Open
tplaymeow opened this issue May 8, 2024 · 0 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels

Comments

@tplaymeow
Copy link

tplaymeow commented May 8, 2024

Description

No response

Reproduction

This code compiles correctly, but crushes at runtime

struct ZeroDivisionError: Error {}

@rethrows protocol Expression {
  func evaluate() throws -> Int
}

struct Number: Expression {
  let value: Int
  func evaluate() -> Int {
    self.value
  }
}

struct Negative<E: Expression>: Expression {
  let expression: E
  func evaluate() rethrows -> Int {
    try self.expression.evaluate() * -1
  }
}

struct Division<E1: Expression, E2: Expression>: Expression {
  let expression1: E1
  let expression2: E2
  func evaluate() throws -> Int {
    let value2 = try self.expression2.evaluate()
    guard value2 != 0 else { throw ZeroDivisionError() }
    return try self.expression1.evaluate() / value2
  }
}

func foo1(_ exp1: some Expression, _ exp2: some Expression) rethrows -> Int {
  try Negative(
    expression: Division(
      expression1: exp1,
      expression2: exp2
    ))
  .evaluate()
}

func foo2(_ exp: some Expression) rethrows {
  try { throw ZeroDivisionError() }()
}

// Runtime crash
foo1(Number(value: 4), Number(value: 0))

// Runtime crash
foo2(Number(value: 0))

Expected behavior

The compiler should emit an error. foo1 and foo2 must be called with try.

Environment

Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Additional information

Similar issues with throws closures:

@tplaymeow tplaymeow added bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels labels May 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels
Projects
None yet
Development

No branches or pull requests

1 participant