fsharp icon indicating copy to clipboard operation
fsharp copied to clipboard

[<return: X>] not respected on class members

Open DragonSA opened this issue 2 months ago • 2 comments

The [<return: X>] approach to attaching an attribute to the return property of a method/function does not work on class (static) methods.

open System.Reflection
open Microsoft.FSharp.Quotations.Patterns

type SomeAttribute() =
    inherit System.Attribute()

module Module =
    let rec ``type`` =
        match <@ ``type`` @> with
        | PropertyGet (_, propertyInfo, _) -> propertyInfo.DeclaringType

    [<return: Some>]
    let func a = a + 1

type Class() =
    [<return: Some>]
    static member ``static member`` a = a + 1

    [<return: Some>]
    member _.``member`` a = a + 1

let printReturnAttr (typ: System.Type) name =
    typ.GetMethod(name).ReturnParameter.GetCustomAttribute<SomeAttribute>()
    |> printfn "%s: %O" name

printReturnAttr (Module.``type``) (nameof Module.func)
printReturnAttr typeof<Class> ("member")
printReturnAttr typeof<Class> (nameof Class.``static member``)

Actual output:

func: Program+SomeAttribute
member: <null>
static member: <null>

Looking at the IL, the "return" bit is being dropped. missingattr.txt

dotnet 9.0.305 and 10.0.100-rc.2.25502.107 on macOS 15.7.1 (24G231)

Sponsored by CP Dynamics

DragonSA avatar Oct 21 '25 14:10 DragonSA

Also, putting the [<return: X>] attribute on the signature file AND the implementation file causes a compiler warning, about a change in the signature. Removing either removed the compiler warning, but this issue persists. Is that expected behaviour?

DragonSA avatar Oct 21 '25 14:10 DragonSA

Also, putting the [<return: X>] attribute on the signature file AND the implementation file causes a compiler warning, about a change in the signature. Removing either removed the compiler warning, but this issue persists. Is that expected behaviour?

A warning is intentional if the attributes or their arguments are different. Otherwise it is OK.

Also, the attributes are copied over, so it is correct to have attributes declared just at one of sig/impl.

T-Gro avatar Nov 10 '25 12:11 T-Gro