fsharp icon indicating copy to clipboard operation
fsharp copied to clipboard

Later errors obscure earlier errors

Open abelbraaksma opened this issue 3 years ago • 3 comments

Using typof<SomeType> can lead to confusing error messages when used as an argument for an attribute.

Repro steps

Try this code:

[<AttributeUsage(AttributeTargets.All)>]
type FooAttribute(t:System.Type) =
    inherit System.Attribute()

[<Foo(typeof<OutOfScopeType>)>]
type Vehicle() = class end

Expected behavior

Should give the same error as normal use of typeof, i.e. that the type is not defined. The expected error is: "FS0039 The type 'OutOfScopeType' is not defined."

In other words, I'd expect it similar to this:

image

Actual behavior

A different error is shown and the whole expression is underlined.

FS0267 This is not a valid constant expression or custom attribute value

image

I should note that if you hover over the type-part, both errors are shown.

Known workarounds

N/A

Related information

This reported has lead to confusion with users. For instance, see this post, where a programmer thought that typeof as a whole was not allowed (and I know I fell for this trap in the past as well): https://stackoverflow.com/questions/18369922/f-attributes-typeof-and-this-is-not-a-constant-expression.

abelbraaksma avatar Aug 15 '22 23:08 abelbraaksma

I see the right thing:

image

dsyme avatar Sep 21 '22 15:09 dsyme

Note it does depend on where you hover

dsyme avatar Sep 21 '22 15:09 dsyme

This is a classic case where error recovery and subsequent errors make later errors more obscure.

@vzarytovskii We should probably implement a general rule: always suppresses later errors if they overlap with the range of an earlier error

dsyme avatar Sep 21 '22 15:09 dsyme

always suppresses later errors if they overlap with the range of an earlier error

Sounds like a plan. Assuming the earlier error will usually be the more relevant one. Also, the later error (at least here) is incorrect, as the expression isn't invalid per se.

Thinking about this 2 seconds longer makes me think this would be a general improvement while editing code.

abelbraaksma avatar Sep 27 '22 11:09 abelbraaksma