Skip to content

Run base constructor then blocks on the derived instance #5272

Open

Description

@MangelMaxime

On JS, TS and Python, Fable can't inherit from a class whose explicit constructor has a self identifier, and a class with a base class can't have one. Once #5235 merges, both are compile errors, as they are on main. .NET prints true and 2.

let saved = ResizeArray<obj>()

type Base =
    val Name: string
    new (name: string) as self = { Name = name } then saved.Add(box self)

type Derived =
    inherit Base
    val X: int
    new () = { inherit Base("d"); X = 1 }

type Counter =
    val mutable Count: int
    new (c: int) as self = { Count = c } then self.Bump()
    member this.Bump() = this.Count <- this.Count + 1

type CounterChild =
    inherit Counter
    val X: int
    new () = { inherit Counter(1); X = 1 }

let d = Derived()
printfn "%b" (obj.ReferenceEquals(saved.[0], d))
printfn "%d" (CounterChild()).Count

On the #5235 branch, both derived classes fail with:

error FABLE: Program.Base has a constructor with a self identifier (`new() as x`), which Fable does not support inheriting from.

Both programs are valid F#. Supporting them means running the base then block on the derived instance. One idea, untested, is to split explicit constructors into separate allocate and initialize steps.

An earlier version of #5235 built a separate base object and copied its fields into the derived one. That was dropped because it gave wrong output for: curried function fields in the derived class, a base behind a .fsi, an [<AttachMembers>] base, and leaking self. It's in the branch history at 2a69b6a, and the tests from that version list the shapes a real fix has to handle.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions