Skip to content
This repository has been archived by the owner on Nov 13, 2023. It is now read-only.

Add support to export refs. #237

Closed
cristianoc opened this issue Aug 22, 2019 · 2 comments · Fixed by #238
Closed

Add support to export refs. #237

cristianoc opened this issue Aug 22, 2019 · 2 comments · Fixed by #238

Comments

@cristianoc
Copy link
Collaborator

The translation should do the equivalent of this:

type ref('a) = {mutable contents: 'a};

[@genType]
let foo = r => r.contents + 1;

gives

export type myref<a> = {| contents: a |};

export const foo: (myref<number>) => number = function (Arg1: $any) {
  const result = ABS.foo([Arg1.contents]);
  return result
};
@cristianoc
Copy link
Collaborator Author

In fact, any translation would destroy the identity of the reference.
Giving reference a 1-tuple type will prevent conversions in the case the argument type does not require conversion.
If the argument type requires conversion, the only safe way is to export the reference as an abstract type, and provide functions to access that type from JS.

@cristianoc
Copy link
Collaborator Author

#238 contains examples on how to export a reference as an abstract type, in case the argument type of the reference requires conversion:

// Abstract version of references: works when conversion is required.

module R: {
  [@genType]
  type t('a);
  let get: t('a) => 'a;
  let make: 'a => t('a);
  let set: (t('a), 'a) => unit;
} = {
  type t('a) = ref('a);
  let get = r => r.contents;
  let make = ref;
  let set = (r, v) => r.contents = v;
};

[@genType]
type t('a) = R.t('a);

[@genType]
let get = R.get;

[@gentype]
let make = R.make;

[@genType]
let set = R.set;

type requiresConversion = {x: int};

// Careful: conversion makes a copy and destroys the reference identity.
[@genType]
let destroysRefIdentity = (x: ref(requiresConversion)) => x;

// Using abstract references preserves the identity.
[@genType]
let preserveRefIdentity = (x: R.t(requiresConversion)) => x;

cristianoc added a commit that referenced this issue Aug 22, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant