dotnet / dotnet/fsharp

Program that should not compile, using statically resolved type parameters, gets runtime exception instead

Open
#4,924 21 comments 0 reactions 0 assignees View on GitHub
Area-Compiler-SRTP Bug Impact-Medium
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

Using statically resolved type parameters, we ran into a problem where we wrote some code that was wrong according to what the types said, and yet compiled (and so we didn't realize it was wrong). While writing unit tests against it, we got an `InvalidCastException`, which was exceedingly puzzling, because nowhere in our code did we use casting. I have boiled this down to a [minimal working example](https://github.com/Kazark/fsharp-srtp-broken).

#### Repro steps

Provide the steps required to reproduce the problem

1. Download my [minimal working example](https://github.com/Kazark/fsharp-srtp-broken).

2. Read the code and comments in `Program.fs` to get an idea of what's going on hear. `SRTP.fs` contains the backing statically resolved type parameter code etc.

2. Compile.

3. Run the resulting `.exe` and observe the output.

#### Expected behavior

Program should not typecheck.

#### Actual behavior

Depends on what you do with the values that do not match their declared types:

1. If you just ignore those values or generally print them to the screen, their declared type is ignored and they just behave the way you would expect given their real type.
2. If you try to use them in a more sophisticated way such as pattern matching on them, which is of course according to their declared type in the code, you will get an `InvalidCastException` at runtime explaining that the real type can't be cast to the supposed type.

#### Known workarounds

I can correct my code and get it to work but my only workaround for regaining confidence that code that compiles is correct is to stop using statically resolved type parameters.

#### Related information

Provide any related information

* Windows 7
* F# 4.1
* .NET >= 4.5 (so you can use statically resolved type parameters)
* Visual Studio 2017
* From my perspective, this is a severe bug, as it really destroys my confidence in the F# compiler's ability to typecheck my code.

Please let me know if more detailed information is needed. This is a high priority issue for me as it seriously compromises the integrity of my F# code.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.