-
Notifications
You must be signed in to change notification settings - Fork 0
/
jswmgen.js
732 lines (689 loc) · 27.9 KB
/
jswmgen.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/*
* This file is part of ESP32_TinyConsole.
*
* Copyright (c) 2024 spuggy0919
*
* ESP32_TinyConsole is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ESP32_TinyConsole is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ESP32_TinyConsole. If not, see
*
* https://github.com/spuggy0919/ESP32_WEB_CONTROL/blob/espcontrol/LICENSE
* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
*
* Author: spuggy0919, [email protected]
*/
/*
*
*/
/*
* @file jswmgen.js
* @brief C++ class wrapper generator
*
* @details
* run this script parser a json file to generate wrapper source code
* %js jswmgen [methods.json [output.cpp]]
* readme to add into *
* this generator for method property , check mapping arglist and call obj method
* TODO callback setting is not generator, need manual dirty work
* Byte* array mapping use arraybuffer
* How to use
* 1. fill the need field in methods
* classObj your objname , for example 'rect'
* constructorPrototype :: is needed, for example 'Rectangle::Rectangle(int length,int width);'
* prototypesArray
* 2. upload to tinyconsole
* 3. js jswmgen [enter]
* 4. select, copy and paste to file.
* Example rectangle
* %js jswmgen rectangle.json rect.cpp
* %cat rect.cpp #select copy and past
** @classname None
* @instance none
*
* @date Apirl 15, 2024
*/
// TODO for command line mode
// TODO usage js jswmgen methos.json file.cpp
// todo method prototype array using Object.array.forEach to generate all method handles
/* main */
// type mapping (c_arg_type->js_arg_type) (cret->jsrettype)
// maybe need to correction
let process = require('process');
let fs = (process.cwd() == '/js/jswmgen') ? require('nodefs'): require('./nodefs');
const version = '0.9.0';
const app = process.argv[1];
let jsonFileName='./json/esp.json';
let outFileName='./jswrapper/autotemp.cpp';
var methods;
var cobj;
var lines = 0;
if (process.argv.length>2) {
jsonFileName ='./json/'+process.argv[2];
}
const [argMappings_C_to_JS,retMappings_C_to_JS] = definedConst();
[methods,cobj] = loadJsonFile(jsonFileName);
outFileName = './jswrapper/jsw_'+methods.className+".cpp";
if (process.argv.length==4) outFileName = './jswrapper/'+process.argv[3];
dumpMethods(jsonFileName,outFileName,methods);
pass1CheckMethods(jsonFileName,outFileName,methods);
jswGenerator(methods);
if (outFileName!='') console.log(`Total ${lines} lines`);
/* load method Object which is defined in JSON file */
function loadJsonFile(jsonFile){
let methods={ // default
classObj : "rectangle",
constructorPrototype : "Rectangle::Rectangle(int length,int width);",
prototypesArray : [
"int getSize();",
"int getLength();",
"int getWidth();",
"int getBuffer(uint8_t* buf, size_t length);" // test arraybuffer
],
className :"",
methodNames:[]
};
const configStr = fs.readFileNodeJS(jsonFile);
methods = JSON.parse(configStr);
if (typeof methods == 'undefined') {
console.log('Error: JSAON Parser');
}
let cobj = constructorPrototypeParser(methods.classObj,methods.constructorPrototype);
// methods.className = cobj.className;
methods.methodNames=[];
return [methods,cobj];
}
function dumpMethods(jsonFile,outFile,methods){
console.log('//C++ wrapper auto generator jswmgen.js ver.'+version);
console.log('//https://github.com/spuggy0919/jswrapper.git');
console.log('//**WARNING**You should examine and fix the code to meet your requirements!');
console.log('//Json:',jsonFile,'\n');
console.log('//File:',outFile,'\n');
console.log('//className:',methods.className,'\n');
console.log('//classObj:',methods.classObj,'\n');
console.log('//constructorPrototype:',methods.constructorPrototype,'\n');
console.log('//prototypesArray:\n');
methods.prototypesArray.forEach(element => {
// print(element);
console.log('// ',element,'\n');
});
if (outFile!=''){
fs.deleteFileNodeJS(outFile);
// writeln(outFile,'// '+outFile,app+version);
let now = new Date();
fs.writeFileNodeJS(outFile,''); // createFile
writeln(outFile,'//C++ wrapper auto generator jswmgen.js ver.'+version);
writeln(outFile,'//https://github.com/spuggy0919/jswrapper.git');
writeln(outFile,'//**WARNING**You should examine and fix the code to meet your requirements!');
writeln(outFile,'//'+now.toString().slice(0,33));
writeln(outFile,'//Json:'+jsonFile);
writeln(outFile,'//File:'+outFile);
writeln(outFile,'//className:'+methods.className);
writeln(outFile,'//classObj:'+methods.classObj);
writeln(outFile,'//constructorPrototype:'+methods.constructorPrototype);
writeln(outFile,'//prototypesArray:');
methods.prototypesArray.forEach(element => {
// print(element);
writeln(outFile,'// '+element);
});
}
}
function pass1CheckMethods(jsonFile,outFile,methods){
methods.prototypesArray.forEach(element => {
console.log('pass1CheckMethods:',element);
methodParserCheckeer(element);
});
}
function methodParserCheckeer(methodPrototype) {
let methodElementsC = extractMethodElements(methodPrototype);
let methodName = methodElementsC.methodName;
let returnctype = methodElementsC.rettype;
//TODO retMappings_C_to_JS[returnctype];
//TODO concerns call method arg typecast
let returnjstype = retMappings_C_to_JS[returnctype];//methodElementsJS.rettype;
let argvCnt = methodElementsC.argvCnt;
try {
if (typeof returnjstype === 'undefined' || returnjstype === ''){
returnjstype = 'undefined';
throw new Error(`Exception retType ${returnctype}, js is null`);
}
if (argvCnt == 0) return;
let argvtype = methodElementsC.argvtypeArray;
let argvname = methodElementsC.argvnameArray;
argvtype.forEach(element => {
let argCtype = argMappings_C_to_JS[element]; // print(element);
if (typeof returnjstype === 'undefined' || argCtype === ''){
throw new Error(`Exception argType ${methodName} ${argCtype}`);
}
});
argvname.forEach(element => {
if (typeof returnjstype === 'undefined' || argvname === ''){
throw new Error(`Exception argName ${methodName} ${argvname}`);
}
});
}catch(e){
console.error('Error:', e.message);
}
}
function outputFileMessage(statements){
if (outFileName!=''){ // outFileName global
// append file TODO
writeln(outFileName,statements);
return;
}
console.log(statements);
}
function outputFileBoth(statements){
if (outFileName!=''){ // outFileName global
// append file TODO
writeln(outFileName,statements);
}
if (statements.length>10) console.log(statements," Done!");
}
function writeln(outFile,msg){
fs.appendFileNodeJS(outFile,msg+"\n");
lines++;
}
function definedConst(){
return [definedConstArg(),definedConstRet()];
}
function definedConstArg(){
const argMappings_C_to_JS = { // TODO for arg_type mappings type
"size_t": "uint32",
"int": "int32",
"int_t": "int32",
"int8_t": "int8",
"int16_t": "int16",
"int32_t": "int32",
"uint": "uint32",
"uint8": "uint8",
"uint16": "uint16",
"uint32": "uint32",
"uint_t": "uint32",
"uint8_t": "uint8",
"uint16_t": "uint16",
"uint32_t": "uint32",
"uint_t*": "arraybuffer",
"uint8_t*": "arraybuffer",
"uint16_t*": "arraybuffer",
"uint32_t*": "arraybuffer",
"int*": "arraybuffer",
"int_t*": "arraybuffer",
"int8_t*": "arraybuffer",
"int16_t*": "arraybuffer",
"int32_t*": "arraybuffer",
"char*": "string", // possible use string_sz
"char": "uint8",
"char*": "string",
"double": "number",
"float": "number",
"bool": "boolean",
"ignore": "ignore", // TODO for callback should be typedef funcptr prototype
"void*": "native_pointer", // TODO for callback should be typedef funcptr prototype
"funcptr": "function", // TODO for callback should be typedef funcptr prototype
"custome": "custome" // TODO for callback should be typedef funcptr prototype
};
return argMappings_C_to_JS;
}
function definedConstRet(){
const retMappings_C_to_JS = { // TODO for return js type
"size_t": "number",
"int8": "number",
"int16": "number",
"int32": "number",
"int": "number",
"int_t": "number",
"int8_t": "number",
"int16_t": "number",
"int32_t": "number",
"uint8": "number",
"uint16": "number",
"uint32": "number",
"uint": "number",
"uint_t": "number",
"uint8_t": "number",
"uint16_t": "number",
"uint32_t": "number",
"uint8*": "string",
"uint8_t*": "string",
"int*": "number", // TODO return a array buffer point, now default number
"char*": "string",
"char": "number",
"bool": "boolean",
"void": "void" // undefined is keyword maybe transfer in functions
};// TODO crettype auto transfer to jsrettype
return retMappings_C_to_JS;
}
function jswGenerator(methods){
// #ifdef _LIB_CLASS_
LibdefHeaderGeneratorPush(cobj);
// native_info
destroyinfoGenerator(cobj);
// Methods
methodsGenerator(methods);
//,free_cb
destroyFreeCBGenerator(cobj);
outputFileMessage(`//Verify Methods List`);
cobj.methods = methods.methodNames;
cobj.methods.forEach((element) => {
outputFileMessage(`/*js_${cobj.classObjName}_${element}*/`);
});
// constructor
constructorGenerator(cobj);
// register
registerGenerator(cobj);
LibdefTailGeneratorPop();
}
function methodsGenerator(methods){
methods.prototypesArray.forEach(( prototypeC ) => {
let methodName = methodGenerator(methods.className,methods.classObj,prototypeC);
methods.methodNames.push(methodName);
});
}
function methodGenerator(className,classObj,prototypeC) {
let methodElementsC = extractMethodElements(prototypeC);
let methodName = methodElementsC.methodName;
let argvtype = methodElementsC.argvtypeArray;
let argvname = methodElementsC.argvnameArray;
let returnctype = methodElementsC.rettype;
//TODO retMappings_C_to_JS[returnctype];
//TODO concerns call method arg typecast
let returnjstype = retMappings_C_to_JS[returnctype];//methodElementsJS.rettype;
if (typeof returnjstype === 'undefined' || returnjstype === ''){
returnjstype = 'undefined';
throw new Error(`Exception retType ${returnctype}, js is null`);
}
let argvCtype = methodElementsC.argvtypeArray;
try {
genFunctionHeaderPush(classObj,prototypeC,methodName);
//2. mapping argument
argList(argvtype,argvname);
mapping(argvtype,argvname);
transform(argvtype);
getNativePtr(classObj);
callClassObjMethod(className,classObj,returnjstype,methodName,argvname,argvtype,argvCtype);
genFunctionTailPop();
} catch (e) {
// Catch and handle the error
console.error('Error:', e.message);
}
return methodName;
}
var blocks=[];
var level=0;
function resetblock(){
blocks=[];
level=0;
}
function pushblock(f){
blocks.push(f);
level++;
}
function popblock(){
s = blocks.pop();
level--;
outputFileBoth(s);
}
function genFunctionHeaderPush(classObj,prototypeC,methodName){
outputFileMessage(`//${prototypeC}`); // method prototype
//1. method prototype
outputFileMessage(`JS_METHOD(${classObj}_${methodName})`); // method prototype
outputFileMessage(`{`);
pushblock(`} /*js_${classObj}_${methodName}*/`);
}
function genFunctionTailPop(){
popblock();
}
function parserMatch(match) {
// Extracted elements
const rettype = match[1].trim();
const methodName = match[2].trim();
// console.log(rettype,retMappings_C_to_JS[rettype]);
// console.log(methodName);
// Check if the argument list is empty
if (match[3] === '') {
// Handle the case of an empty argument list
const argCnt = 0;
const argvtypeArray = [];
const argvnameArray = [];
// console.log(argCnt);
// Return the extracted elements as an object
return {
rettype,
methodName,
argCnt,
argvtypeArray,
argvnameArray
};
}
const argList = match[3];
// Split the argument list into individual arguments
const argArray = argList.split(',').map(arg => arg.trim());
// Extract argument types and names
const argvtypeArray = argArray.map(arg => arg.split(' ')[0].trim());
const argvnameArray = argArray.map(arg => arg.split(' ')[1].trim());
// Argument count
let argCnt = 0;
if ((typeof argArray !== undefined )) {
argCnt = argArray.length;
}
// Return the extracted elements as an object
return {
rettype,
methodName,
argCnt,
argvtypeArray,
argvnameArray
};
}
function extractMethodElements(methodPrototype) {
// Regular expression pattern to match the method prototype syntax
const pattern = /^(\w+\*?)\s+(\w+)\((.*?)\);?$/;
// Execute the regular expression on the method prototype
const match = methodPrototype.match(pattern);
if (match) {
return parserMatch(match);
// } else {
// Method prototype does not match the expected syntax
// throw new Error(`Method prototype extract error ${methodPrototype}`);
// return null;
}
return null;
}
function argList(argvtype,argvname){
if (typeof argvtype === 'undefined' || argvtype.length == 0){
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_UNUSED(call_info_p);`);
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_UNUSED(args_p);`);
outputFileMessage(`${' '.repeat(level * 4)}JERRYXX_ON_ARGS_COUNT_THROW_ERROR_SYNTAX(args_cnt != 0, "Wrong arguments count");`);
return 0;
}
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_UNUSED(call_info_p);`);
//2. mapping argument
let i=0;
for(i=0;i<argvtype.length;i++) {
if (argvtype[i]=='char*'){
outputFileMessage(`${' '.repeat(level * 4)}char ${argvname[i]}[32];// **WARNNING** need to check BUFFERSIZE`);
}else{
outputFileMessage(`${' '.repeat(level * 4)}${argvtype[i]} ${argvname[i]};`);
}
}
return argvtype.length;
}
function mappingEntry_string(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_string(${argvname}, sizeof(${argvname}), JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_array(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_array(&${argvname}, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_int(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_${argvtype}(&${argvname}, JERRYX_ARG_CEIL, JERRYX_ARG_NO_CLAMP, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_native_pointer(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}/* **TODO** need to define your c callback to use jerry_call */`);
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_function(&${argvname}, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_function(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}/* **TODO** need to define your c callback to use jerry_call */`);
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_function(&${argvname}, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_coerce_required(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_${argvtype}(&${argvname}, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_coerce_optional(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_${argvtype}(&${argvname}, JERRYX_ARG_NO_COERCE, JERRYX_ARG_OPTIONAL),`);
}
function mappingEntry_arraybuffer(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_${argvtype}(&${argvname}, JERRYX_ARG_REQUIRED),`);
}
function mappingEntry_ignore(argvname,argvtype){
outputFileMessage(`${' '.repeat(level * 4)}jerryx_arg_ignore (void), // *TODO*ignore should be modified as GFX drawbitmap, to get arraybuffer_data`);
}
function mapping(argvtype,argvname){
if (typeof argvtype=== 'undefined' || argvtype.length == 0) return 0;
outputFileMessage(`\n${' '.repeat(level * 4)}const jerryx_arg_t mapping[] ={`); lines++; // for newline
pushblock(`${' '.repeat(level * 4)}};`);
let i=0;
for(i=0;i<argvtype.length;i++) {
let jsargtype= argMappings_C_to_JS[argvtype[i]];
switch(jsargtype){// convert c type to mapping
case 'string':
mappingEntry_string(argvname[i],argvtype[i]);
break;
case 'array':
mappingEntry_array(argvname[i],argvtype[i]);
break;
case 'number':
case 'boolean':
mappingEntry_coerce_required(argvname[i],jsargtype);
break;
case 'int8':
case 'int16':
case 'int32':
case 'uint8':
case 'uint16':
case 'uint32':
mappingEntry_int(argvname[i],jsargtype);
break;
case 'arraybuffer':
mappingEntry_arraybuffer(argvname[i],jsargtype);
break;
case 'function':
mappingEntry_function(argvname[i],jsargtype);
break;
case 'native_point':
mappingEntry_native_pointer(argvname[i],jsargtype);
case 'ignore':
mappingEntry_ignore(argvname[i],jsargtype);
break;
default:
console.log('ERROR ',argvtype[i],argvname[i],'for arg Mapping()');
throw new Error(`Exception Type ${argvtype[i]}, ${argvname[i]} for arg Mapping()`);
}
}
popblock();
return 1;
}
function transform(argvtype){
if (typeof argvtype === 'undefined' || argvtype.length == 0) {
return;
}
outputFileMessage(`${' '.repeat(level * 4)}const jerry_value_t rv = jerryx_arg_transform_args(args_p, args_cnt, mapping, JERRYXX_ARRAY_SIZE(mapping));`);
outputFileMessage(`${' '.repeat(level * 4)}if (jerry_value_is_exception(rv)){`);
pushblock(`${' '.repeat(level * 4)}}`);
outputFileMessage(`${' '.repeat((level) * 4)}return rv;`);
popblock();
outputFileMessage(`${' '.repeat(level * 4)}JERRYXX_ON_ARGS_COUNT_THROW_ERROR_SYNTAX(args_cnt != ${argvtype.length}, "Wrong arguments count");`);
}
function getNativePtr(classObj){
outputFileMessage(`\n${' '.repeat(level * 4)}void *native_pointer = NULL;`); lines++; // for newline
outputFileMessage(`${' '.repeat(level * 4)}native_pointer = jerry_object_get_native_ptr(call_info_p->this_value, &${classObj}_info);`);
}
function callClassObjMethodArgs(methodName,argvname,argvtype){
let callargs = '';
callargs+=methodName+'(' ;
if (typeof argvname=== 'undefined' || argvname.length == 0) {
callargs+=')';
return callargs;
}
for(let i=0;i<argvname.length;i++){
if (1){
callargs+="("+argvtype[i]+') '; // type cast maybe ignore
}
callargs+=argvname[i]+((i!=argvname.length-1) ?',':')');
}
return callargs;
}
function callClassObjMethod(className,classObj,returnjstype,methodName,argvname,argvtype,argvCtype){
let rettype = returnjstype;
outputFileMessage(`\n${' '.repeat(level * 4)}if(native_pointer) {`); lines++; // for newline
pushblock(`${' '.repeat(level * 4)}}`);
outputFileMessage(`${' '.repeat(level * 4)}${className}* ${classObj} = (${className}*)native_pointer;`);
let callmethod = callClassObjMethodArgs(methodName,argvname,argvtype);
if (rettype=='void'){
// call method only then return
outputFileMessage(`${' '.repeat(level * 4)}${classObj}->${callmethod};`);
}else{
// return by js type
outputFileMessage(`${' '.repeat(level * 4)}return jerry_${returnjstype}(${classObj}->${callmethod});`);
}
popblock();
outputFileMessage(`${' '.repeat(level * 4)}return jerry_undefined();`);
}
/* return constructor parser obj */
function constructorPrototypeParser(classObjName,prototype) {
var constructor = {
className:'',
classObjName:'',
methods:[],
prototype:'TwoWire::TwoWire(uint8_t bus_num)',
argvCnt:0,
argvtypes:[],
argvnames:[],
jsretobjName:'js_cobj',
};
let cobj = constructor;
cobj.prototype = prototype;
cobj.classObjName = classObjName;
// Extract class name
cobj.className = prototype.split('::')[0].trim();
// Extract argument types and argument names
let pattern =/\(\s*\)/; //void
if (prototype.match(pattern)){
cobj.argvCnt = 0;
return cobj;
}
var argsPart = prototype.split('(')[1].split(')')[0];
var argsList = argsPart.split(',');
// Extract argument types and names
console.log(typeof argsPart, typeof argsList);
if (typeof argsList === 'undefined' || argsPart =='' ){
cobj.argvCnt = 0;
return cobj;
}
cobj.argvCnt = argsList.length;
if (argsList.length > 0 && argsList[0].trim() !== '') {
argsList.forEach(function(arg) {
var argParts = arg.trim().split(' ');
cobj.argvtypes.push(argParts[0]);
cobj.argvnames.push(argParts[1]);
});
}
return cobj;
}
function constructorGenerator(cobj) {
let prototypeC = cobj.prototype;
let classObj = cobj.classObjName;
try {
genFunctionHeaderPush(classObj,prototypeC,cobj.className);
//2. mapping argument
argList(cobj.argvtypes,cobj.argvnames);
mapping(cobj.argvtypes,cobj.argvnames);
transform(cobj.argvtypes);
classObjSetNativePtr(cobj);
methodsTable(cobj);
setProperties(cobj);
genFunctionTailPop();
} catch (e) {
// Catch and handle the error
console.error('Error:', e.message);
}
return;
}
function destroyinfoGenerator(cobj) { // put on top
let classObj = cobj.classObjName;
outputFileMessage(`${' '.repeat(level * 4)}void ${classObj}_free_callback(void* native_p, jerry_object_native_info_t *info_p);`);
outputFileMessage(`${' '.repeat(level * 4)}const static jerry_object_native_info_t ${classObj}_info = {`);
pushblock(`${' '.repeat(level * 4)}};`);
outputFileMessage(`${' '.repeat(level * 4)}.free_cb = ${classObj}_free_callback`);
popblock();
}
function destroyFreeCBGenerator(cobj) { // put before constructor
let className = cobj.className;
let classObj = cobj.classObjName;
outputFileMessage(`${' '.repeat(level * 4)}/* ~${className} ${classObj} destroy */`);
outputFileMessage(`${' '.repeat(level * 4)}void ${classObj}_free_callback(void* native_p, jerry_object_native_info_t *info_p){`);
pushblock(`${' '.repeat(level * 4)}};`);
outputFileMessage(`${' '.repeat(level * 4)}WSDEBUG_TPRINTF("[${className}] delete %x\\n",native_p);`);
outputFileMessage(`${' '.repeat(level * 4)}${className}* ${classObj} = (${className}*)native_p;`);
outputFileMessage(`${' '.repeat(level * 4)}/** **TODO** free your own resource here **/`);
// if (!jerry_value_is_undefined(onReceive_cb_func))
// jerry_value_free(onReceive_cb_func);
// if (!jerry_value_is_undefined(onRequest_cb_func))
// jerry_value_free(onRequest_cb_func);
outputFileMessage(`${' '.repeat(level * 4)}delete(${classObj});`);
popblock();
}
function registerGenerator(cobj) {
let className = cobj.className;
let classObj = cobj.classObjName;
outputFileMessage(`${' '.repeat(level * 4)}bool js_${classObj}_classobj_wrapper(){ `);
outputFileMessage(`${' '.repeat(level * 4)}//1 a)modified func name and b) define in .h c) call by jswwrap_tc`);
pushblock(`${' '.repeat(level * 4)}};`);
outputFileMessage(`${' '.repeat(level * 4)}return jerryx_register_global ("${className}", js_${classObj}_${className});`);
// outputFileMessage(`${' '.repeat(level * 4)}return true;`);
popblock();
}
function LibdefHeaderGeneratorPush(cobj) {
let className = cobj.className;
resetblock();
outputFileMessage(`#include "jswrap_tc.h"`);
outputFileMessage(`#ifdef _LANG_JERRYSCRIPT_ `);
pushblock(`#endif // _LANG_JERRYSCRIPT_ Congraturation Done!`); level--; // non level shift
outputFileMessage(`#ifdef _LIB_${className.toUpperCase()}_`);
pushblock(`#endif //_LIB_${className.toUpperCase()}_`); level--; // non level shift
outputFileMessage(`/* **HOW 1** simple select copy & paste **/`);
outputFileMessage(`/* **HOW 2** or using process.argv[2] for output file, then dl file**/`);
outputFileMessage(`/* **WARNNING** if tab position is wrong, means error found**/`);
outputFileMessage(`/* **TODO** Include your class declaration here **/`);
outputFileMessage(`#include "${className}.h"`);
}
function LibdefTailGeneratorPop() {
popblock(); //#endif //_LIB_${className.toUpperCase()}_
popblock(); //#endif // _LANG_JERRYSCRIPT_
}
function classObjSetNativePtr(cobj){
let className = cobj.className;
let classObj = cobj.classObjName;
let argvnames = cobj.argvnames;
let argvtypes = cobj.argvtypes;
let callmehtod = callClassObjMethodArgs(className,argvnames,argvtypes);
outputFileMessage(`${' '.repeat(level * 4)}${className}* ${classObj} = new ${callmehtod}; //4`);
outputFileMessage(`${' '.repeat(level * 4)}WSDEBUG_TPRINTF("[${className}] new %x\\n",${classObj});`);
outputFileMessage(`${' '.repeat(level * 4)}jerry_value_t js_${classObj}obj = jerry_object();`);
outputFileMessage(`${' '.repeat(level * 4)}jerry_object_set_native_ptr(js_${classObj}obj, &${classObj}_info , ${classObj} );`);
}
function methodsTable(cobj){
let className = cobj.className;
let classObj = cobj.classObjName;
outputFileMessage(`${' '.repeat(level * 4)}// Register initialization function`);
outputFileMessage(`${' '.repeat(level * 4)}jerryx_property_entry props[] ={ //5 methods`);
pushblock(`${' '.repeat(level * 4)}};`);
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_PROPERTY_STRING_SZ ("id", "${className}"),`);
cobj.methods.forEach((element) => {
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_PROPERTY_FUNCTION ("${element}", js_${classObj}_${element}),`);
});
outputFileMessage(`${' '.repeat(level * 4)}JERRYX_PROPERTY_LIST_END(),`);
popblock();
}
function setProperties(cobj){
let classObj = cobj.classObjName;
outputFileMessage(`${' '.repeat(level * 4)}jerryx_register_result reg = jerryx_set_properties (js_${classObj}obj, props);`);
outputFileMessage(`${' '.repeat(level * 4)}if (jerry_value_is_exception (reg.result)){`);
pushblock(`${' '.repeat(level * 4)}};`);
outputFileMessage(`${' '.repeat(level * 4)}WSDEBUG_TPRINTF("Only registered %d properties\\r\\n", reg.registered);`);
outputFileMessage(`${' '.repeat(level * 4)}/* clean up not registered property values */`);
outputFileMessage(`${' '.repeat(level * 4)}jerryx_release_property_entry (props, reg);`);
outputFileMessage(`${' '.repeat(level * 4)}jerry_value_free (reg.result);`);
outputFileMessage(`${' '.repeat(level * 4)}return jerry_undefined();`);
outputFileMessage(`${' '.repeat(level * 4)}/* clean up the error */`);
popblock();
outputFileMessage(`${' '.repeat(level * 4)}return js_${classObj}obj;`);
}