Skip to content

Compiler warning when obj is inferred as a type #696

@Smaug123

Description

@Smaug123

I propose we create a compiler warning, off-by-default, that warns when the typechecker infers a type to be obj without annotation.

Ideally, if there is some reason to expect that something is of type obj, then we would not warn. For example, the following code should not generate a warning, because a is constrained to be obj by the type argument to unbox, and b is constrained to be obj because it is of the same type as a.

let a = 5 |> unbox<obj>
let b = a

However, we would warn in the following case, where a is inferred to be obj because that's the most general thing it could be:

let f<'b> () : 'b =
    let a = failwith ""
    a |> unbox

The existing way of approaching this problem in F# is to ignore it and assume that you intended obj whenever obj is inferred (unless there's some other reason to think that you didn't mean it, such as unnecessary specialisation of a generic type as indicated by FS0064).

Pros and Cons

The advantages of making this adjustment to F# are that it causes us to catch a class of bug we currently can't catch. I have never encountered an instance where the compiler has inferred obj and my code was correct; using obj at all is sufficiently weird that it seems reasonable to expect it to be signposted with a type annotation somewhere (much like mutable is a required signpost for mutability). However, since this is a feature of F#, it seems reasonable to disable the warning by default.

The disadvantages of making this adjustment to F# are a slight increase in complexity during typecheck, since we need to work out whether a type has been specialised.

Extra information

Estimated cost (XS, S, M, L, XL, XXL): S

Related suggestions: none

Affidavit (please submit!)

Please tick this by placing a cross in the box:

  • This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I or my company would be willing to help implement and/or test this

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions