swiftlang / swift

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

Emit diagnostics for parsing disambiguation #60295

Open simanerush opened 2 years ago

simanerush commented 2 years ago

As a regular user of the Swift programming language, I get frustrated when I see diagnostics for the following cases dealing with cast destination types:

  1. let _ = 1 as Int16 < 7
  2. let _ = 1 as Int16 << 7

In both cases, I see error: expected type diagnostics, even though the context of the expression does not imply any presence of the type after <.

Proposed Solution: I would like to see more helpful diagnostics. For example, here is what Rust does in the same situation:

error: `<` is interpreted as a start of generic arguments for `i16`, not a shift
 --> <source>:3:16
  |
3 |     num as i16 << 7
  |                ^^ - interpreted as generic arguments
  |                |
  |                not interpreted as shift
  |
help: try shifting the cast value
  |
3 |     (num as i16) << 7
  |     +          +

Alternatives The alternative would be silencing the expected error diagnostics, and this was already attempted in my PR #60088. However, @CodaFi provided a great feedback which says,

This embeds a form of unbounded lookahead in the Swift type grammar. We should be careful committing to additional lookahead like this to disambiguate parses. This is strictly a change to the language and should probably be discussed on evolution.

I tend to agree with that, so therefore I think it's best to change the diagnostics in this case instead of proceeding with the alternative solution in my PR.

CodaFi commented 2 years ago

Diagnostic changes don't usually need to go through evolution since you're just using lookahead to pattern match the token stream but not actually changing the parse. This issue is a fine way to catalogue the feature request here. We should close out the other one in favor of this.

simanerush commented 2 years ago

Yes, thank you for clarification. I will close the other one!

AnthonyLatsis commented 2 years ago

@CodaFi Maybe we should keep the other one open so that we can close this one once we deal with the diagnostics QoI part?