forked from p2pderivatives/cfd-js-wasm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_json_map_class.ts
2195 lines (2052 loc) · 70.8 KB
/
generate_json_map_class.ts
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable require-jsdoc */
'use strict';
import fs from 'fs';
import path from 'path';
import {Project} from 'ts-morph';
// FIXME(k-matsuzawa): Consider splitting the file.
interface JsonObjectCommonType {
namespace: string | string[];
commonHeader: string;
}
interface ClassMapType {
[key: string]: DetailClassParameterType;
}
interface ClassParameterType {
name: string;
comment: string;
}
interface CollectMapDataResponse {
type: string;
comment: string;
}
interface DetailClassParameterType {
data: JsonMappingData;
childList: DetailParameterType[];
parentList: string[];
}
interface DetailParameterType {
param: ParameterType;
data: JsonMappingData;
}
interface ParameterType {
name: string;
type: string;
comment: string;
}
interface TsAppendFunctionData {
name: string;
parameters: ParameterType[];
returnType: string;
comment: string;
}
interface ReferenceClassInfo {
name: string;
references: Set<string>;
weight: number;
}
// ----------------------------------------------------------------------------
// debug log function
// ----------------------------------------------------------------------------
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let debugLog = function(...args: any | any[]) {
// do nothing
// console.log(...args);
};
// eslint-disable-next-line prefer-const
let requireOptionFunc = function(requireInfo: string) {
return requireInfo !== 'optional';
};
// ----------------------------------------------------------------------------
// json data class
// ----------------------------------------------------------------------------
class JsonMappingData {
name: string;
methodName: string;
variableName: string;
initValue: string | number | boolean;
className: string;
classComment: string;
childList: {[key: string]: JsonMappingData};
parent: null;
isOutputStruct: boolean;
isArray: boolean;
isObject: boolean;
isRequire: boolean;
comment: string;
type: string;
structType: string;
constructor(name: string, type: string, initValue: string | number | boolean,
className: string, isOutputStruct = true) {
this.name = name;
this.methodName = (() => {
const replacedMethodName = this.name.replace(/-/gi, '_');
return replacedMethodName.charAt(0).toUpperCase() +
replacedMethodName.slice(1);
})();
this.variableName = (() => {
const replacedVariableName = this.name.replace(/-/gi, '_');
return replacedVariableName.split(/(?=[A-Z])/).join('_').toLowerCase();
})();
this.type = type;
this.structType = `${type}Struct`;
this.setType(type);
this.initValue = initValue;
this.className = className;
this.childList = {};
this.parent = null;
this.isOutputStruct = isOutputStruct;
this.isArray = false;
this.isObject = false;
this.isRequire = false;
this.comment = '';
this.classComment = '';
// Reserved word support.
// TODO(k-matsuzawa): If the number increases, make a list.
if (this.variableName == 'asm') this.variableName = `${this.variableName}_`;
}
setType(type: string) {
this.type = type;
this.structType = `${type}Struct`;
if (type.startsWith('JsonValueVector')) {
const typeName = type.split('<')[1].split('>')[0];
this.structType = `std::vector<${typeName}>`;
} else if (type.startsWith('JsonObjectVector')) {
const typeName = type.split('<')[1].split(',')[0].split('>')[0];
this.structType = `std::vector<${typeName}Struct>`;
}
}
setRequired(requireInfo: string) {
this.isRequire = requireOptionFunc(requireInfo);
}
setComment(comment: string, hint: string) {
if (comment) {
this.comment = comment;
if (hint) {
this.comment = `${comment} (${hint})`;
}
}
}
setTypeStruct(type: string, structType: any) {
this.type = type;
this.structType = structType;
if (type.startsWith('JsonValueVector')) {
const typeName = type.split('<')[1].split('>')[0];
this.structType = `std::vector<${typeName}>`;
} else if (type.startsWith('JsonObjectVector')) {
const typeName = type.split('<')[1].split(',')[0].split('>')[0];
this.structType = `std::vector<${typeName}Struct>`;
}
}
join(data: JsonMappingData) {
const newList: {[key: string]: JsonMappingData} = {};
for (const key2 in this.childList) {
if (this.childList[key2]) {
newList[key2] = this.childList[key2];
}
}
for (const key1 in data.childList) {
if (data.childList[key1]) {
let exist = false;
for (const key2 in this.childList) {
if (key1 == key2) {
exist = true;
break;
}
}
if (exist) {
newList[key1] = data.childList[key1];
}
}
}
const obj = new JsonMappingData(
this.name, this.type, this.initValue, this.className);
obj.name = this.name;
obj.methodName = this.methodName;
obj.variableName = this.variableName;
obj.initValue = this.initValue;
obj.className = this.className;
obj.classComment = this.classComment;
obj.childList = newList;
obj.parent = this.parent;
obj.isOutputStruct = this.isOutputStruct;
obj.isArray = this.isArray;
obj.isObject = this.isObject;
obj.isRequire = this.isRequire;
obj.comment = this.comment;
obj.type = this.type;
obj.structType = this.structType;
return obj;
}
toString() {
const str = `[JsonMappingData] ${this.name}:${this.type}:${this.className}`;
// for debug code.
// for (const key in this.childList) {
// str += "\n - "
// str += this.childList[key].toString()
// }
return str;
}
collectMapData(map: ClassMapType, list: ClassParameterType[],
isRequest: boolean, parentInfo: JsonMappingData): CollectMapDataResponse {
if (this.type.startsWith('JsonValueVector') ||
this.type.startsWith('JsonObjectVector')) {
for (const key in this.childList) {
if (!{}.hasOwnProperty.call(this.childList, key)) continue;
if (this.childList[key]) {
const ret = this.childList[key].collectMapData(
map, list, isRequest, parentInfo);
const comment = ret['comment'] || this.comment;
return {
type: ret['type'] + '[]',
comment,
};
}
break;
}
throw Error('Illegal state.');
} else if (this.type === 'ErrorResponseBase') {
const clsName = 'ErrorResponse';
const props: DetailParameterType[] = [];
for (const key in this.childList) {
if (this.childList[key]) {
const name = this.childList[key].name + (this.childList[key].isRequire ? '' : '?');
const ret = this.childList[key].collectMapData(
map, list, isRequest, parentInfo);
const type = ret['type'];
const comment = ret['comment'];
if (name === 'isOutputStruct') {
continue;
}
props.push({
param: {name: name, type: type, comment},
data: this.childList[key],
});
}
}
map[clsName] = {data: this, childList: props, parentList: []};
list.push({name: clsName, comment: this.classComment});
return {
type: clsName,
comment: this.classComment,
};
} else if (Object.keys(this.childList).length > 0) {
// my class name
const props: DetailParameterType[] = [];
for (const key in this.childList) {
if (this.childList[key]) {
let name = this.childList[key].name + (this.childList[key].isRequire ? '' : '?');
const ret = this.childList[key].collectMapData(
map, list, isRequest, this);
debugLog('prop : ', ret);
const type = ret['type'];
const comment = ret['comment'];
if (name.indexOf('-') > 0) {
name = '\'' + name + '\'';
}
props.push({
param: {name: name, type: type, comment},
data: this.childList[key],
});
}
}
debugLog(`type = ${this.type}, comment = ${this.comment}`);
debugLog(`class = ${this.className}, clsComment = ${this.classComment}`);
debugLog('props = ', props);
if (map[this.type]) {
// property check
const appendProps = [];
const existDataProps = map[this.type].childList;
const removeProps: string[] = [];
for (const newProp of props) {
let exist = false;
const srcName = newProp.param.name.replace('?', '');
for (const prop of existDataProps) {
const dstName = prop.param.name.replace('?', '');
if (newProp.param.name == prop.param.name) {
if (newProp.data.isRequire != prop.data.isRequire) {
throw new Error(`unmatch require. caller:${this.type}, name=${prop.param.name} type=${prop.param.type},${newProp.param.type}`);
}
if (newProp.param.type != prop.param.type) {
if ((newProp.param.type.indexOf('bigint') >= 0) &&
(prop.param.type.indexOf('bigint') >= 0)) {
if (newProp.param.type == 'bigint') {
// removeProps.push(prop.param.name);
exist = true;
}
break;
}
throw new Error(`unmatch type. caller:${this.type}, name=${prop.param.name} type=${prop.param.type},${newProp.param.type}`);
}
exist = true;
break;
} else if (newProp.param.type == prop.param.type) {
if (srcName == dstName) {
throw new Error(`unmatch option. caller:${this.type}, name=${prop.param.name} type=${prop.param.type},${newProp.param.type}`);
}
} else if (srcName == dstName) {
throw new Error(`unmatch option. caller:${this.type}, name=${prop.param.name} type=${prop.param.type},${newProp.param.type}`);
}
}
if (!exist) appendProps.push(newProp);
}
if (appendProps) {
const newProps = (!removeProps) ? existDataProps :
existDataProps.filter(
(value: DetailParameterType) =>
(removeProps.indexOf(value.param.name) == -1));
const parentList = map[this.type].parentList;
if (parentInfo != null) {
parentList.push(parentInfo.type);
}
const joinData = map[this.type].data.join(this);
for (const prop of appendProps) {
newProps.push(prop);
}
map[this.type] = {
data: joinData, childList: newProps,
parentList: parentList,
};
}
} else {
let parentName = '';
if (parentInfo != null) parentName = parentInfo.type;
map[this.type] = {
data: this, childList: props, parentList: [parentName],
};
list.push({name: this.type, comment: this.classComment});
}
return {
type: this.type,
comment: this.comment || this.classComment,
};
} else {
let type = '';
if (this.type === 'std::string') {
type = 'string';
} else if (this.type === 'bool') {
type = 'boolean';
} else if ((this.type === 'int64_t') || (this.type === 'uint64_t')) {
type = (isRequest) ? 'bigint | number' : 'bigint';
} else {
type = 'number';
}
return {type: type, comment: this.comment};
}
}
getFunctionName() {
let result = '';
if (this.type.indexOf('Request') >= 0) {
result = this.type.substring(0, this.type.indexOf('Request'));
} else if (this.type.indexOf('Response') >= 0) {
result = this.type.substring(0, this.type.indexOf('Response'));
}
// ignore target
if (result === 'Error') {
return '';
}
return result;
}
}
// ----------------------------------------------------------------------------
// json data class
// ----------------------------------------------------------------------------
class JsonData {
filename: string;
inputJsonData: any;
requestData: JsonMappingData | null | undefined;
responseData: JsonMappingData | null | undefined;
constructor(filename: string, inputJsonData: any,
requestData: JsonMappingData | null | undefined,
responseData: JsonMappingData | null | undefined) {
this.filename = path.basename(filename).split('.').shift() || '';
this.inputJsonData = inputJsonData;
this.requestData = requestData;
this.responseData = responseData;
}
}
// interface ClassCache {
// cache: Map<string, JsonMappingData>;
// }
// ----------------------------------------------------------------------------
// array check function
// ----------------------------------------------------------------------------
function isArray(obj: any) {
return (obj instanceof Array);
// return Object.prototype.toString.call(obj) === '[object Array]';
}
// ----------------------------------------------------------------------------
// analyze function
// ----------------------------------------------------------------------------
function analyzeJson(jsonObj: any | any[],
objName = '', arrayType = '') {
debugLog(`analyzeJson obj=${objName}`);
let result: JsonMappingData;
if (typeof jsonObj == 'string') {
return new JsonMappingData(objName, 'std::string', jsonObj, '');
} else if (typeof jsonObj == 'number') {
return new JsonMappingData(objName, 'int64_t', jsonObj, '');
} else if (typeof jsonObj == 'boolean') {
return new JsonMappingData(objName, 'boolean', jsonObj, '');
} else if (jsonObj) {
const objKey = Object.keys(jsonObj);
const objValues = Object.values(jsonObj);
// if (objKey == 0) { // array
if (isArray(jsonObj)) {
debugLog(`read arr = ${objValues}`);
let pastType = '';
let firstMap: JsonMappingData | null = null;
for (const item in jsonObj) {
if (!{}.hasOwnProperty.call(jsonObj, item)) continue;
const tempChild = analyzeJson(jsonObj[item], objName);
if (!tempChild) {
// error
} else if (pastType == '') {
firstMap = tempChild;
pastType = tempChild.type;
} else if (pastType != tempChild.type) {
console.log('illegal list elements. fail.');
throw new Error('illegal list elements. fail.');
}
}
debugLog(`pastType = ${pastType}`);
if (pastType == '') {
// field and class name is set by the caller.
result = new JsonMappingData('', '', '', '');
} else {
if ((typeof objValues[0] == 'string') || (typeof objValues[0] == 'number') ||
(typeof objValues[0] == 'boolean')) {
// array of string or number.
if ((typeof objValues[0] == 'number') && (arrayType)) {
result = new JsonMappingData(objName, `JsonValueVector<${arrayType}>`, '', '');
if (firstMap !== null) firstMap.setType(arrayType);
} else {
result = new JsonMappingData(objName, `JsonValueVector<${pastType}>`, '', '');
}
} else {
// array of object
result = new JsonMappingData(objName, `JsonObjectVector<${pastType}, ${pastType}Struct>`, '', '');
}
}
if (firstMap !== null) {
result.childList[0] = firstMap;
}
result.isArray = true;
debugLog(`list_type = ${result.type}`);
debugLog(`childList_type = ${result.childList[0].type}`);
return result;
} else { // object
debugLog(`read keys = ${objKey}`);
let className = objName;
let classComment = '';
if (':class' in jsonObj) {
if (typeof jsonObj[':class'] === 'string') {
className = jsonObj[':class'];
debugLog(`read className = ${className}`);
}
}
if (':class:comment' in jsonObj) {
if (typeof jsonObj[':class:comment'] === 'string') {
classComment = jsonObj[':class:comment'];
debugLog(`read classComment = ${classComment}`);
}
}
let isOutputStruct = true;
if (':isOutputStruct' in jsonObj) {
if (typeof jsonObj[':isOutputStruct'] === 'boolean') {
isOutputStruct = jsonObj[':isOutputStruct'];
debugLog(`set ${className}, isOutputStruct=${isOutputStruct}`);
}
}
// Class name is set by the caller.
result = new JsonMappingData(objName, className, '', '', isOutputStruct);
result.isObject = true;
result.classComment = classComment;
// Stored in temporary map to maintain sort order.
const tmpMap: {[key: string]: JsonMappingData} = {};
const requireMap: {[key: string]: string} = {};
const clsCommentMap: {[key: string]: string} = {};
const commentMap: {[key: string]: string} = {};
const hintMap: {[key: string]: string} = {};
const arrayTypeMap: {[key: string]: string} = {};
for (const key in jsonObj) {
if (!{}.hasOwnProperty.call(jsonObj, key)) continue;
if ((key != ':class') && (key != ':class:comment')) {
if (key.lastIndexOf(':type') >= 0) {
const keyName = key.split(':')[0];
if (tmpMap[keyName]) {
tmpMap[keyName].setType(jsonObj[key]);
} else {
const data = new JsonMappingData(keyName, jsonObj[key], '', className, isOutputStruct);
data.classComment = classComment;
tmpMap[keyName] = data;
debugLog(`set JsonMappingData = ${keyName}`);
}
}
if (key.lastIndexOf(':require') >= 0) {
const keyName = key.split(':')[0];
requireMap[keyName] = jsonObj[key];
}
if (key.lastIndexOf(':arraytype') >= 0) {
const keyName = key.split(':')[0];
arrayTypeMap[keyName] = jsonObj[key];
}
if (key.lastIndexOf(':comment') >= 0) {
const keyName = key.split(':')[0];
commentMap[keyName] = jsonObj[key];
}
if (key.lastIndexOf(':hint') >= 0) {
const keyName = key.split(':')[0];
hintMap[keyName] = jsonObj[key];
}
} else {
if (key == ':class:comment') {
const tmpKeyName = jsonObj[':class'];
clsCommentMap[tmpKeyName] = jsonObj[key];
}
}
}
for (const key in jsonObj) {
if (!{}.hasOwnProperty.call(jsonObj, key)) continue;
if (key.indexOf(':') == -1) {
debugLog(`read key = ${key}`);
const value = jsonObj[key];
if (tmpMap[key]) {
result.childList[key] = tmpMap[key];
result.childList[key].initValue = value;
} else {
// type check
let typeStr = '';
if (typeof value == 'string') {
typeStr = 'std::string';
} else if (typeof value == 'number') {
typeStr = 'int64_t';
} else if (typeof value == 'boolean') {
typeStr = 'bool';
} else if (value) {
const objKey2 = Object.keys(value);
if ((typeof objKey2 === 'number') && (objKey2 == 0)) { // array
// Should I examine the element first?
typeStr = '';
} else { // object
typeStr = '';
}
}
result.childList[key] = new JsonMappingData(
key, typeStr, value, className);
}
// if (requireMap[key]) {
// result.childList[key].setRequired(requireMap[key]);
// }
result.childList[key].setRequired(requireMap[key]);
if (commentMap[key]) {
result.childList[key].setComment(commentMap[key], hintMap[key]);
}
const tempChild = analyzeJson(value, key, arrayTypeMap[key]);
if (tempChild) {
if (result.childList[key].type == '') {
result.childList[key].setTypeStruct(
tempChild.type, tempChild.structType);
if ((result.childList[key].type.indexOf('JsonObjectVector') >= 0) ||
(result.childList[key].type.indexOf('JsonValueVector') >= 0)) {
result.childList[key].isArray = true;
} else {
result.childList[key].isObject = true;
result.childList[key].classComment = tempChild.classComment;
}
}
result.childList[key].childList = tempChild.childList;
result.childList[key].className = className;
}
}
}
}
return result;
} else {
console.log('empty value.');
throw new Error('empty value.');
}
}
// ----------------------------------------------------------------------------
// analyze child class function
// ----------------------------------------------------------------------------
function getChildClasses(jsonMapData: JsonMappingData,
list: JsonMappingData[]) {
if (!jsonMapData) {
// do nothing
} else if (jsonMapData.isObject) {
for (const key in jsonMapData.childList) {
if (jsonMapData.childList[key]) {
if (jsonMapData.childList[key].isObject ||
jsonMapData.childList[key].isArray) {
getChildClasses(jsonMapData.childList[key], list);
}
}
}
list.push(jsonMapData);
} else if (jsonMapData.isArray) {
getChildClasses(jsonMapData.childList[0], list);
}
}
// ----------------------------------------------------------------------------
// generate cpp file source function
// ----------------------------------------------------------------------------
function generateFileSource(copyright: string, filename: string,
headerName: string | string[],
classList: any[], jsonSetting: JsonObjectCommonType | undefined) {
const result = [];
const namespace = (!jsonSetting) ? '' : jsonSetting.namespace;
const includeNolint = (headerName.indexOf('/') >= 0) ? '' : ' // NOLINT';
// header
const sourceFileHeader = `// ${copyright}
/**
* @file ${filename}
*
* @brief JSON mapping file (auto generate)
*/
#include <set>
#include <string>
#include <vector>
#include "${headerName}"${includeNolint}
`;
result.push(sourceFileHeader);
if (isArray(namespace)) {
for (let idx = 0; idx < namespace.length; ++idx) {
result.push(`namespace ${namespace[idx]} {`);
}
} else {
result.push(`namespace ${namespace} {`);
}
const sourceFileHeader2 = `
using cfd::core::JsonClassBase;
using cfd::core::JsonObjectVector;
using cfd::core::JsonValueVector;
using cfd::core::JsonVector;
// clang-format off
// @formatter:off\
`;
const sourceFileFooter = `
// @formatter:on
// clang-format on
`;
result.push(sourceFileHeader2);
if (classList) {
for (const data in classList) {
if (!{}.hasOwnProperty.call(classList, data)) continue;
result.push(classList[data]);
}
}
result.push(sourceFileFooter);
if (isArray(namespace)) {
for (let idx = namespace.length - 1; idx >= 0; --idx) {
result.push(`} // namespace ${namespace[idx]}`);
}
} else {
result.push(`} // namespace ${namespace}`);
}
result.push('');
return result.join('\n');
}
// ----------------------------------------------------------------------------
// generate cpp class source direct function
// ----------------------------------------------------------------------------
function generateClassSourceDirect(mapData: JsonMappingData,
responseList: string[] | undefined) {
const result = [];
const sourceClassHeader = `
// ------------------------------------------------------------------------
// ${mapData.type}
// ------------------------------------------------------------------------
cfd::core::JsonTableMap<${mapData.type}>
${mapData.type}::json_mapper;
std::vector<std::string> ${mapData.type}::item_list;
void ${mapData.type}::CollectFieldName() {
if (!json_mapper.empty()) {
return;
}
cfd::core::CLASS_FUNCTION_TABLE<${mapData.type}> func_table; // NOLINT
`;
result.push(sourceClassHeader);
for (const childKey in mapData.childList) {
if (!{}.hasOwnProperty.call(mapData.childList, childKey)) continue;
const childData = mapData.childList[childKey];
// start
const addJsonMapperComment = `\
func_table = {
${mapData.type}::Get${childData.methodName}String,
${mapData.type}::Set${childData.methodName}String,
${mapData.type}::Get${childData.methodName}FieldType,
};
json_mapper.emplace("${childData.name}", func_table);
item_list.push_back("${childData.name}");\
`;
// end
result.push(addJsonMapperComment);
}
result.push('}');
if (mapData.isOutputStruct) {
result.push('');
result.push(`void ${mapData.type}::ConvertFromStruct(`);
result.push(` const ${mapData.structType}& data) {`);
for (const childKey in mapData.childList) {
if (!{}.hasOwnProperty.call(mapData.childList, childKey)) continue;
const childData = mapData.childList[childKey];
if (childData.isObject || childData.isArray) {
const str = ` ${childData.variableName}_.ConvertFromStruct(data.${childData.variableName});`;
if (str.length > 80) {
result.push(` ${childData.variableName}_.ConvertFromStruct(`);
result.push(` data.${childData.variableName});`);
} else {
result.push(` ${childData.variableName}_.ConvertFromStruct(data.${childData.variableName});`);
}
} else {
result.push(` ${childData.variableName}_ = data.${childData.variableName};`);
}
}
result.push(` ignore_items = data.ignore_items;`);
result.push('}');
result.push('');
result.push(`${mapData.structType} ${mapData.type}::ConvertToStruct() const { // NOLINT`);
result.push(` ${mapData.structType} result;`);
for (const childKey in mapData.childList) {
if (!{}.hasOwnProperty.call(mapData.childList, childKey)) continue;
const childData = mapData.childList[childKey];
if (childData.isObject || childData.isArray) {
const str = ` result.${childData.variableName} = ${childData.variableName}_.ConvertToStruct();`;
if (str.length > 80) {
result.push(` result.${childData.variableName} = ${childData.variableName}_.ConvertToStruct(); // NOLINT`);
} else {
result.push(` result.${childData.variableName} = ${childData.variableName}_.ConvertToStruct();`);
}
} else {
result.push(` result.${childData.variableName} = ${childData.variableName}_;`);
}
}
result.push(` result.ignore_items = ignore_items;`);
result.push(' return result;');
result.push('}');
}
if (responseList) {
for (const str of result) {
responseList.push(str);
}
}
return result.join('\n');
}
// ----------------------------------------------------------------------------
// generate cpp class source function
// ----------------------------------------------------------------------------
function generateClassSource(req: JsonMappingData | null | undefined,
res: JsonMappingData | null | undefined,
outputList: Set<string>) {
const result: string[] = [];
if (req || res) {
const list: JsonMappingData[] = [];
if (req) list.push(req);
if (res) list.push(res);
for (const data of list) {
if (!data) continue;
// sort by class name
// for child elements
const mapList: JsonMappingData[] = [];
getChildClasses(data, mapList);
debugLog(`mapList = ${mapList}`);
for (const mapKey in mapList) {
if (!{}.hasOwnProperty.call(mapList, mapKey)) continue;
const mapData = mapList[mapKey];
if (outputList.has(mapData.type)) continue;
generateClassSourceDirect(mapData, result);
outputList.add(mapData.type);
}
}
}
return result.join('\n');
}
// ----------------------------------------------------------------------------
// generate class header function
// ----------------------------------------------------------------------------
function generateClassHeaderData(mapData: JsonMappingData,
exportDefine: string) {
const classHeader = `
// ------------------------------------------------------------------------
// ${mapData.type}
// ------------------------------------------------------------------------
/**
* @brief JSON-API (${mapData.type}) class
*/
class ${exportDefine}${mapData.type}
: public cfd::core::JsonClassBase<${mapData.type}> {
public:
${mapData.type}() {
CollectFieldName();
}
virtual ~${mapData.type}() {
// do nothing
}
/**
* @brief collect field name.
*/
static void CollectFieldName();
`;
return classHeader;
}
// ----------------------------------------------------------------------------
// generate object function by header
// ----------------------------------------------------------------------------
function generateObjectFunctionByHeader(mapData: JsonMappingData,
childData: JsonMappingData) {
// Rename method name because equals windows macro's function.
const methodName = (childData.methodName === 'KValue') ?
'K_Value' : childData.methodName;
const objectFunctions = `\
/**
* @brief Get of ${childData.name}.
* @return ${childData.name}
*/
${childData.type}& Get${methodName}() { // NOLINT
return ${childData.variableName}_;
}
/**
* @brief Set to ${childData.name}.
* @param[in] ${childData.variableName} setting value.
*/
void Set${methodName}( // line separate
const ${childData.type}& ${childData.variableName}) { // NOLINT
this->${childData.variableName}_ = ${childData.variableName};
}
/**
* @brief Get data type of ${childData.name}.
* @return Data type of ${childData.name}.
*/
static std::string Get${childData.methodName}FieldType() {
return "${childData.type}"; // NOLINT
}
/**
* @brief Get json string of ${childData.name} field.
* @param[in,out] obj class object
* @return JSON string.
*/
static std::string Get${childData.methodName}String( // line separate
const ${mapData.type}& obj) { // NOLINT
// Do not set to const, because substitution of member variables
// may occur in pre / post processing inside Serialize
return obj.${childData.variableName}_.Serialize();
}
/**
* @brief Set json object to ${childData.name} field.
* @param[in,out] obj class object
* @param[in] json_value JSON object
*/
static void Set${childData.methodName}String( // line separate
${mapData.type}& obj, // NOLINT
const UniValue& json_value) {
obj.${childData.variableName}_.DeserializeUniValue(json_value);
}
`;
return objectFunctions;
}
// ----------------------------------------------------------------------------
// generate value function by header
// ----------------------------------------------------------------------------
function generateValueFunctionByHeader(mapData: JsonMappingData,
childData: JsonMappingData) {
// Rename method name because equals windows macro's function.
const methodName = (childData.methodName === 'KValue') ?
'K_Value' : childData.methodName;
const valueFunctions = `\
/**
* @brief Get of ${childData.name}
* @return ${childData.name}
*/
${childData.type} Get${methodName}() const {
return ${childData.variableName}_;
}
/**
* @brief Set to ${childData.name}
* @param[in] ${childData.variableName} setting value.
*/
void Set${methodName}( // line separate
const ${childData.type}& ${childData.variableName}) { // NOLINT
this->${childData.variableName}_ = ${childData.variableName};
}
/**
* @brief Get data type of ${childData.name}
* @return Data type of ${childData.name}
*/
static std::string Get${childData.methodName}FieldType() {
return "${childData.type}";
}
/**
* @brief Get json string of ${childData.name} field.
* @param[in,out] obj class object.
* @return JSON string
*/
static std::string Get${childData.methodName}String( // line separate
const ${mapData.type}& obj) { // NOLINT
return cfd::core::ConvertToString(obj.${childData.variableName}_);
}
/**
* @brief Set json object to ${childData.name} field.
* @param[in,out] obj class object.
* @param[in] json_value JSON object.
*/
static void Set${childData.methodName}String( // line separate
${mapData.type}& obj, // NOLINT
const UniValue& json_value) {
cfd::core::ConvertFromUniValue( // line separate
obj.${childData.variableName}_, json_value);
}
`;
return valueFunctions;
}
// ----------------------------------------------------------------------------
// generate class field by header
// ----------------------------------------------------------------------------
function generateClassFieldByHeader(mapData: JsonMappingData) {
let structConvertFunction = '';
if (mapData.isOutputStruct) {
structConvertFunction = `\
/**
* @brief Convert struct to class.
* @param[in] data struct data.
*/
void ConvertFromStruct(
const ${mapData.structType}& data);
/**
* @brief Convert class to struct.
* @return struct data.
*/
${mapData.structType} ConvertToStruct() const;`;
}
const commonFields = `\
/**
* @brief Set ignore item.
* @param[in] key ignore target key name.
*/
void SetIgnoreItem(const std::string& key) {
ignore_items.insert(key);
}
${structConvertFunction}
protected:
/**
* @brief definition type of Map table.
*/
using ${mapData.type}MapTable =
cfd::core::JsonTableMap<${mapData.type}>;
/**
* @brief Get JSON mapping object.
* @return JSON mapping object.
* @see cfd::core::JsonClassBase::GetJsonMapper()