Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support inref in computation expression operations #1360

Open
5 of 6 tasks
xperiandri opened this issue May 17, 2024 · 16 comments
Open
5 of 6 tasks

Support inref in computation expression operations #1360

xperiandri opened this issue May 17, 2024 · 16 comments

Comments

@xperiandri
Copy link

I propose we support accepting inref<'T> as the first parameter of computation expression operation

[<Struct>]
type CreateOperation<'a> = {
    Item : 'a
    PartitionKey : PartitionKey voption
    RequestOptions : ItemRequestOptions
}

type CreateBuilder<'a> (enableContentResponseOnWrite : bool) =
    member _.Yield _ =
        {
            Item = Unchecked.defaultof<_>
            PartitionKey = ValueNone
            RequestOptions = ItemRequestOptions (EnableContentResponseOnWrite = enableContentResponseOnWrite)
        }
        : CreateOperation<'a>

    /// Sets the item being created
    [<CustomOperation "item">]
    member _.Item (state : inref<CreateOperation<_>>, item) = { state with Item = item }

    /// Sets the partition key
    [<CustomOperation "partitionKey">]
    member _.PartitionKey (state : inref<CreateOperation<_>>, partitionKey : PartitionKey) = {
        state with
            PartitionKey = ValueSome partitionKey
    }

    /// Sets the partition key
    [<CustomOperation "partitionKey">]
    member _.PartitionKey (state : inref<CreateOperation<_>>, partitionKey : string) = {
        state with
            PartitionKey = ValueSome (PartitionKey partitionKey)
    }

    /// Sets the request options
    [<CustomOperation "requestOptions">]
    member _.RequestOptions (state : inref<CreateOperation<_>>, options : ItemRequestOptions) = {
        state with
            RequestOptions = options
    }

The existing way of approaching this problem in F# is not using inrefs and causing structs to be copied

Pros and Cons

The advantages of making this adjustment to F# are performant object builders using computation expressions and value type state

The disadvantages of making this adjustment to F# do not exist

Extra information

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

Related suggestions: No

Affidavit

Please tick these items 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
  • This is a language change and not purely a tooling change (e.g. compiler bug, editor support, warning/error messages, new warning, non-breaking optimisation) belonging to the compiler and tooling repository
  • 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
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate

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

For Readers

If you would like to see this issue implemented, please click the 👍 emoji on this issue. These counts are used to generally order the suggestions by engagement.

@abelbraaksma
Copy link
Member

abelbraaksma commented May 19, 2024

Hey @xperiandri 👋! This looks interesting, but can you please update the example code such that it doesn't have unresolved types? I.e., PartitionKey and ItemRequestOptions are not defined. Please consider using a "small reproducible example".

And can you explain what is currently not working for you? If I copy your code and fix the missing types, it just compiles. Can you update the original post such that it shows what part with inref you are looking for?

Some related suggestions (but not the same):

@vzarytovskii
Copy link

vzarytovskii commented May 21, 2024

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

😆 no, definitely not an XS task. XS tasks are to fix some invalid xmldocs, or add one function to, let's say, List module. This one is definitely not XS.

@vzarytovskii
Copy link

vzarytovskii commented May 21, 2024

And can you explain what is currently not working for you?

There are currently no conversion between 'a and inref<'a>, so you can't do something like the following

let foo (a: inref<string>) =
    a = "foo"
    
foo "bar"

So, the issues is not really about CEs, but rather about supporting implicit conversion from 'a to byref<a, ByRefKind.In>. We already do for refs:

let foo (a: inref<string>) =
    a = "foo"

let mutable f = "bar"
foo &f

Not sure we want to do it for arbitrary expressions. It's up to @dsyme.

@xperiandri
Copy link
Author

In my mind, it is only about CEs. I have no opinion about the need for implicit conversion in other places.
I'm about efficient object builders using computation expressions.

@dsyme
Copy link
Collaborator

dsyme commented May 21, 2024

It's an interesting suggestion to allow this in a limited place (or perhaps in arguments with an opt-in attribute).

IIRC it's not hard to implement this - it was more a policy decision about code correctness and understanding semantics.

I think I'd be ok with an opt-in F#-specific attribute on the parameter as a general mechanism for call-by-address-to-inref. WDYT?

@xperiandri
Copy link
Author

I like that idea

@vzarytovskii
Copy link

I'm about efficient object builders using computation expressions.

Passing it by ref won't always mean "more efficient". Passing by value oftentimes is more efficient, since JIT knows that structure is 100% on the stack and can optimize a bunch of stuff. On the other hand if you have a ref parameter, JIT doesn't really know where it's pointing - can be heap (class field), and in this case it will need write barriers.

@vzarytovskii
Copy link

I think I'd be ok with an opt-in F#-specific attribute on the parameter as a general mechanism for call-by-address-to-inref. WDYT?

This, or warning, should be okay.

@xperiandri
Copy link
Author

xperiandri commented May 21, 2024

Hm, I thought inref is only for read-only structs and pins them to heap

@vzarytovskii
Copy link

Hm, I thought inref is only for read-only structs and pins them to heap

JIT doesn't differentiate between types of byref, so it can do defensive write barriers

@xperiandri
Copy link
Author

Is it possible to declare a read-only struct in F#?

@abelbraaksma
Copy link
Member

abelbraaksma commented May 21, 2024

Is it possible to declare a read-only struct in F#?

Yes @xperiandri: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/structs#readonly-structs

Hm, I thought inref is only for read-only structs and pins them to heap

See: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/byrefs#inref-semantics
Notably: "There is no implication that SomeStruct is immutable by virtue of x being an inref."

For pinning, you can use fixed, iirc.

@xperiandri
Copy link
Author

What is fixed?

@vzarytovskii
Copy link

What is fixed?

It's way of pinning local onto stack.

@voronoipotato
Copy link

@xperiandri in case sharplab is ever down, copy pasted here

open System

type PartitionKey (value : string) = struct end
type ItemRequestOptions () =
    member val EnableContentResponseOnWrite = true with get, set

[<Struct>]
type CreateOperation<'a> = {
    Item : 'a
    PartitionKey : PartitionKey voption
    RequestOptions : ItemRequestOptions
}

type CreateBuilder<'a> (enableContentResponseOnWrite : bool) =
    member _.Yield _ =
        {
            Item = Unchecked.defaultof<_>
            PartitionKey = ValueNone
            RequestOptions = ItemRequestOptions (EnableContentResponseOnWrite = enableContentResponseOnWrite)
        }
        : CreateOperation<'a>

    /// Sets the item being created
    [<CustomOperation "item">]
    member _.Item (state : inref<CreateOperation<_>>, item) = { state with Item = item }

    /// Sets the partition key
    [<CustomOperation "partitionKey">]
    member _.PartitionKey (state : inref<CreateOperation<_>>, partitionKey : PartitionKey) = {
        state with
            PartitionKey = ValueSome partitionKey
    }

    /// Sets the partition key
    [<CustomOperation "partitionKey">]
    member _.PartitionKey (state : inref<CreateOperation<_>>, partitionKey : string) = {
        state with
            PartitionKey = ValueSome (PartitionKey partitionKey)
    }

    /// Sets the request options
    [<CustomOperation "requestOptions">]
    member _.RequestOptions (state : inref<CreateOperation<_>>, options : ItemRequestOptions) = {
        state with
            RequestOptions = options
    }
    
let create<'a> = CreateBuilder<'a>(false)

let operation = create {
    item "item"
    partitionKey "partitionKey"
}

()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants