This repository has been archived by the owner on Nov 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathjsapi.js
399 lines (321 loc) · 11.7 KB
/
jsapi.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
* jsapi.js
* JavaScript bindings for Sparkling
* Created by Arpad Goretity on 01/09/2014.
*
* Licensed under the 2-clause BSD License
*/
(function () {
// Takes a JavaScript string, returns the index of
// the function representing the compiled program
var compile = Module.cwrap('jspn_compile', 'number', ['string']);
var compileExpr = Module.cwrap('jspn_compileExpr', 'number', ['string']);
var parse = Module.cwrap('jspn_parse', 'number', ['string']);
var parseExpr = Module.cwrap('jspn_parseExpr', 'number', ['string']);
var compileAST = Module.cwrap('jspn_compileAST', 'number', ['number']);
// Takes a function index and an array index.
// Returns the index of the value which is the result of calling the
// function at the given index in the specified array as arguments.
var call = Module.cwrap('jspn_call', 'number', ['number', 'number']);
// takes the name of a global value, returns its referencing index
var getGlobal = Module.cwrap('jspn_getGlobal', 'number', ['string']);
// Given a JavaScript value, converts it to a Sparkling value
// and returns its referencing index
var addJSValue = function (val) {
var typeMap = {
'undefined': addNil,
'boolean': addBool,
'number': addNumber,
'string': addString,
'object': addObject,
'function': addFunction
};
var typeErrorFn = function () {
throw "Unrecognized type: " + typeof val;
};
var conversionFn = typeMap[typeof val] || typeErrorFn;
return conversionFn(val);
};
// Private helpers for addJSValue
var addNil = Module.cwrap('jspn_addNil', 'number', []);
var addBool = Module.cwrap('jspn_addBool', 'number', ['number']);
var addNumber = Module.cwrap('jspn_addNumber', 'number', ['number']);
var addString = Module.cwrap('jspn_addString', 'number', ['string']);
// We are trying to be robust with this function and check for
// auto-boxed variants of primitive boolean, number and string values.
var addObject = function (val) {
// unfortunately, typeof null === 'object'...
if (val === null) {
return addNil();
} else if (val instanceof Boolean) {
return addBool(val.valueOf());
} else if (val instanceof Number) {
return addNumber(val.valueOf());
} else if (val instanceof String) {
return addString(val.toString());
} else if (val instanceof Array) {
return addArray(val);
} else if (val instanceof SparklingNonSerializable) {
return addNonSerializable(val);
} else {
return addDictionary(val);
}
};
var addArray = function (val) {
var length = val.length;
var i;
var index;
var indexBuffer = Module._malloc(length * 4);
var result;
for (i = 0; i < length; i++) {
index = addJSValue(val[i]);
Module.setValue(indexBuffer + i * 4, index, 'i32');
}
result = addArrayWithIndexBuffer(indexBuffer, length);
Module._free(indexBuffer);
return result;
};
var addDictionary = function (val) {
var keys = Object.keys(val);
var length = keys.length;
var i;
var key;
var keyIndex, valIndex;
var indexBuffer = Module._malloc(length * 2 * 4);
var result;
for (i = 0; i < length; i++) {
key = keys[i];
keyIndex = addJSValue(key);
valIndex = addJSValue(val[key]);
Module.setValue(indexBuffer + (2 * i + 0) * 4, keyIndex, 'i32');
Module.setValue(indexBuffer + (2 * i + 1) * 4, valIndex, 'i32');
}
result = addDictionaryWithIndexBuffer(indexBuffer, length);
Module._free(indexBuffer);
return result;
};
var addNonSerializable = function (val) {
return val.index;
};
// Adds a native array that contains the object at the
// specified referencing indices, then returns the
// referencing index of the newly created array.
// Parameters: (int32_t *indexBuffer, size_t numberOfObjects)
var addArrayWithIndexBuffer = Module.cwrap('jspn_addArrayWithIndexBuffer', 'number', ['number', 'number']);
// Similar to addArrayWithIndexBuffer, but also adds the keys
// and constructs a dictionary instead of an array.
// Parameters: (int32_t *indexBuffer, size_t numberOfKeyValuePairs)
var addDictionaryWithIndexBuffer = Module.cwrap('jspn_addDictionaryWithIndexBuffer', 'number', ['number', 'number']);
// this belongs to addFunction
var wrappedFunctions = [];
var addFunction = function (val) {
// optimization: if this function is a wrapper around
// a function that comes from Sparkling anyway, then
// just return its original index.
if (val.fnIndex !== undefined) {
return val.fnIndex;
}
// Else, i. e. if 'val' is a naked JavaScript function,
// then create a wrapper around it
var wrapIndex = wrappedFunctions.length;
wrappedFunctions.push(val);
return addWrapperFunction(wrapIndex);
};
// Takes an index into the wrappedFunctions array.
// Returns the referencing index of an SpnValue<SpnFunction> that,
// when called, will call the aforementioned JavaScript function.
var addWrapperFunction = Module.cwrap('jspn_addWrapperFunction', 'number', ['number']);
// This is the inverse of 'addJSValue'. Given an internal
// referencing index, pulls out the corresponding SpnValue
// and converts it into a JavaScript value.
var valueAtIndex = function (index) {
/*
var TYPE_NIL = 0,
TYPE_BOOL = 1,
TYPE_NUMBER = 2,
TYPE_RAWPTR = 3,
TYPE_OBJECT = 4;
*/
var conversionFunctions = [
getNil,
getBool,
getNumber,
getNonSerializable,
getObject
];
var typeErrorFn = function () {
throw "unknown type tag";
};
var typeIndex = typeAtIndex(index);
var conversionFn = conversionFunctions[typeIndex] || typeErrorFn;
return conversionFn(index);
};
var typeAtIndex = Module.cwrap('jspn_typeAtIndex', 'number', ['number']);
var valueTypeNameAtIndex = Module.cwrap('jspn_valueTypeNameAtIndex', 'string', ['number']);
var getNil = function (index) {
return undefined;
};
// Module.cwrap seems <s>not to interpret the 'boolean'
// return type correctly</s> not to support 'boolean' at all,
// either as a return type or as an argument type, and passing
// 'boolean' as an argument type will throw an exception.
// Hence the following work-around.
var getBool = function (index) {
return !!rawGetBool(index);
}
var rawGetBool = Module.cwrap('jspn_getBool', 'number', ['number']);
var getNumber = Module.cwrap('jspn_getNumber', 'number', ['number']);
var getString = Module.cwrap('jspn_getString', 'string', ['number']);
function SparklingNonSerializable(index) {
this.index = index;
return this;
}
// Just returns a wrapper object
var getNonSerializable = function (index) {
return new SparklingNonSerializable(index);
};
var getObject = function (index) {
var typeName = valueTypeNameAtIndex(index);
var typewiseGetters = {
'string': getString,
'array': getArray,
'hashmap': getHashmap,
'function': getFunction
};
var getter = typewiseGetters[typeName] || getNonSerializable;
return getter(index);
}
var getArray = function (index) {
var i;
var values = [];
var length = countOfArrayAtIndex(index);
var indexBuffer = Module._malloc(length * 4);
getValueIndicesOfArrayAtIndex(index, indexBuffer);
for (i = 0; i < length; i++) {
valueIndex = Module.getValue(indexBuffer + i * 4, 'i32');
values[i] = valueAtIndex(valueIndex);
}
Module._free(indexBuffer);
return values;
};
var getHashmap = function (index) {
var i;
var keyIndex, valueIndex, key, value;
var object = {};
var length = countOfHashMapAtIndex(index);
var indexBuffer = Module._malloc(length * 2 * 4);
getKeyAndValueIndicesOfHashMapAtIndex(index, indexBuffer);
for (i = 0; i < length; i++) {
keyIndex = Module.getValue(indexBuffer + (2 * i + 0) * 4, 'i32');
key = valueAtIndex(keyIndex);
valueIndex = Module.getValue(indexBuffer + (2 * i + 1) * 4, 'i32');
value = valueAtIndex(valueIndex);
if (typeof key !== 'string') {
Module._free(indexBuffer);
throw "keys must be strings";
}
object[key] = value;
}
Module._free(indexBuffer);
return object;
};
var countOfArrayAtIndex = Module.cwrap('jspn_countOfArrayAtIndex', 'number', ['number']);
var countOfHashMapAtIndex = Module.cwrap('jspn_countOfHashMapAtIndex', 'number', ['number']);
var getValueIndicesOfArrayAtIndex = Module.cwrap('jspn_getValueIndicesOfArrayAtIndex', null, ['number', 'number']);
var getKeyAndValueIndicesOfHashMapAtIndex = Module.cwrap('jspn_getKeyAndValueIndicesOfHashMapAtIndex', null, ['number', 'number']);
var getFunction = function (fnIndex) {
// XXX: should we check if the value at given index is really a function?
var result = function () {
var argv = Array.prototype.slice.apply(arguments);
var argvIndex = addArray(argv); // returns the index of an SpnValue<SpnArray>
var retIndex = call(fnIndex, argvIndex);
if (retIndex < 0) {
throw Sparkling.lastErrorMessage();
}
return valueAtIndex(retIndex);
};
// optimization, see the relevant comment in addFunction
result.fnIndex = fnIndex;
return result;
};
// Takes a pointer to SpnArray and an integer index,
// Returns the integer value of the array's element at that index.
var getIntFromArray = Module.cwrap('jspn_getIntFromArray', 'number', ['number', 'number']);
var backtrace = Module.cwrap('jspn_backtrace', 'string', []);
var lastErrorLine = Module.cwrap('jspn_lastErrorLine', 'number', []);
var lastErrorColumn = Module.cwrap('jspn_lastErrorColumn', 'number', []);
Sparkling = {
// export these values as "private" symbols
// in order that auxlib.js be able to use them
_wrappedFunctions: wrappedFunctions,
_valueAtIndex: valueAtIndex,
_addJSValue: addJSValue,
_getIntFromArray: getIntFromArray,
// Public API
compile: function (src) {
var fnIndex = compile(src);
return fnIndex < 0 ? undefined : getFunction(fnIndex);
},
compileExpr: function (src) {
var fnIndex = compileExpr(src);
return fnIndex < 0 ? undefined : getFunction(fnIndex);
},
parse: function (src) {
var astIndex = parse(src);
return astIndex < 0 ? undefined : getHashmap(astIndex);
},
parseExpr: function (src) {
var astIndex = parseExpr(src);
return astIndex < 0 ? undefined : getHashmap(astIndex);
},
compileAST: function (ast) {
var astIndex = addDictionary(ast);
var fnIndex = compileAST(astIndex);
return fnIndex < 0 ? undefined : getFunction(fnIndex);
},
lastErrorMessage: Module.cwrap('jspn_lastErrorMessage', 'string', []),
lastErrorType: Module.cwrap('jspn_lastErrorType', 'string', []),
lastErrorLocation: function () {
return {
line: lastErrorLine(),
column: lastErrorColumn(),
toString: function() {
return "L " + this.line + ", C " + this.column;
}
};
},
backtrace: function () {
function parseBacktrace(line) {
var parts = line.split("|");
var address = parseInt(parts[4], 16);
return {
"function": parts[0],
"file": parts[1],
"line": parseInt(parts[2], 10) || undefined,
"column": parseInt(parts[3], 10) || undefined,
"address": address >= 0 ? address : undefined,
toString: function() {
var str = "function " + this["function"] + "()";
str += this.file !== "???" ? " in " + this.file : "";
str += this.line ? ", L " + this.line : "";
str += this.column ? ", C " + this.column : "";
str += this.address ? ", at address 0x" + this.address.toString(16) : "";
return str;
}
};
}
var bt = backtrace();
return bt ? bt.split("\n").map(parseBacktrace) : [];
},
getGlobal: function (name) {
return valueAtIndex(getGlobal(name));
},
// Frees all memory used by Sparkling values generated
// by Sparkling code. (This includes the return values
// of functions as well as the results of automatic
// conversion between JavaScript and Sparkling in both
// directions.)
freeAll: Module.cwrap('jspn_freeAll', null, []),
reset: Module.cwrap('jspn_reset', null, [])
};
}());