forked from espruino/Espruino
-
Notifications
You must be signed in to change notification settings - Fork 4
/
build_jswrapper.py
executable file
·525 lines (451 loc) · 19.5 KB
/
build_jswrapper.py
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/python
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <[email protected]>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ----------------------------------------------------------------------------------------
# Scans files for comments of the form /*JSON......*/ and then builds a tree structure of ifs to
# efficiently detect the symbols without using RAM. See common.py for formatting
# ----------------------------------------------------------------------------------------
import subprocess;
import re;
import json;
import sys;
import os;
scriptdir = os.path.dirname(os.path.realpath(__file__))
basedir = scriptdir+"/../"
sys.path.append(basedir+"scripts");
sys.path.append(basedir+"boards");
import common
# ------------------------------------------------------------------------------------------------------
def codeOut(s):
# print str(s)
wrapperFile.write(s+"\n");
# ------------------------------------------------------------------------------------------------------
def getConstructorTestFor(className, variableName):
# IMPORTANT - we expect built-in objects to be native functions with a pointer to
# their constructor function inside
for jsondata in jsondatas:
if jsondata["type"]=="constructor" and jsondata["name"]==className:
if variableName=="constructorPtr": # jsvIsNativeFunction/etc has already been done
return "constructorPtr==(void*)"+jsondata["generate"];
else:
return "jsvIsNativeFunction("+variableName+") && (void*)"+variableName+"->varData.native.ptr==(void*)"+jsondata["generate"];
print("No constructor found for "+className)
exit(1)
def getTestFor(className, static):
if static:
return getConstructorTestFor(className, "parent");
else:
if className=="String": return "jsvIsString(parent)"
if className=="Pin": return "jsvIsPin(parent)"
if className=="Integer": return "jsvIsInt(parent)"
if className=="Double": return "jsvIsFloat(parent)"
if className=="Number": return "jsvIsInt(parent) || jsvIsFloat(parent)"
if className=="Object": return "parent" # we assume all are objects
if className=="Array": return "jsvIsArray(parent)"
if className=="ArrayBufferView": return "jsvIsArrayBuffer(parent) && parent->varData.arraybuffer.type!=ARRAYBUFFERVIEW_ARRAYBUFFER"
if className=="Function": return "jsvIsFunction(parent)"
return getConstructorTestFor(className, "constructorPtr");
def toArgumentType(argName):
if argName=="": return "JSWAT_VOID";
if argName=="JsVar": return "JSWAT_JSVAR";
if argName=="JsVarArray": return "JSWAT_ARGUMENT_ARRAY";
if argName=="bool": return "JSWAT_BOOL";
if argName=="pin": return "JSWAT_PIN";
if argName=="int32": return "JSWAT_INT32";
if argName=="int": return "JSWAT_INT32";
if argName=="float": return "JSWAT_JSVARFLOAT";
sys.stderr.write("ERROR: toArgumentType: Unknown argument name "+argName+"\n")
exit(1)
def toCType(argName):
if argName=="": return "void";
if argName=="JsVar": return "JsVar*";
if argName=="JsVarArray": return "JsVar*";
if argName=="bool": return "bool";
if argName=="pin": return "Pin";
if argName=="int32": return "int";
if argName=="int": return "JsVarInt";
if argName=="float": return "JsVarFloat";
sys.stderr.write("ERROR: toCType: Unknown argument name "+argName+"\n")
exit(1)
def hasThis(func):
return func["type"]=="property" or func["type"]=="method"
def getParams(func):
params = []
if "params" in func:
for param in func["params"]:
params.append(param)
return params
def getResult(func):
result = [ "", "Description" ]
if "return" in func: result = func["return"]
return result
def getArgumentSpecifier(jsondata):
params = getParams(jsondata)
result = getResult(jsondata);
s = [ toArgumentType(result[0]) ]
if hasThis(jsondata): s.append("JSWAT_THIS_ARG");
# Either it's a variable/property, in which case we need to execute the native function in order to return the correct info
if jsondata["type"]=="variable" or common.is_property(jsondata):
s.append("JSWAT_EXECUTE_IMMEDIATELY")
# Or it's an object, in which case the native function contains code that creates it - and that must be executed too.
# It also returns JsVar
if jsondata["type"]=="object":
s = [ toArgumentType("JsVar"), "JSWAT_EXECUTE_IMMEDIATELY" ]
n = 1
for param in params:
s.append("("+toArgumentType(param[1])+" << (JSWAT_BITS*"+str(n)+"))");
n=n+1
return " | ".join(s);
def getCDeclaration(jsondata, name):
# name could be '(*)' for a C function pointer
params = getParams(jsondata)
result = getResult(jsondata);
s = [ ]
if hasThis(jsondata): s.append("JsVar*");
for param in params:
s.append(toCType(param[1]));
return toCType(result[0])+" "+name+"("+",".join(s)+")";
def codeOutSymbolTable(builtin):
codeName = builtin["name"]
# sort by name
builtin["functions"] = sorted(builtin["functions"], key=lambda n: n["name"]);
# output tables
listSymbols = []
listChars = ""
strLen = 0
for sym in builtin["functions"]:
symName = sym["name"];
if builtin["name"]=="global" and symName in libraries:
continue # don't include libraries on global namespace
if "generate" in sym:
listSymbols.append("{"+", ".join([str(strLen), "(void (*)(void))"+sym["generate"], getArgumentSpecifier(sym)])+"}")
listChars = listChars + symName + "\\0";
strLen = strLen + len(symName) + 1
else:
print (codeName + "." + symName+" not included in Symbol Table because no 'generate'")
builtin["symbolTableChars"] = "\""+listChars+"\"";
builtin["symbolTableCount"] = str(len(listSymbols));
codeOut("static const JswSymPtr jswSymbols_"+codeName+"[] = {\n "+",\n ".join(listSymbols)+"\n};");
def codeOutBuiltins(indent, builtin):
codeOut(indent+"jswBinarySearch(&jswSymbolTables["+builtin["indexName"]+"], parent, name);");
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------
jsondatas = common.get_jsondata(False)
includes = common.get_includes_from_jsondata(jsondatas)
# work out what we have actually got
classes = []
constructors = []
for jsondata in jsondatas:
if "class" in jsondata :
if not jsondata["class"] in classes:
classes.append(jsondata["class"])
if jsondata["type"]=="constructor":
if not jsondata["name"] in constructors:
constructors.append(jsondata["name"])
# Add constructors if we need them
for className in classes:
if not className in constructors:
jsondatas.append({
"type":"constructor", "class": className, "name": className,
"generate_full" : "jsvNewWithFlags(JSV_OBJECT)",
"filename" : "jswrapper.c",
"return" : [ "JsVar", "" ]
});
# ------------------------------------------------------------------------------------------------------
#print json.dumps(tree, sort_keys=True, indent=2)
# ------------------------------------------------------------------------------------------------------
wrapperFile = open('gen/jswrapper.c', 'w')
codeOut('// Automatically generated wrapper file ')
codeOut('// Generated by scripts/build_jswrapper.py');
codeOut('');
codeOut('#include "jswrapper.h"');
codeOut('#include "jsnative.h"');
for include in includes:
codeOut('#include "'+include+'"');
codeOut('');
codeOut('');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('// ----------------------------------------------------------------- AUTO-GENERATED WRAPPERS');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('');
for jsondata in jsondatas:
if ("generate_full" in jsondata) or (jsondata["type"]=="object"):
gen_name = "gen_jswrap"
if "class" in jsondata: gen_name = gen_name + "_" + jsondata["class"];
gen_name = gen_name + "_" + jsondata["name"];
jsondata["generate"] = gen_name
s = [ ]
if jsondata["type"]=="object":
jsondata["generate_full"] = "jspNewObject(\""+jsondata["name"]+"\", \""+jsondata["instanceof"]+"\") /* needs JSWAT_EXECUTE_IMMEDIATELY */";
params = []
result = ["JsVar"]
else:
params = getParams(jsondata)
result = getResult(jsondata);
if hasThis(jsondata): s.append("JsVar *parent");
for param in params:
s.append(toCType(param[1])+" "+param[0]);
codeOut("static "+toCType(result[0])+" "+jsondata["generate"]+"("+", ".join(s)+") {");
if result[0]:
codeOut(" return "+jsondata["generate_full"]+";");
else:
codeOut(" "+jsondata["generate_full"]+";");
codeOut("}");
codeOut('');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('');
codeOut("""
JsVar *jswBinarySearch(const JswSymList *symbolsPtr, JsVar *parent, const char *name) {
int searchMin = 0;
int searchMax = symbolsPtr->symbolCount-1;
while (searchMin <= searchMax) {
int idx = (searchMin+searchMax) >> 1;
const JswSymPtr *sym = &symbolsPtr->symbols[idx];
int cmp = strcmp(name, &symbolsPtr->symbolChars[sym->strOffset]);
if (cmp==0) {
if ((sym->functionSpec & JSWAT_EXECUTE_IMMEDIATELY_MASK) == JSWAT_EXECUTE_IMMEDIATELY)
return jsnCallFunction(sym->functionPtr, sym->functionSpec, parent, 0, 0);
return jsvNewNativeFunction(sym->functionPtr, sym->functionSpec);
} else {
if (cmp<0) {
// searchMin is the same
searchMax = idx-1;
} else {
searchMin = idx+1;
// searchMax is the same
}
}
}
return 0;
}
""");
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('// -----------------------------------------------------------------------------------------');
codeOut('');
codeOut('');
print("Finding Libraries")
libraries = []
for jsondata in jsondatas:
if jsondata["type"]=="library":
print("Found library "+jsondata["class"])
libraries.append(jsondata["class"])
print("Classifying Functions")
builtins = {}
for jsondata in jsondatas:
if "name" in jsondata:
jsondata["static"] = not (jsondata["type"]=="property" or jsondata["type"]=="method")
testCode = "!parent"
builtinName = "global"
className = "global"
isProto = False
if not jsondata["type"]=="constructor":
if "class" in jsondata:
testCode = getTestFor(jsondata["class"], jsondata["static"])
className = jsondata["class"]
builtinName = className
if not jsondata["static"]:
isProto = True
builtinName = builtinName+"_proto";
if not testCode in builtins:
print("Adding "+testCode+" to builtins")
builtins[testCode] = { "name" : builtinName, "className" : className, "isProto" : isProto, "functions" : [] }
builtins[testCode]["functions"].append(jsondata);
print("Outputting Symbol Tables")
idx = 0
for b in builtins:
builtin = builtins[b]
codeOutSymbolTable(builtin);
builtins[b]["indexName"] = "jswSymbolIndex_"+builtin["name"];
codeOut("static const unsigned char "+builtin["indexName"]+" = "+str(idx)+";");
idx = idx + 1
codeOut('');
codeOut('');
codeOut('const JswSymList jswSymbolTables[] = {');
for b in builtins:
builtin = builtins[b]
codeOut(" {"+", ".join(["jswSymbols_"+builtin["name"], builtin["symbolTableCount"], builtin["symbolTableChars"]])+"},");
codeOut('};');
codeOut('');
codeOut('');
codeOut('JsVar *jswFindBuiltInFunction(JsVar *parent, const char *name) {')
codeOut(' JsVar *v;')
codeOut(' if (parent && !jsvIsRoot(parent)) {')
codeOut(' // ------------------------------------------ INSTANCE + STATIC METHODS')
nativeCheck = "jsvIsNativeFunction(parent) && "
codeOut(' if (jsvIsNativeFunction(parent)) {')
first = True
for className in builtins:
if className.startswith(nativeCheck):
codeOut(' '+("" if first else "} else ")+'if ('+className[len(nativeCheck):]+') {')
first = False
codeOutBuiltins(" v = ", builtins[className])
codeOut(' if (v) return v;');
if not first:
codeOut(" }")
codeOut(' }')
for className in builtins:
if className!="parent" and className!="!parent" and not "constructorPtr" in className and not className.startswith(nativeCheck):
codeOut(' if ('+className+') {')
codeOutBuiltins(" v = ", builtins[className])
codeOut(' if (v) return v;');
codeOut(" }")
codeOut(' // ------------------------------------------ INSTANCE METHODS WE MUST CHECK CONSTRUCTOR FOR')
codeOut(' JsVar *proto = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_INHERITS_VAR, false)):0;')
codeOut(' JsVar *constructor = jsvIsObject(proto)?jsvSkipNameAndUnLock(jsvFindChildFromString(proto, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
codeOut(' jsvUnLock(proto);')
codeOut(' if (constructor && jsvIsNativeFunction(constructor)) {')
codeOut(' void *constructorPtr = constructor->varData.native.ptr;')
codeOut(' jsvUnLock(constructor);')
first = True
for className in builtins:
if "constructorPtr" in className:
if first:
codeOut(' if ('+className+') {')
first = False
else:
codeOut(' } else if ('+className+') {')
codeOutBuiltins(" v = ", builtins[className])
codeOut(' if (v) return v;')
if not first:
codeOut(" }")
codeOut(' } else {')
codeOut(' jsvUnLock(constructor);')
codeOut(' }')
codeOut(' // ------------------------------------------ METHODS ON OBJECT')
if "parent" in builtins:
codeOutBuiltins(" v = ", builtins["parent"])
codeOut(' if (v) return v;');
codeOut(' } else { /* if (!parent) */')
codeOut(' // ------------------------------------------ FUNCTIONS')
codeOut(' // Handle pin names - eg LED1 or D5 (this is hardcoded in build_jsfunctions.py)')
codeOut(' Pin pin = jshGetPinFromString(name);')
codeOut(' if (pin != PIN_UNDEFINED) {')
codeOut(' return jsvNewFromPin(pin);')
codeOut(' }')
if "!parent" in builtins:
codeOutBuiltins(" return ", builtins["!parent"])
codeOut(' }');
codeOut(' return 0;')
codeOut('}')
codeOut('')
codeOut('')
codeOut('const JswSymList *jswGetSymbolListForObject(JsVar *parent) {')
for className in builtins:
builtin = builtins[className]
if not className in ["parent","!parent"] and not builtin["isProto"]:
codeOut(" if ("+className+") return &jswSymbolTables["+builtin["indexName"]+"];");
codeOut(" if (parent==execInfo.root) return &jswSymbolTables[jswSymbolIndex_global];");
codeOut(" return 0;")
codeOut('}')
codeOut('')
codeOut('')
codeOut('const JswSymList *jswGetSymbolListForObjectProto(JsVar *parent) {')
codeOut(' if (jsvIsNativeFunction(parent)) {')
for className in builtins:
builtin = builtins[className]
if builtin["isProto"] and not "constructorPtr" in className and not className in ["parent","!parent"] :
check = className
for jsondata in jsondatas:
if jsondata["type"]=="constructor" and jsondata["name"]==builtin["className"]:
check = "(void*)parent->varData.native.ptr==(void*)"+jsondata["generate"]
codeOut(" if ("+check+") return &jswSymbolTables["+builtin["indexName"]+"];");
codeOut(' }')
codeOut(' JsVar *constructor = jsvIsObject(parent)?jsvSkipNameAndUnLock(jsvFindChildFromString(parent, JSPARSE_CONSTRUCTOR_VAR, false)):0;')
codeOut(' if (constructor && jsvIsNativeFunction(constructor)) {')
codeOut(' void *constructorPtr = constructor->varData.native.ptr;')
codeOut(' jsvUnLock(constructor);')
for className in builtins:
builtin = builtins[className]
if builtin["isProto"] and "constructorPtr" in className:
codeOut(" if ("+className+") return &jswSymbolTables["+builtin["indexName"]+"];");
codeOut(' }')
nativeCheck = "jsvIsNativeFunction(parent) && "
for className in builtins:
if className!="parent" and className!="!parent" and not "constructorPtr" in className and not className.startswith(nativeCheck):
codeOut(' if ('+className+") return &jswSymbolTables["+builtins[className]["indexName"]+"];");
codeOut(" return &jswSymbolTables["+builtins["parent"]["indexName"]+"];")
codeOut('}')
codeOut('')
codeOut('')
builtinChecks = []
for jsondata in jsondatas:
if "class" in jsondata:
check = 'strcmp(name, "'+jsondata["class"]+'")==0';
if not jsondata["class"] in libraries:
if not check in builtinChecks:
builtinChecks.append(check)
codeOut('bool jswIsBuiltInObject(const char *name) {')
codeOut(' return\n'+" ||\n ".join(builtinChecks)+';')
codeOut('}')
codeOut('')
codeOut('')
codeOut('void *jswGetBuiltInLibrary(const char *name) {')
for lib in libraries:
codeOut('if (strcmp(name, "'+lib+'")==0) return (void*)gen_jswrap_'+lib+'_'+lib+';');
codeOut(' return 0;')
codeOut('}')
codeOut('')
codeOut('')
objectChecks = {}
for jsondata in jsondatas:
if "type" in jsondata and jsondata["type"]=="class":
if "check" in jsondata:
objectChecks[jsondata["class"]] = jsondata["check"]
codeOut('/** Given a variable, return the basic object name of it */')
codeOut('const char *jswGetBasicObjectName(JsVar *var) {')
for className in objectChecks.keys():
codeOut(" if ("+objectChecks[className]+") return \""+className+"\";")
codeOut(' return 0;')
codeOut('}')
codeOut('')
codeOut('')
codeOut("/** Given the name of a Basic Object, eg, Uint8Array, String, etc. Return the prototype object's name - or 0. */")
codeOut('const char *jswGetBasicObjectPrototypeName(const char *objectName) {')
for jsondata in jsondatas:
if "type" in jsondata and jsondata["type"]=="class":
if "prototype" in jsondata:
#print json.dumps(jsondata, sort_keys=True, indent=2)
codeOut(" if (!strcmp(objectName, \""+jsondata["class"]+"\")) return \""+jsondata["prototype"]+"\";")
codeOut(' return strcmp(objectName,"Object") ? "Object" : 0;')
codeOut('}')
codeOut('')
codeOut('')
codeOut("/** Tasks to run on Idle. Returns true if either one of the tasks returned true (eg. they're doing something and want to avoid sleeping) */")
codeOut('bool jswIdle() {')
codeOut(' bool wasBusy = false;')
for jsondata in jsondatas:
if "type" in jsondata and jsondata["type"]=="idle":
codeOut(" if ("+jsondata["generate"]+"()) wasBusy = true;")
codeOut(' return wasBusy;')
codeOut('}')
codeOut('')
codeOut('')
codeOut("/** Tasks to run on Initialisation */")
codeOut('void jswInit() {')
for jsondata in jsondatas:
if "type" in jsondata and jsondata["type"]=="init":
codeOut(" "+jsondata["generate"]+"();")
codeOut('}')
codeOut('')
codeOut('')
codeOut("/** Tasks to run on Deinitialisation */")
codeOut('void jswKill() {')
for jsondata in jsondatas:
if "type" in jsondata and jsondata["type"]=="kill":
codeOut(" "+jsondata["generate"]+"();")
codeOut('}')
codeOut('')
codeOut('')