swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.51k stars 10.35k forks source link

[SR-2033] Better Error Messages When Not Inferring Closure Types #44642

Open swift-ci opened 8 years ago

swift-ci commented 8 years ago
Previous ID SR-2033
Radar None
Original Reporter rosslebeau (JIRA User)
Type Improvement
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 2 | |Component/s | | |Labels | Improvement, TypeChecker | |Assignee | None | |Priority | Medium | md5: c2c0a8cc9c599b2c75ab2204b5edcdcd

Issue Description:

Since the type checker does not infer types for closures with more than 1 statement (a purposeful feature of the type checker, in order to keep performance up), the following code compiles:

let a = [[1,2],[3],[4,5,6]]
var b: [Int]
b = a.flatMap { elem in
  return elem
}

While this code gives the error: "cannot convert return expression of type '[Int]' to return type 'Int?'":

b = a.flatMap { elem in
  print(elem)
  return elem
}

As the type checker seems to pick an implementation of flatMap and check against that, it tells us to use a different flatMap than we intended, even though our code is actually valid.

I think that for users who aren't aware of this type checker limitation, this error message will be very confusing. Additionally, it could occur with many different functions, and you could also get the same message in a case where you actually aren't providing valid types.

I propose that, in the case where the type checker does not infer the type of a multi-statement closure, yet finds an error with the types, it adds a more helpful message so the user is aware that their code might be valid, and they should explicitly declare the types in their closure. Something like "Did not infer types in multi-statement closure, try explicitly declaring them if you are expecting a different implementation".

swift-ci commented 8 years ago

Comment by Bernd Ohr (JIRA)

Just curious and tried this:

let b = a.flatMap { elem in
    defer { print(elem) }
    return elem
}

Wouldn't it be nice if the type checker could handle this special case of a single-statement-closure?