1 of 11

Symbols as WeakMap keys

For Stage 2

Daniel Ehrenberg

Igalia in partnership with Bloomberg

July 2020 TC39 meeting

2 of 11

Why?

  • I'm championing this in order to:�enable references from Records and Tuples to Objects via WeakMaps
  • Some TC39 delegates reported other use cases

3 of 11

Details

  • Any Symbol may be used as
    • A WeakMap key
    • A WeakSet entry
    • The target of a WeakRef
    • Registered in a FinalizationRegistry

4 of 11

Spec text

5 of 11

Why not add a Box type?

Boxmaker, Boxmaker....

6 of 11

Intuition: Box objects in a primitive

const obj = { hello: "world" };

const box = Box(obj);

assert(typeof box === "box", "boxes are a new primitive type");

assert(obj !== box, "boxes are not their boxed object");

assert(obj.hello === box.deref().hello, "boxes can deref props");

assert(obj === box.deref(), "boxes can deref the full object");

const server = #{

port: 8080,

handler: Box(function handler(req) { /* ... */ }),

};

server.handler.deref()({ /* ... */ });

7 of 11

Box semantics in more detail

  • Each Box has an associated [[Id]]
  • Each Realm has an associated weak mapping [[Id]] -> Boxed object�
  • Box(obj)
    • Create a new [[Id]], and write [[Id]] -> obj into the Realm's mapping
    • Return a Box value with an associated [[Id]]
  • Box.prototype.deref
    • If this Realm's mapping contains an entry for this.[[Id]]
      • Return the associated object
    • Else, return undefined

8 of 11

Sharing and isolating with Boxes

  • Box.prototype.deref is the only way to get at that Realm's mapping
  • Two different Realms cannot see into each other's Boxes
    • Unless one Realm gives the other Realm its Box.prototype.deref
  • A Realm can pull off its deref, delete it, etc, to control access to the mapping

9 of 11

Problem: isolating within a Realm

  • If using membrane-based isolation within a Realm,�Box() + Box.prototype.deref bypasses the membrane
  • Only option to preserve membrane is to disable the feature (early)

delete Box.prototype.deref

  • Some committee members want all TC39 features to be available within a single frozen Realm, membrane-isolated world
    • ⇒ no Box

10 of 11

Symbols as WeakMap keys omits Realm-wide mapping.�Manage your own mapping!

11 of 11

Stage 2?