Skip to content

Improve Error Reporting: "could not be generalized because it would escape its scope" #3302

@isaacabraham

Description

@isaacabraham

What

This error crops up when creating SRTP members but forgetting to inline them (example here taken from this SO question): -

type MyType<'T when ^T: (static member ( + ) : ^T * ^T -> ^T)> =
    member this.F a b = a + b

leads to

error FS0670: This code is not sufficiently generic. The type variable ^T when ^T : (static member ( + ) : ^T * ^T -> ^T) could not be generalized because it would escape its scope.

Why

It seems that the error could not be generalized because it would escape its scope normally can be solved by inlining the member definition. There are a few posts / questions out there on SO etc. regarding this, all with that answer.

I know that SRTP is a somewhat advanced F# topic but nonetheless the error could be improved since there's often the same fix that can be applied. Also, the current error message could explain itself a little better - what does "it would escape its scope" mean in this context? Why would inlining fix it? etc.

How

I'm not entirely sure, but perhaps a start would be to at least offer the solution: -

error FS0670: This code is not sufficiently generic. The type variable ^T when ^T : (static member ( + ) : ^T * ^T -> ^T) could not be generalized because it would escape its scope. Consider inlining the member to fix this error e.g. "member inline this.F" ....

However, this still doesn't clearly explain the "why"; someone seeing this for the first (or second!) time won't know why the error is occuring, but rather than a tried-and-tested solution that makes the error go away. Other ideas include: -

  • Showing an alternate way to define the member which (apparently?) gets the constraint for free:-
type MyType() =
    member inline this.F a b = a + b
  • Another answer that I rather like from the SO post above contains a much more : -
    "Member constrains need statically resolved type parameters. But statically resolved type parameters are not allowed on types, only for inline functions and inline methods.". This at least tries to address the why the error occurs, although it could still be improved upon IMHO.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Compiler-SRTPbugs in SRTP inference, resolution, witness passing, code genFeature ImprovementTheme-Simple-F#A cross-community initiative called "Simple F#", keeping people in the sweet spot of the language.

    Type

    No type

    Projects

    Status

    In Progress

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions