Skip to content

Add "never" type for return statement type-checking #21

@kodek16

Description

@kodek16

Consider how the following function would currently behave with the type checker:

fun is_positive(x: int): bool {
  if (x > 0) {
    return true;
  } else {
    return false;
  }
}

While overly verbose, this looks like a perfectly legit function that should not cause any compiler errors. Alas, the way type checker currently works, it sees the whole if as the final expression in the function body. This expression has type void, while the function return type is bool. A type mismatch is reported and the code does not compile.

There are various ways of expressing to the compiler why exactly this reasoning is flawed, but one of the cleanest ones is the "never" type. Let us call it ! for now.

With just a few rules concerning ! type, we can make the previous example work:

  • A block that contains a return statement has type !.
  • A block that contains an eval instruction with expression of type ! has type !.
  • Function body is allowed to have ! type whatever its return type is.

The last rule is actually just one specific case of a more general rule that says that ! can be substituted for any other type T, but this rule is a bit more tricky to implement in the current compiler. For now just this particular case should be enough to solve most of the syntactic troubles with return statements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions