Transpiled version (6360L) is out of date.
1 | static bool structure_showTiming, structure_checkTokenCount; |
2 | |
3 | static S structure(O o) { |
4 | ret structure(o, new structure_Data); |
5 | } |
6 | |
7 | static S structure(O o, structure_Data d) { |
8 | new StringWriter sw; |
9 | d.out = new PrintWriter(sw); |
10 | structure_go(o, d); |
11 | S s = str(sw); |
12 | if (structure_checkTokenCount) { |
13 | print("token count=" + d.n); |
14 | assertEquals("token count", l(javaTokC(s)), d.n); |
15 | } |
16 | ret s; |
17 | } |
18 | |
19 | static void structure_go(O o, structure_Data d) { |
20 | structure_1(o, d); |
21 | while (nempty(d.stack)) |
22 | popLast(d.stack).run(); |
23 | } |
24 | |
25 | static void structureToPrintWriter(O o, PrintWriter out, structure_Data d default new) { |
26 | d.out = out; |
27 | structure_go(o, d); |
28 | } |
29 | |
30 | // leave to false, unless unstructure() breaks |
31 | static boolean structure_allowShortening = false; |
32 | |
33 | // info on how to serialize objects of a certain class |
34 | sclass structure_ClassInfo { |
35 | Class c; |
36 | L<Field> fields; |
37 | Method customSerializer; |
38 | IVF1<O> serializeObject; // can be set by caller of structure function |
39 | bool special; // various special classes |
40 | bool nullInstances; // serialize all instances as null (e.g. lambdas/anonymous classes) |
41 | } |
42 | |
43 | sclass structure_Data { |
44 | PrintWriter out; |
45 | int stringSizeLimit; |
46 | int shareStringsLongerThan = 20; |
47 | bool noStringSharing; |
48 | bool storeBaseClasses; |
49 | bool honorFieldOrder = true; |
50 | S mcDollar = actualMCDollar(); |
51 | |
52 | new IdentityHashMap<O, Integer> seen; |
53 | //new BitSet refd; |
54 | new HashMap<S, Int> strings; |
55 | new HashSet<S> concepts; |
56 | HashMap<Class, structure_ClassInfo> infoByClass = new HashMap; |
57 | new HashMap<Class, Field> persistenceInfo; |
58 | int n; // token count |
59 | new L<Runnable> stack; |
60 | |
61 | // append single token |
62 | structure_Data append(S token) { out.print(token); ++n; ret this; } |
63 | structure_Data append(int i) { out.print(i); ++n; ret this; } |
64 | |
65 | // append multiple tokens |
66 | structure_Data append(S token, int tokCount) { out.print(token); n += tokCount; ret this; } |
67 | |
68 | // extend last token |
69 | structure_Data app(S token) { out.print(token); ret this; } |
70 | structure_Data app(int i) { out.print(i); ret this; } |
71 | |
72 | structure_ClassInfo infoForClass(Class c) { |
73 | structure_ClassInfo info = infoByClass.get(c); |
74 | if (info == null) info = newClass(c); |
75 | ret info; |
76 | } |
77 | |
78 | // called when a new class is detected |
79 | // can be overridden by clients |
80 | structure_ClassInfo newClass(Class c) { |
81 | new structure_ClassInfo info; |
82 | info.c = c; |
83 | infoByClass.put(c, info); |
84 | |
85 | try { |
86 | if (isSyntheticOrAnonymous(c)) { |
87 | info.special = info.nullInstances = true; |
88 | ret info; |
89 | } |
90 | |
91 | if ((info.customSerializer = findMethodNamed(c, '_serialize)) |
92 | != null) info.special = true; |
93 | |
94 | if (storeBaseClasses) { |
95 | Class sup = c.getSuperclass(); |
96 | if (sup != O) { |
97 | append("bc "); |
98 | append(shortDynClassNameForStructure(c)); |
99 | out.print(" "); |
100 | append(shortDynClassNameForStructure(sup)); |
101 | out.print(" "); |
102 | infoForClass(sup); // transitively write out superclass relations |
103 | } |
104 | } |
105 | |
106 | if (!isPersistableClass(c)) |
107 | warn("Class not persistable: " + c + " (anonymous or no default constructor)"); |
108 | } catch print e { |
109 | info.nullInstances = true; |
110 | } |
111 | |
112 | ret info; |
113 | } |
114 | |
115 | void setFields(structure_ClassInfo info, L<Field> fields) { |
116 | info.fields = fields; |
117 | } |
118 | |
119 | void writeObject(O o, S shortName, MapSO fv) { |
120 | S singleField = fv.size() == 1 ? first(fv.keySet()) : null; |
121 | |
122 | append(shortName); |
123 | n += countDots(shortName)*2; // correct token count |
124 | ifdef structure_debug |
125 | print("Fields for " + shortName + ": " + fv.keySet()); |
126 | endifdef |
127 | |
128 | int l = n; |
129 | Iterator it = fv.entrySet().iterator(); |
130 | |
131 | stack.add(r { |
132 | if (!it.hasNext()) { |
133 | if (n != l) |
134 | append(")"); |
135 | } else { |
136 | Map.Entry e = (Map.Entry) it.next(); |
137 | append(n == l ? "(" : ", "); |
138 | append((S) e.getKey()).append("="); |
139 | stack.add(this); |
140 | structure_1(e.getValue(), structure_Data.this); |
141 | } |
142 | }); |
143 | } |
144 | } |
145 | |
146 | static void structure_1(final Object o, final structure_Data d) ctex { |
147 | if (o == null) { d.append("null"); ret; } |
148 | |
149 | Class c = o.getClass(); |
150 | bool concept = false; |
151 | ifclass Concept |
152 | concept = o instanceof Concept; |
153 | endif |
154 | structure_ClassInfo info = d.infoForClass(c); |
155 | |
156 | L<Field> lFields = info.fields; |
157 | if (lFields == null) { |
158 | // these are never back-referenced (for readability) |
159 | |
160 | if (o instanceof Number) { |
161 | PrintWriter out = d.out; |
162 | if (o instanceof Integer) { int i = ((Int) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; ret; } |
163 | if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; ret; } |
164 | if (o cast Short) { short s = o.shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; ret; } |
165 | if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); ret; } |
166 | if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); ret; } |
167 | if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; ret; } |
168 | } |
169 | |
170 | if (o instanceof Boolean) { |
171 | d.append(((Boolean) o).booleanValue() ? "t" : "f"); ret; |
172 | } |
173 | |
174 | if (o instanceof Character) { |
175 | d.append(quoteCharacter((Character) o)); ret; |
176 | } |
177 | |
178 | if (o instanceof File) { |
179 | d.append("File ").append(quote(((File) o).getPath())); ret; |
180 | } |
181 | |
182 | // referencable objects follow |
183 | |
184 | Int ref = d.seen.get(o); |
185 | if (o instanceof S && ref == null) ref = d.strings.get((S) o); |
186 | if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); ret; } |
187 | |
188 | if (!o instanceof S) |
189 | d.seen.put(o, d.n); // record token number |
190 | else { |
191 | S s = d.stringSizeLimit != 0 ? shorten((S) o, d.stringSizeLimit) : (S) o; |
192 | if (!d.noStringSharing) { |
193 | if (d.shareStringsLongerThan == Int.MAX_VALUE) |
194 | d.seen.put(o, d.n); |
195 | if (l(s) >= d.shareStringsLongerThan) |
196 | d.strings.put(s, d.n); |
197 | } |
198 | quoteToPrintWriter(s, d.out); d.n++; ret; |
199 | } |
200 | |
201 | if (o cast Set) { |
202 | /*O set2 = unwrapSynchronizedSet(o); |
203 | if (set2 != o) { |
204 | d.append("sync"); |
205 | o = set2; |
206 | } TODO */ |
207 | |
208 | if (o instanceof TreeSet) { |
209 | d.append(isCISet_gen(o) ? "ciset" : "treeset"); |
210 | structure_1(new ArrayList(o), d); |
211 | ret; |
212 | } |
213 | |
214 | // assume it's a HashSet or LinkedHashSet |
215 | d.append(o instanceof LinkedHashSet ? "lhs" : "hashset"); |
216 | structure_1(new ArrayList(o), d); |
217 | ret; |
218 | } |
219 | |
220 | S name = c.getName(); |
221 | |
222 | if (o instanceof Collection |
223 | && !isJavaXClassName(name) |
224 | /* && neq(name, "main$Concept$RefL") */) { |
225 | |
226 | // it's a list |
227 | |
228 | if (name.equals("java.util.Collections$SynchronizedList") |
229 | || name.equals("java.util.Collections$SynchronizedRandomAccessList")) { |
230 | d.append("sync "); |
231 | ret with structure_1(unwrapSynchronizedList(o/List), d); |
232 | } |
233 | else if (name.equals("java.util.LinkedList")) d.append("ll"); |
234 | d.append("["); |
235 | final int l = d.n; |
236 | final Iterator it = cloneList((Collection) o).iterator(); |
237 | d.stack.add(r { |
238 | if (!it.hasNext()) |
239 | d.append("]"); |
240 | else { |
241 | d.stack.add(this); |
242 | if (d.n != l) d.append(", "); |
243 | structure_1(it.next(), d); |
244 | } |
245 | }); |
246 | ret; |
247 | } |
248 | |
249 | ifdef OurSyncCollections |
250 | if (o cast SynchronizedMap) { |
251 | d.append("sync "); |
252 | ret with structure_1(o.m, d); |
253 | } |
254 | endifdef |
255 | |
256 | |
257 | if (o instanceof Map && !startsWith(name, d.mcDollar)) { |
258 | if (o instanceof LinkedHashMap) d.append("lhm"); |
259 | else if (o instanceof HashMap) d.append("hm"); |
260 | else if (o cast TreeMap) |
261 | d.append(isCIMap_gen(o) ? "cimap" : "tm"); |
262 | else if (name.equals("java.util.Collections$SynchronizedMap") |
263 | || name.equals("java.util.Collections$SynchronizedSortedMap") |
264 | || name.equals("java.util.Collections$SynchronizedNavigableMap")) { |
265 | d.append("sync "); |
266 | ret with structure_1(unwrapSynchronizedMap(o/Map), d); |
267 | } |
268 | |
269 | d.append("{"); |
270 | final int l = d.n; |
271 | final Iterator it = cloneMap((Map) o).entrySet().iterator(); |
272 | |
273 | d.stack.add(new Runnable() { |
274 | bool v; |
275 | Map.Entry e; |
276 | |
277 | public void run() { |
278 | if (v) { |
279 | d.append("="); |
280 | v = false; |
281 | d.stack.add(this); |
282 | structure_1(e.getValue(), d); |
283 | } else { |
284 | if (!it.hasNext()) |
285 | d.append("}"); |
286 | else { |
287 | e = (Map.Entry) it.next(); |
288 | v = true; |
289 | d.stack.add(this); |
290 | if (d.n != l) d.append(", "); |
291 | structure_1(e.getKey(), d); |
292 | } |
293 | } |
294 | } |
295 | }); |
296 | ret; |
297 | } |
298 | |
299 | if (c.isArray()) { |
300 | if (o instanceof byte[]) { |
301 | d.append("ba ").append(quote(bytesToHex((byte[]) o))); ret; |
302 | } |
303 | |
304 | final int n = Array.getLength(o); |
305 | |
306 | if (o instanceof bool[]) { |
307 | S hex = boolArrayToHex((bool[]) o); |
308 | int i = l(hex); |
309 | while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2; |
310 | d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); ret; |
311 | } |
312 | |
313 | S atype = "array"/*, sep = ", "*/; // sep is not used yet |
314 | |
315 | if (o instanceof int[]) { |
316 | //ret "intarray " + quote(intArrayToHex((int[]) o)); |
317 | atype = "intarray"; |
318 | //sep = " "; |
319 | } else if (o instanceof double[]) { |
320 | atype = "dblarray"; |
321 | //sep = " "; |
322 | } else { |
323 | Pair<Class, Int> p = arrayTypeAndDimensions(c); |
324 | if (p.a == int.class) atype = "intarray"; |
325 | else if (p.a == byte.class) atype = "bytearray"; |
326 | else if (p.a == bool.class) atype = "boolarray"; |
327 | else if (p.a == double.class) atype = "dblarray"; |
328 | else if (p.a == S) { atype = "array S"; d.n++; } |
329 | else atype = "array"; // fail("Unsupported array type: " + p.a); |
330 | if (p.b > 1) { |
331 | atype += "/" + p.b; // add number of dimensions |
332 | d.n += 2; // 2 additional tokens will be written |
333 | } |
334 | } |
335 | |
336 | d.append(atype).append("{"); |
337 | d.stack.add(new Runnable() { |
338 | int i; |
339 | public void run() { |
340 | if (i >= n) |
341 | d.append("}"); |
342 | else { |
343 | d.stack.add(this); |
344 | if (i > 0) d.append(", "); |
345 | structure_1(Array.get(o, i++), d); |
346 | } |
347 | } |
348 | }); |
349 | ret; |
350 | } |
351 | |
352 | if (o instanceof Class) { |
353 | d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); ret; |
354 | } |
355 | |
356 | if (o instanceof Throwable) { |
357 | d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); ret; |
358 | } |
359 | |
360 | if (o instanceof BitSet) { |
361 | BitSet bs = (BitSet) o; |
362 | d.append("bitset{", 2); |
363 | int l = d.n; |
364 | for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { |
365 | if (d.n != l) d.append(", "); |
366 | d.append(i); |
367 | } |
368 | d.append("}"); ret; |
369 | } |
370 | |
371 | // Need more cases? This should cover all library classes... |
372 | if (name.startsWith("java.") || name.startsWith("javax.")) { |
373 | d.append("j ").append(quote(str(o))); ret; // Hm. this is not unstructure-able |
374 | } |
375 | |
376 | ifclass Lisp |
377 | if (o instanceof Lisp) { |
378 | d.append("l(", 2); |
379 | final Lisp lisp = cast o; |
380 | structure_1(lisp.head, d); |
381 | final Iterator it = lisp.args == null ? emptyIterator() : lisp.args.iterator(); |
382 | d.stack.add(r { |
383 | if (!it.hasNext()) |
384 | d.append(")"); |
385 | else { |
386 | d.stack.add(this); |
387 | d.append(", "); |
388 | structure_1(it.next(), d); |
389 | } |
390 | }); |
391 | ret; |
392 | } |
393 | endif |
394 | |
395 | /*if (name.equals("main$Lisp")) { |
396 | fail("lisp not supported right now"); |
397 | }*/ |
398 | |
399 | if (info.special) { |
400 | if (info.customSerializer != null) { |
401 | // custom serialization (_serialize method) |
402 | O o2 = invokeMethod(info.customSerializer, o); |
403 | d.append("cu "); |
404 | S shortName = dropPrefix(d.mcDollar, name); |
405 | d.append(shortName); |
406 | d.out.append(' '); |
407 | structure_1(o2, d); |
408 | ret; |
409 | } else if (info.nullInstances) ret with d.append("null"); |
410 | else if (info.serializeObject != null) |
411 | ret with info.serializeObject.get(o); |
412 | else fail("unknown special type"); |
413 | } |
414 | |
415 | S dynName = shortDynClassNameForStructure(o); |
416 | if (concept && !d.concepts.contains(dynName)) { |
417 | d.concepts.add(dynName); |
418 | d.append("c "); |
419 | } |
420 | |
421 | // serialize an object with fields. |
422 | // first, collect all fields and values in fv. |
423 | |
424 | TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() { |
425 | public int compare(Field a, Field b) { |
426 | ret stdcompare(a.getName(), b.getName()); |
427 | } |
428 | }); |
429 | |
430 | Class cc = c; |
431 | while (cc != Object.class) { |
432 | for (Field field : getDeclaredFields_cached(cc)) { |
433 | S fieldName = field.getName(); |
434 | if (fieldName.equals("_persistenceInfo")) |
435 | d.persistenceInfo.put(c, field); |
436 | if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) |
437 | continue; |
438 | |
439 | fields.add(field); |
440 | |
441 | // put special cases here...? |
442 | } |
443 | |
444 | cc = cc.getSuperclass(); |
445 | } |
446 | |
447 | lFields = asList(d.honorFieldOrder ? fieldObjectsInFieldOrder(c, fields) : fields); |
448 | |
449 | // Render this$0/this$1 first because unstructure needs it for constructor call. |
450 | |
451 | int n = l(lFields); |
452 | for (int i = 0; i < n; i++) { |
453 | Field f = lFields.get(i); |
454 | if (f.getName().startsWith("this$")) { |
455 | lFields.remove(i); |
456 | lFields.add(0, f); |
457 | break; |
458 | } |
459 | } |
460 | |
461 | ifdef structure_debug |
462 | print("Saving fields for " + c + ": " + lFields); |
463 | endifdef |
464 | d.setFields(info, lFields); |
465 | } // << if (lFields == null) |
466 | else { // ref handling for lFields != null |
467 | Int ref = d.seen.get(o); |
468 | if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); ret; } |
469 | d.seen.put(o, d.n); // record token number |
470 | } |
471 | |
472 | // get _persistenceInfo from field and/or dynamic field |
473 | Field persistenceInfoField = cast d.persistenceInfo.get(c); |
474 | MapSO persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o); |
475 | |
476 | if (persistenceInfoField == null && o instanceof DynamicObject) |
477 | persistenceInfo = (MapSO) getOptDynOnly(o/DynamicObject, "_persistenceInfo"); |
478 | |
479 | ifdef structure_debug |
480 | print("persistenceInfo for " + c + ": " + persistenceInfo); |
481 | endifdef |
482 | new LinkedHashMap<S, O> fv; |
483 | for (Field f : lFields) { |
484 | Object value; |
485 | try { |
486 | value = f.get(o); |
487 | } catch (Exception e) { |
488 | value = "?"; |
489 | } |
490 | |
491 | if (value != null && (persistenceInfo == null |
492 | || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) |
493 | fv.put(f.getName(), value); |
494 | ifdef structure_debug |
495 | else print("Skipping null field " + f.getName() + " for " + identityHashCode(o)); |
496 | endifdef |
497 | } |
498 | |
499 | S name = c.getName(); |
500 | S shortName = dropPrefix("loadableUtils.utils$", dropPrefix(d.mcDollar, name)); |
501 | if (startsWithDigit(shortName)) shortName = name; // for anonymous classes |
502 | |
503 | // Now we have fields & values. Process fieldValues if it's a DynamicObject. |
504 | |
505 | // omit field "className" if equal to class's name |
506 | if (concept && eq(fv.get("className"), shortName)) |
507 | fv.remove("className"); |
508 | |
509 | if (o cast DynamicObject) { |
510 | putAll(fv, (Map) fv.get("fieldValues")); |
511 | fv.remove("fieldValues"); |
512 | if (o.className != null) { |
513 | // TODO: this probably doesn't work with inner classes |
514 | shortName = shortDynClassNameForStructure(o); |
515 | fv.remove("className"); |
516 | } |
517 | } |
518 | |
519 | d.writeObject(o, shortName, fv); |
520 | } |
Began life as a copy of #1030701
download show line numbers debug dex old transpilations
Travelled to 5 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt
No comments. add comment
Snippet ID: | #1030944 |
Snippet name: | structure function (v19, storing class relationships) |
Eternal ID of this version: | #1030944/44 |
Text MD5: | bf67b4e0c0bc8f9568daad1540c34635 |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2022-02-19 08:04:40 |
Source code size: | 16438 bytes / 520 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 355 / 636 |
Version history: | 43 change(s) |
Referenced in: | [show references] |