rescript-lang / rescript-compiler

The compiler for ReScript.
https://rescript-lang.org
Other
6.68k stars 445 forks source link

[@@bs.deriving accessors] in submodule generates useless variant accessors #3454

Closed donut closed 5 years ago

donut commented 5 years ago

If a variant is defined in a submodule with [@@bs.deriving accessors], it generates useless accessors.

For example:

type minion  =
  Boo
  | Koopa of string
  | Goomba
  [@@bs.deriving accessors]

generates this JS:

function koopa(param_0) {
  return /* Koopa */[param_0];
}

var boo = /* Boo */0;

var goomba = /* Goomba */1;

exports.boo = boo;
exports.koopa = koopa;
exports.goomba = goomba;

But when that same variant is put in a submodule like so:

module Minion = struct
  type t =
      Boo
    | Koopa of string
    | Goomba
    [@@bs.deriving accessors]
 end

it generates this JS, missing the Boo and Goomba accessors and exporting nothing useful:

function koopa(param_0) {
  return /* Koopa */[param_0];
}

var Minion = /* module */[
  /* boo : Boo */0,
  /* koopa */koopa,
  /* goomba : Goomba */1
];

exports.Minion = Minion;

This breaks interop with JavaScript since Minion is exported as an array and the only accessor that's generated (Koopa()), is not exported. On top of that, only accessors for variants with payloads are generated.

The output I'd expect is something like this:

var Minion = {
  boo: 0,
  koopa: function(param_0) { return [param_0]),
  Goomba: 1
};

exports.Minion = Minion;
bobzhang commented 5 years ago

Hi, this works as expected. The missing part is that we don't have a good story in the interop between bucklescript and javascript on submodule representation, we will revisit it in the future (it is not relevant to the code gen).