summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/js/builtins/weakrefs/resources/maybe-garbage-collect.js
blob: 8bd4cac309d39f9a2a173b8035156f71f3a2859b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * maybeGarbageCollectAsync
 *
 * It might garbage collect, it might not. If it doesn't, that's ok.
 */
self.maybeGarbageCollectAsync = garbageCollect;

/**
 * maybeGarbageCollectKeptObjectsAsync
 *
 * Based on "asyncGCDeref" in https://github.com/tc39/test262/blob/master/harness/async-gc.js
 *
 * @return {Promise} Resolves to a trigger if ClearKeptObjects
 *                   exists to provide one
 */
async function maybeGarbageCollectKeptObjectsAsync() {
  let trigger;

  if (typeof ClearKeptObjects === 'function') {
    trigger = ClearKeptObjects();
  }

  await maybeGarbageCollectAsync();

  return trigger;
}

/**
 * maybeGarbageCollectAndCleanupAsync
 *
 * Based on "asyncGC" in https://github.com/tc39/test262/blob/master/harness/async-gc.js
 *
 * @return {undefined}
 */
async function maybeGarbageCollectAndCleanupAsync(...targets) {
  let finalizationRegistry = new FinalizationRegistry(() => {});
  let length = targets.length;

  for (let target of targets) {
    finalizationRegistry.register(target, 'target');
    target = null;
  }

  targets = null;

  await 'tick';
  await maybeGarbageCollectKeptObjectsAsync();

  let names = [];

  finalizationRegistry.cleanupSome(name => names.push(name));

  if (names.length !== length) {
    throw maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED;
  }
}

maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED = Symbol('Object was not collected');

/**
 * resolveGarbageCollection
 *
 * Based on "resolveAsyncGC" in https://github.com/tc39/test262/blob/master/harness/async-gc.js
 *
 * @param  {Error} error An error object.
 * @return {undefined}
 */
function resolveGarbageCollection(error) {
  if (error && error !== maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED) {
    throw error;
  }
}