Skip to content

Duplication of code in recursive types #639

@patricoferris

Description

@patricoferris

I think I have convinced myself that this is expected behaviour, but perhaps we can add a warning in some documentation about how to properly annotate recursive types.

Given the following .ml file that uses our examples/simple-deriver, a user might quite reasonably apply a [@@deriving accessors] to each part of the recursive type (note is only recursive by the use of and not the types themselves).

type x = {
  age : int
}[@@deriving accessors]

and y = {
  name : string
}[@@deriving accessors]

This generates the following code:

type x = {
  age: int }[@@deriving accessors]
and y = {
  name: string }[@@deriving accessors]
include
  struct
    let _ = fun (_ : x) -> ()
    let _ = fun (_ : y) -> ()
    let age x = x.age
    let _ = age
    let name x = x.name
    let _ = name
    let age x = x.age
    let _ = age
    let name x = x.name
    let _ = name
  end[@@ocaml.doc "@inline"][@@merlin.hide ]

Of course, if one were to only add an annotation on one part of the recursive type then you would only get a single instance of the accessors. However, this is definitely happening in the wild, for example: https://git.frama-c.com/pub/frama-c/-/blob/master/src/kernel_services/ast_data/property.ml?ref_type=heads#L107 and (where this issue originally came from) ocaml-ppx/ppx_deriving#292. In general, I think when this does occur, recursive types tend to be rather large ASTs and so the code bloat is probably quite noticeable!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions