Minor source break with `if let` and `guard let` bindings

Just a heads up about something you might notice in upcoming developer snapshots.

In Swift, if let and guard let bindings are intended to be used only with optional values. On the other hand, Swift also supports an implicit conversion of any type to an optional. These two together mean that in the case where you convert a value to an optional and immediately unwrap it, we need to emit a diagnostic, since that's probably not what you meant to do--the else branch is dead:

func f() {
  if let x = 0 {  // error: initializer for conditional binding must have Optional type, not 'Int'
  } else {
    ... complicated stuff ...
  }
}

However, we would sometimes not diagnose this error if the value of the binding was a ternary expression, because the type checker might insert the optional injection conversions inside the branches of the ternary instead of converting the result:

func f(b: Bool) {
  if let x = b ? 0 : 0 {  // no error
  }
}

While working on some optimizations, I noticed that my changes had the effect of making some examples that were formerly diagnosed no longer diagnose, and vice versa. I fixed this by tightening up the check, which makes the second example above into an error.

We found only four instances of this pattern in Apple's codebase, and all seemed accidental, or perhaps historical because a value used to be optional at one point and no longer was. In each case, there was an obvious fix to just move a binding out of the if or guard; in two cases, the entire else branch became dead as a result.

If this change turns out to have more significant fallout, I'd be happy to downgrade it to a warning in this case where you have a ternary there, but this would mean that some expressions that were errors before would now be diagnosed as warnings. Let me know if you run into any difficulties as a result of this.

17 Likes

Given the number of dependencies that probably consider themselves "finished", I'd argue that new diagnostics on code that has a meaning indeed ought to be warnings, even if it's silly code. If it were just that I might have hesitated to post at all—it's not my problem until I find out one of my dependencies is actually doing that—but I'd actually argue that this should have always been just a warning. If someone is experimenting in a playground, or changing the signature of a function used elsewhere, having this be "just a warning" lets them see how the program will behave if they take the compiler recommendation of removing the else-branch without having to stop in the middle of their change. Of course that won't be true for all kinds of changes, but for this particular kind of bad code it seems only a little worse than an out-of-range comparison, which is also only a warning.

11 Likes

And now that we have targeted controls for upgrading specific warnings to errors, I feel more comfortable about taking a softer stance on code that we would otherwise think "you should never write this because it's silly at best and hiding a bug at worst". We can let teams who want to apply stricter controls to their own codebase do so without breaking dependencies that they don't control.

4 Likes

I agree with Jordan's point that this is conceptually no worse than an unused variable, or something like

if true {
  ...
} else {
  ...
}

It may or may not indicate a logic error in the code, but there's no soundness hole or anything like that. So I think downgrading it to a warning unconditionally (with slight change in phrasing) would be another reasonable choice.

In order of personal preference, from best to worst, here is how I'd rank the solutions:

  1. Leave slightly stricter behavior as-is (just because it's less work :) )
  2. Unconditional warning in its own diagnostic group
  3. Special-case carveout for ternary expressions (and any other cases we find later)

The thing I dislike about 3. is that we tend to accumulate a lot of these "downgrade to warning" checks, and while they're beneficial in the short term in that they minimize observable behavior changes, they clutter the language over the long run, and seeing certain behaviors produce warnings while almost identical code outputs errors is potentially a source of confusion for users.

While the complexity of doing 3. is low in this case and I'm not going to die on this hill, I think as a matter of principle we should prefer approaches 1. or 2. whenever an issue like this comes up.

8 Likes

Here is a draft PR to downgrade this to a warning: Sema: Downgrade non-optional conditional binding to a warning by slavapestov · Pull Request #93334 · swiftlang/swift · GitHub.

The warning lives in its own diagnostic group named ConditionalBindingNonOptionalType. I still need to write a documentation file for it.

7 Likes

The LSG discussed this and is supportive of option 2. This particular code pattern of if let and guard let used with a non-optional value is unnecessary but it isn't harmful, and if we add a diagnostic group, people still have the option to promote the warning to an error.

3 Likes

Sounds good, the PR to make the check more accurate and downgrade it to a warning is now merged.

4 Likes