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

Special termination handling for while true loops? #312

Open
kengorab opened this issue May 7, 2021 · 0 comments
Open

Special termination handling for while true loops? #312

kengorab opened this issue May 7, 2021 · 0 comments
Labels
enhancement New feature or request

Comments

@kengorab
Copy link
Owner

kengorab commented May 7, 2021

Let's say we have this function

func foo(): String {
  while true {
    if 1 < 3 {
      continue
    } else {
      return "asdf"
    }
  }
}

We know intuitively as programmers that this code will always result in a String (from a typechecking perspective, not a runtime perspective). But it's difficult to detect this while typechecking; this will produce an error like

Invalid return type
  |    while true {
       ^^^^^
Function 'foo' has return type String, but this is of type Unit

We can get around this by adding a "return" value at the end of the function (after the loop), but it seems silly since we know this is unreachable (since all branches within the infinite loop either continue or return). This however, falls apart if we aren't guaranteed to have an infinite loop:

func foo(): String {
  var done = false
  while !done {
    if 1 < 3 {
      continue
    } else if 1 == 1 {
      done = true
    } else {
      return "asdf"
    }
  }
  "foo" // <- control flow _might_ reach here now
}

This proposal is to consider having a special case to handle this - if we're in a while loop and the condition is the literal true, then we can say with 100% certainty that the loop will terminate if all branches either continue or return (again, "terminate" from a purely typechecking perspective). This seems like such an edge case, and is probably very uncommon, but it's one of those things that just makes the compiler feel a lot smarter.

@kengorab kengorab added the enhancement New feature or request label May 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant