Fable icon indicating copy to clipboard operation
Fable copied to clipboard

nullary union case physical equality behaves differently between fable and fsc

Open joprice opened this issue 1 year ago • 0 comments

Description

When comparing two references to a nullary union case for physical equality, they are considered identical in fsc, but distinct in fable. Checking the generated code, this seems to be due to the fact that they are represented as classes, and each reference generates a distinct call to the constructor, instead of reusing a single instance.

type X = A | B | C

// true for fsc, false for fable
LanguagePrimitives.PhysicalEquality X.A X.A

Attempting to work around this by using either Erase or StringEnum introduces issues with reflection, since the type is erased to String, making reflection techniques keyed on type conflate these types with plain Strings, as discussed in this Thoth.Json issue https://github.com/thoth-org/Thoth.Json/issues/203. Using TypeScriptTaggedUnion has the same issue of generating distinct objects per call site

{
    type: "a",
} === {
    type: "a",
};

One workaround that does work is to write a let for each case, effectively instantiating a singleton for each instance of the DU:

type X = A | B | C

module X = 
  let A = A
  let B = B
  let C = C

But you need to make sure everything that could work with the constructors such as Thoth decoders references these singletons:

let decoder: Thoth.Json.Decoder<State> =
        let decoder = Decode.Auto.generateDecoder<State> ()

        decoder
        |> Decode.map (function
            | On -> On
            | Off -> Off)

Could the compiler generate these singleton values and reference them instead?

Repro code

https://fable.io/repl/#?code=FDAuE8AcFMAIA1YF5YEFYB9YCFOwMIgC2A9gCYCuANnIisLLDaGsmiM7NAI4CMb8AHToUQ1ME48ATGwAyAQwB2Acwrzl0AAoAnAJZFdoXQDdoAZ0GaAFuDO6AxvKoBRbmqqHwCYd-GTuAMxySqrqWnoGRqYW1rYOTq7unt64QtjAkHqKoABmirAARACkAEawpeUlBVx8NTI8AUA&html=Q&css=Q

Expected and actual results

Please provide the expected and actual results.

Related information

  • Fable version: 4.18.0
  • Operating system: OSX

joprice avatar Jul 13 '24 16:07 joprice