fsharp / fslang-suggestions

The place to make suggestions, discuss and vote on F# language and core library features
341 stars 20 forks source link

Allow 'use ptr = fixed &mem' in computation expressions #1139

Open reijerh opened 2 years ago

reijerh commented 2 years ago

Allow 'use ptr = fixed &mem' in computation expressions

I propose we allow pinning locals in computation expressions (CEs) via use ptr = fixed &mem. This is currently not allowed and results in a confusing error: Error FS3207 : Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string'

Personally I'd like to be able to use it in the result { } CE.

A workaround is to use the let-form instead: let ptr = fixed &mem, which has a couple of problems:

  1. It's an undocumented form, the docs (and compiler error) state that fixed must always be used in the use-form.
  2. This form is not allowed outside CEs, this is confusing.
  3. It's unclear if this unpins the local when going out of scope or not, I wouldn't expect it to. (Testing suggests it does, the generated IL is the same.)
  4. It doesn't yield an IDisposable to dispose manually.

Existings way of approaching this problem in F# are:

  1. Do the pinning outside the CE (awkward an not always feasible).
  2. Manual management through e.g. Marshal.AllocHGlobal and related functions, preferably made opaque by wrapping it in an IDisposable type.

Pros and Cons

The advantages of making this adjustment to F# are:

  1. Less memory management mistakes caused by manual memory management
  2. Code is more readable
  3. Less confused F# users

The disadvantages of making this adjustment to F# are:

  1. I'm guessing there's a good technical reason why it doesn't work at the moment, quoting @dsyme from here:

    This is by design for F# 6, because of the way use is de-sugared and treated in computation expressions. Just use a let or similar with a try/finally

    I'm not clear if it could be handled differently

Extra information

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

Affidavit (please submit!)

Please tick all that apply:

For Readers

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

jwosty commented 10 months ago

This is included in FS-1081 ("Extended Fixed Expressions")

jwosty commented 10 months ago

This is now complete: https://github.com/dotnet/fsharp/pull/15697