-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson2crystal.js
204 lines (192 loc) · 4.43 KB
/
json2crystal.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
import dq from 'fast-deep-equal';
const crystallies = {
string: 'String',
boolean: 'Bool',
int: 'Int64',
float: 'Float64',
undefined: 'Nil'
};
const reserved = [
'abstract',
'do',
'if',
'nil?',
'select',
'union',
'alias',
'else',
'in',
'of',
'self',
'unless',
'as',
'elsif',
'include',
'out',
'sizeof',
'until',
'as?',
'end',
'instance_sizeof',
'pointerof',
'struct',
'verbatim',
'asm',
'ensure',
'is_a?',
'private',
'super',
'when',
'begin',
'enum',
'lib',
'protected',
'then',
'while',
'break',
'extend',
'macro',
'require',
'true',
'with',
'case',
'false',
'module',
'rescue',
'type',
'yield',
'class',
'for',
'next',
'responds_to?',
'typeof',
'def',
'fun',
'nil',
'return',
'uninitialized'
];
export default function (json, optimize = false) {
const entries = Object.entries(JSON.parse(json));
if (entries.length === 0) return '';
const struct = {};
function addStruct(obj) {
struct[obj.name] = obj.value;
}
handetypes(entries, addStruct);
let typedStruct = Object.entries(struct);
if (optimize) typedStruct = clean(typedStruct);
const res = [];
// Map used for reusing random variable names that match
const nameCache = new Map();
// Loop through all generated types and format them for Crystal
for (let i = 0; i < typedStruct.length; i++) {
const structArr = ['struct ' + typedStruct[i][0], '\tinclude JSON::Serializable\n'];
const body = Object.entries(typedStruct[i][1]);
for (let j = 0; j < body.length; j++) {
let variable = body[j][0];
let shouldNewLine = false;
if (!isVarSafe(variable)) {
structArr.push(`\t@[JSON::Field(key: ${JSON.stringify(variable)})]`);
// Reuse or generate new random variable name
variable =
'n_' +
(nameCache.has(variable)
? nameCache.get(variable)
: nameCache.set(variable, randomID()).get(variable));
shouldNewLine = true;
}
structArr.push(`\tproperty ${variable} : ${body[j][1]}${shouldNewLine ? '\n' : ''}`);
}
structArr.push('end');
res.push(structArr.join('\n'));
}
return res.join('\n');
}
function handetypes(ent, setter, t = false, rand = randomID()) {
let res = {};
for (let i = 0; i < ent.length; i++) {
res[ent[i][0]] = typeHandler(ent[i][1], setter);
}
setter({
name: (t ? 'T_' : 'O_') + rand,
value: res
});
}
// Detect and name the value type according to Crystal
function typeHandler(tp, setter) {
let type = typeof tp;
if (type === 'number') {
type = tp === parseInt(tp) ? 'int' : 'float';
type = crystallies[type.toLowerCase()];
} else if (type === 'object' && tp != null) {
const isArray = typeof tp.push === 'function';
const rand = randomID();
// Nested json
if (!isArray) {
handetypes(Object.entries(tp), setter, true, rand);
type = 'T_' + rand;
} else {
type = handleArray(tp, setter);
}
} else {
if (tp == null) type = 'undefined';
type = crystallies[type.toLowerCase()];
}
return type;
}
function handleArray(arr, setter) {
let types = [];
for (let i = 0; i < arr.length; i++) {
types.push(typeHandler(arr[i], setter));
}
types = [...new Set(types)];
types = types.join('|');
return 'Array(' + types + ')';
}
function isVarSafe(variable) {
return /^[a-z][a-zA-Z_0-9]*$/.test(variable) && !reserved.includes(variable.toLowerCase());
}
function randomID() {
// Not super random but random enough
return Math.round(new Date().valueOf() * Math.random()).toString(36);
}
// Go through all value types and if any of them match
// 100%, reuse.
function clean(ent) {
let tmp = ent.filter((x) => x);
const keys2replace = {};
for (let i = 0; i < tmp.length; i++) {
const structk2r = [];
for (let j = i + 1; j < tmp.length; j++) {
if (dq(tmp[i][1], tmp[j][1])) {
structk2r.push(tmp[j][0]);
delete tmp[j];
tmp = tmp.filter((x) => x);
}
}
if (structk2r.length > 0) keys2replace[tmp[i][0]] = structk2r;
}
const pp = Object.entries(keys2replace);
for (let i = 0; i < Object.keys(pp).length; i++) {
for (let j = 0; j < pp[i][1].length; j++) {
tmp = replaceStruct(tmp, pp[i][1][j], pp[i][0]);
}
}
// Recursive till input matches output (can't optimize more)
if (!dq(ent, tmp)) tmp = clean(tmp);
return tmp;
}
function replaceStruct(ent, key, replacement) {
const tmp = ent;
for (let i = 0; i < tmp.length; i++) {
Object.entries(tmp[i][1]).forEach((x) => {
if (x[1] === key) {
tmp[i][1][x[0]] = replacement;
} else if (x[1].includes(key)) {
tmp[i][1][x[0]] = x[1].replace(key, replacement);
}
});
}
return tmp;
}