Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile a polymorphic variant to a desired string cleanly #655

Open
jbhoot opened this issue Jul 9, 2023 · 1 comment
Open

Compile a polymorphic variant to a desired string cleanly #655

jbhoot opened this issue Jul 9, 2023 · 1 comment

Comments

@jbhoot
Copy link

jbhoot commented Jul 9, 2023

In order to compile a polymorphic variant to a desired string value in JavaScript, the following approach is required:

type x =
  [ `Document_fonts [@bs.as "document-fonts"]
  | `Browser_fonts [@bs.as "browser-fonts"]
  ]
[@@bs.deriving jsConverter]

let a : x = `Document_fonts
let b = xToJs `Document_fonts

The assignments are compiled to

var a = "Document_fonts";
var b = xToJs("Document_fonts");

out of which, b is correctly assigned the value "document-fonts".

However, [@@bs.deriving jsConverter] generates converter functions, which are also compiled and added to the JavaScript code. So the full compiled code is quite a bit:

var _map = {"Document_fonts":"document-fonts","Browser_fonts":"browser-fonts"};

var _revMap = {"document-fonts":"Document_fonts","browser-fonts":"Browser_fonts"};

function xToJs(param) {
  return _map[param];
}

function xFromJs(param) {
  return _revMap[param];
}

var b = xToJs("Document_fonts");

var a = "Document_fonts";

export {
  xToJs ,
  xFromJs ,
  a ,
  b ,
}

Things could be a lot cleaner:

  1. The requirement of [@@bs.deriving jsConverter] attribute could be dropped, i.e., the definition of the polymorphic variant type, coupled with the [@bs.as "x"] attribute(s) should provide the intent adequately.
  2. Ideally, i.e., from my understanding, the converter functions should not be needed and could be dropped too.
  3. An assignment like
let a : x = `Document_fonts

for the above definition would ideally compile directly to

var a = "document-fonts";
@anmonteiro
Copy link
Member

anmonteiro commented Jul 21, 2023

This isn't actually possible because we'd need to support defining polymorphic variants that break the OCaml syntax. i.e. it's not possible to write type x = [`foo-bar]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants