summaryrefslogtreecommitdiff
path: root/rts/js/stableptr.js
blob: 82fc2d336c8ba52fc761cb6a05646d27204431f2 (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
73
74
75
//#OPTIONS: CPP

/*
  Stable pointers are all allocated in the h$StablePtrData buffer and
  can therefore be distinguished by offset

  StablePtr# is treated as Word32# when it comes to writing and reading them
 */

 #ifdef GHCJS_TRACE_STABLEPTR
 function h$logStablePtr(args) { h$log.apply(h$log,arguments); }
 #define TRACE_STABLEPTR(args...) h$logStablePtr(args)
 #else
 #define TRACE_STABLEPTR(args...)
 #endif

var h$stablePtrData = [null];
var h$stablePtrBuf  = h$newByteArray(8);
var h$stablePtrN    = 1;
var h$stablePtrFree = [];

function h$makeStablePtr(v) {
  TRACE_STABLEPTR("makeStablePtr")
  if(!v) return 0;
  var slot = h$stablePtrFree.pop();
  if(slot === undefined) {
    slot = h$stablePtrN++;
  }
  TRACE_STABLEPTR("  -> slot:" + slot)
  h$stablePtrData[slot] = v;
  return slot << 2;
}

var h$foreignExports = [];
function h$foreignExport(f, packageName, moduleName, functionName, typeSig) {
  h$foreignExports.push({ exported: f,
                          package: packageName,
                          mod:  moduleName,
                          name: functionName,
                          sig: typeSig
                        });
  // console.log("foreign export:", f, packageName, moduleName, functionName, typeSig);
  h$makeStablePtr(f);
  if(typeof exports === 'object') {
    if(typeof exports[functionName] === 'undefined') {
      exports[functionName] = f;
    }
  }
}
/*
function h$foreignExportStablePtr(x) {
  // h$makeStablePtr(x);
}
*/
function h$deRefStablePtr(stable_o) {
  var slot = stable_o >> 2;
  return h$stablePtrData[slot];
}

function h$hs_free_stable_ptr(stable_d, stable_o) {
  var slot = stable_o >> 2;
  TRACE_STABLEPTR("hs_free_stable_ptr")
  if(h$stablePtrData[slot] !== null) {
    h$stablePtrData[slot] = null;
    h$stablePtrFree.push(slot);
  }
}

// not strictly stableptr, but we make it work only for stable pointers
function h$addrToAny(addr_v, addr_o) {
  TRACE_STABLEPTR("addrToAny")
  TRACE_STABLEPTR(addr_v === h$stablePtrBuf)
  var slot = addr_o >> 2;
  return h$stablePtrData[slot];
}