Libraryless. Click here for Pure Java version (2928L/19K).
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) {
|
26 | new structure_Data d; |
27 | d.out = out; |
28 | structure_go(o, d); |
29 | } |
30 | |
31 | // leave to false, unless unstructure() breaks |
32 | static boolean structure_allowShortening = false; |
33 | |
34 | // info on how to serialize objects of a certain class |
35 | sclass structure_ClassInfo {
|
36 | L<Field> fields; |
37 | Method customSerializer; |
38 | bool special, nullInstances; |
39 | } |
40 | |
41 | sclass structure_Data {
|
42 | PrintWriter out; |
43 | int stringSizeLimit; |
44 | int shareStringsLongerThan = 20; |
45 | bool noStringSharing; |
46 | |
47 | new IdentityHashMap<O, Integer> seen; |
48 | //new BitSet refd; |
49 | new HashMap<S, Int> strings; |
50 | new HashSet<S> concepts; |
51 | HashMap<Class, structure_ClassInfo> infoByClass = new HashMap; |
52 | new HashMap<Class, Field> persistenceInfo; |
53 | int n; // token count |
54 | new L<Runnable> stack; |
55 | |
56 | // append single token |
57 | structure_Data append(S token) { out.print(token); ++n; ret this; }
|
58 | structure_Data append(int i) { out.print(i); ++n; ret this; }
|
59 | |
60 | // append multiple tokens |
61 | structure_Data append(S token, int tokCount) { out.print(token); n += tokCount; ret this; }
|
62 | |
63 | // extend last token |
64 | structure_Data app(S token) { out.print(token); ret this; }
|
65 | structure_Data app(int i) { out.print(i); ret this; }
|
66 | } |
67 | |
68 | static void structure_1(final Object o, final structure_Data d) ctex {
|
69 | if (o == null) { d.append("null"); ret; }
|
70 | |
71 | Class c = o.getClass(); |
72 | bool concept = false; |
73 | ifclass Concept |
74 | concept = o instanceof Concept; |
75 | endif |
76 | structure_ClassInfo info = d.infoByClass.get(c); |
77 | if (info == null) {
|
78 | d.infoByClass.put(c, info = new structure_ClassInfo); |
79 | if ((info.customSerializer = findMethodNamed(c, '_serialize)) |
80 | != null) info.special = true; |
81 | } |
82 | |
83 | L<Field> lFields = info.fields; |
84 | if (lFields == null) {
|
85 | // these are never back-referenced (for readability) |
86 | |
87 | if (o instanceof Number) {
|
88 | PrintWriter out = d.out; |
89 | if (o instanceof Integer) { int i = ((Int) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; ret; }
|
90 | if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; ret; }
|
91 | if (o cast Short) { short s = o.shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; ret; }
|
92 | if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); ret; }
|
93 | if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); ret; }
|
94 | if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; ret; }
|
95 | } |
96 | |
97 | if (o instanceof Boolean) {
|
98 | d.append(((Boolean) o).booleanValue() ? "t" : "f"); ret; |
99 | } |
100 | |
101 | if (o instanceof Character) {
|
102 | d.append(quoteCharacter((Character) o)); ret; |
103 | } |
104 | |
105 | if (o instanceof File) {
|
106 | d.append("File ").append(quote(((File) o).getPath())); ret;
|
107 | } |
108 | |
109 | // referencable objects follow |
110 | |
111 | Int ref = d.seen.get(o); |
112 | if (o instanceof S && ref == null) ref = d.strings.get((S) o); |
113 | if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); ret; }
|
114 | |
115 | if (!o instanceof S) |
116 | d.seen.put(o, d.n); // record token number |
117 | else {
|
118 | S s = d.stringSizeLimit != 0 ? shorten((S) o, d.stringSizeLimit) : (S) o; |
119 | if (!d.noStringSharing) {
|
120 | if (d.shareStringsLongerThan == Int.MAX_VALUE) |
121 | d.seen.put(o, d.n); |
122 | if (l(s) >= d.shareStringsLongerThan) |
123 | d.strings.put(s, d.n); |
124 | } |
125 | quoteToPrintWriter(s, d.out); d.n++; ret; |
126 | } |
127 | |
128 | if (o cast Set) {
|
129 | /*O set2 = unwrapSynchronizedSet(o); |
130 | if (set2 != o) {
|
131 | d.append("sync");
|
132 | o = set2; |
133 | } TODO */ |
134 | |
135 | if (o instanceof TreeSet) {
|
136 | d.append(isCISet_gen(o) ? "ciset" : "treeset"); |
137 | structure_1(new ArrayList(o), d); |
138 | ret; |
139 | } |
140 | |
141 | // assume it's a HashSet or LinkedHashSet |
142 | d.append(o instanceof LinkedHashSet ? "lhs" : "hashset"); |
143 | structure_1(new ArrayList(o), d); |
144 | ret; |
145 | } |
146 | |
147 | S name = c.getName(); |
148 | |
149 | if (o instanceof Collection |
150 | && !startsWith(name, "main$") |
151 | /* && neq(name, "main$Concept$RefL") */) {
|
152 | |
153 | // it's a list |
154 | |
155 | if (name.equals("java.util.Collections$SynchronizedList")
|
156 | || name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
|
157 | if (unwrapSynchronizedList(o/List) instanceof LinkedList) |
158 | d.append("syncLL");
|
159 | else |
160 | d.append("sync");
|
161 | } |
162 | else if (name.equals("java.util.LinkedList")) d.append("ll");
|
163 | d.append("[");
|
164 | final int l = d.n; |
165 | final Iterator it = ((Collection) o).iterator(); |
166 | d.stack.add(r {
|
167 | if (!it.hasNext()) |
168 | d.append("]");
|
169 | else {
|
170 | d.stack.add(this); |
171 | if (d.n != l) d.append(", ");
|
172 | structure_1(it.next(), d); |
173 | } |
174 | }); |
175 | ret; |
176 | } |
177 | |
178 | if (o instanceof Map && !startsWith(name, "main$")) {
|
179 | if (o instanceof LinkedHashMap) d.append("lhm");
|
180 | else if (o instanceof HashMap) d.append("hm");
|
181 | else if (o cast TreeMap) |
182 | d.append(isCIMap_gen(o) ? "cimap" : "tm"); |
183 | else if (name.equals("java.util.Collections$SynchronizedMap")) d.append("sync");
|
184 | else if (name.equals("java.util.Collections$SynchronizedSortedMap")) { d.append("sync tm", 2); }
|
185 | |
186 | d.append("{");
|
187 | final int l = d.n; |
188 | final Iterator it = ((Map) o).entrySet().iterator(); |
189 | |
190 | d.stack.add(new Runnable() {
|
191 | bool v; |
192 | Map.Entry e; |
193 | |
194 | public void run() {
|
195 | if (v) {
|
196 | d.append("=");
|
197 | v = false; |
198 | d.stack.add(this); |
199 | structure_1(e.getValue(), d); |
200 | } else {
|
201 | if (!it.hasNext()) |
202 | d.append("}");
|
203 | else {
|
204 | e = (Map.Entry) it.next(); |
205 | v = true; |
206 | d.stack.add(this); |
207 | if (d.n != l) d.append(", ");
|
208 | structure_1(e.getKey(), d); |
209 | } |
210 | } |
211 | } |
212 | }); |
213 | ret; |
214 | } |
215 | |
216 | if (c.isArray()) {
|
217 | if (o instanceof byte[]) {
|
218 | d.append("ba ").append(quote(bytesToHex((byte[]) o))); ret;
|
219 | } |
220 | |
221 | final int n = Array.getLength(o); |
222 | |
223 | if (o instanceof bool[]) {
|
224 | S hex = boolArrayToHex((bool[]) o); |
225 | int i = l(hex); |
226 | while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2; |
227 | d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); ret;
|
228 | } |
229 | |
230 | S atype = "array", sep = ", "; |
231 | |
232 | if (o instanceof int[]) {
|
233 | //ret "intarray " + quote(intArrayToHex((int[]) o)); |
234 | atype = "intarray"; |
235 | sep = " "; |
236 | } |
237 | |
238 | d.append(atype).append("{");
|
239 | d.stack.add(new Runnable() {
|
240 | int i; |
241 | public void run() {
|
242 | if (i >= n) |
243 | d.append("}");
|
244 | else {
|
245 | d.stack.add(this); |
246 | if (i > 0) d.append(", ");
|
247 | structure_1(Array.get(o, i++), d); |
248 | } |
249 | } |
250 | }); |
251 | ret; |
252 | } |
253 | |
254 | if (o instanceof Class) {
|
255 | d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); ret;
|
256 | } |
257 | |
258 | if (o instanceof Throwable) {
|
259 | d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); ret;
|
260 | } |
261 | |
262 | if (o instanceof BitSet) {
|
263 | BitSet bs = (BitSet) o; |
264 | d.append("bitset{", 2);
|
265 | int l = d.n; |
266 | for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
|
267 | if (d.n != l) d.append(", ");
|
268 | d.append(i); |
269 | } |
270 | d.append("}"); ret;
|
271 | } |
272 | |
273 | // Need more cases? This should cover all library classes... |
274 | if (name.startsWith("java.") || name.startsWith("javax.")) {
|
275 | d.append("j ").append(quote(str(o))); ret; // Hm. this is not unstructure-able
|
276 | } |
277 | |
278 | ifclass Lisp |
279 | if (o instanceof Lisp) {
|
280 | d.append("l(", 2);
|
281 | final Lisp lisp = cast o; |
282 | structure_1(lisp.head, d); |
283 | final Iterator it = lisp.args == null ? emptyIterator() : lisp.args.iterator(); |
284 | d.stack.add(r {
|
285 | if (!it.hasNext()) |
286 | d.append(")");
|
287 | else {
|
288 | d.stack.add(this); |
289 | d.append(", ");
|
290 | structure_1(it.next(), d); |
291 | } |
292 | }); |
293 | ret; |
294 | } |
295 | endif |
296 | |
297 | /*if (name.equals("main$Lisp")) {
|
298 | fail("lisp not supported right now");
|
299 | }*/ |
300 | |
301 | if (info.special) {
|
302 | if (info.customSerializer != null) {
|
303 | // custom serialization (_serialize method) |
304 | O o2 = invokeMethod(info.customSerializer, o); |
305 | d.append("cu ");
|
306 | S shortName = dropPrefix("main$", name);
|
307 | d.append(shortName); |
308 | d.out.append(' ');
|
309 | structure_1(o2, d); |
310 | ret; |
311 | } else |
312 | if (info.nullInstances) ret with d.append("null");
|
313 | else fail("unknown special type");
|
314 | } |
315 | |
316 | S dynName = shortDynamicClassName(o); |
317 | if (concept && !d.concepts.contains(dynName)) {
|
318 | d.concepts.add(dynName); |
319 | d.append("c ");
|
320 | } |
321 | |
322 | // serialize an object with fields. |
323 | // first, collect all fields and values in fv. |
324 | |
325 | TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() {
|
326 | public int compare(Field a, Field b) {
|
327 | ret stdcompare(a.getName(), b.getName()); |
328 | } |
329 | }); |
330 | |
331 | Class cc = c; |
332 | while (cc != Object.class) {
|
333 | for (Field field : getDeclaredFields_cached(cc)) {
|
334 | S fieldName = field.getName(); |
335 | if (fieldName.equals("_persistenceInfo"))
|
336 | d.persistenceInfo.put(c, field); |
337 | if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) |
338 | continue; |
339 | |
340 | fields.add(field); |
341 | |
342 | // put special cases here...? |
343 | } |
344 | |
345 | cc = cc.getSuperclass(); |
346 | } |
347 | |
348 | // TODO: S fieldOrder = getOpt(c, "_fieldOrder"); |
349 | lFields = asList(fields); |
350 | |
351 | // Render this$1 first because unstructure needs it for constructor call. |
352 | |
353 | int n = l(lFields); |
354 | for (int i = 0; i < n; i++) {
|
355 | Field f = lFields.get(i); |
356 | if (f.getName().equals("this$1")) {
|
357 | lFields.remove(i); |
358 | lFields.add(0, f); |
359 | break; |
360 | } |
361 | } |
362 | |
363 | ifdef structure_debug |
364 | print("Saving fields for " + c + ": " + lFields);
|
365 | endifdef |
366 | info.fields = lFields; |
367 | } // << if (lFields == null) |
368 | else { // ref handling for lFields != null
|
369 | Int ref = d.seen.get(o); |
370 | if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); ret; }
|
371 | d.seen.put(o, d.n); // record token number |
372 | } |
373 | |
374 | Field persistenceInfoField = cast d.persistenceInfo.get(c); |
375 | Map<S, O> persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o); |
376 | ifdef structure_debug |
377 | print("persistenceInfo for " + c + ": " + persistenceInfo);
|
378 | endifdef |
379 | new LinkedHashMap<S, O> fv; |
380 | for (Field f : lFields) {
|
381 | Object value; |
382 | try {
|
383 | value = f.get(o); |
384 | } catch (Exception e) {
|
385 | value = "?"; |
386 | } |
387 | |
388 | if (value != null && (persistenceInfo == null |
389 | || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) |
390 | fv.put(f.getName(), value); |
391 | ifdef structure_debug |
392 | else print("Skipping null field " + f.getName() + " for " + identityHashCode(o));
|
393 | endifdef |
394 | } |
395 | |
396 | S name = c.getName(); |
397 | String shortName = dropPrefix("main$", name);
|
398 | if (startsWithDigit(shortName)) shortName = name; // for anonymous classes |
399 | |
400 | // Now we have fields & values. Process fieldValues if it's a DynamicObject. |
401 | |
402 | // omit field "className" if equal to class's name |
403 | if (concept && eq(fv.get("className"), shortName))
|
404 | fv.remove("className");
|
405 | |
406 | if (o instanceof DynamicObject) {
|
407 | putAll(fv, (Map) fv.get("fieldValues"));
|
408 | fv.remove("fieldValues");
|
409 | shortName = shortDynamicClassName(o); |
410 | fv.remove("className");
|
411 | } |
412 | |
413 | S singleField = fv.size() == 1 ? first(fv.keySet()) : null; |
414 | |
415 | d.append(shortName); |
416 | d.n += countDots(shortName)*2; // correct token count |
417 | ifdef structure_debug |
418 | print("Fields for " + shortName + ": " + fv.keySet());
|
419 | endifdef |
420 | |
421 | final int l = d.n; |
422 | final Iterator it = fv.entrySet().iterator(); |
423 | |
424 | d.stack.add(r {
|
425 | if (!it.hasNext()) {
|
426 | if (d.n != l) |
427 | d.append(")");
|
428 | } else {
|
429 | Map.Entry e = (Map.Entry) it.next(); |
430 | d.append(d.n == l ? "(" : ", ");
|
431 | d.append((S) e.getKey()).append("=");
|
432 | d.stack.add(this); |
433 | structure_1(e.getValue(), d); |
434 | } |
435 | }); |
436 | } |
Began life as a copy of #1009411
download show line numbers debug dex old transpilations
Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt
No comments. add comment
| Snippet ID: | #1024864 |
| Snippet name: | structure function (v16, custom serialisation) |
| Eternal ID of this version: | #1024864/14 |
| Text MD5: | 66bccfd9cbf06fcb7b7042694bf7f5bd |
| Transpilation MD5: | f5a6e694ba8a9b4809aa5818628cb454 |
| Author: | stefan |
| Category: | javax |
| Type: | JavaX fragment (include) |
| Public (visible to everyone): | Yes |
| Archived (hidden from active list): | No |
| Created/modified: | 2019-09-29 16:09:26 |
| Source code size: | 13454 bytes / 436 lines |
| Pitched / IR pitched: | No / No |
| Views / Downloads: | 459 / 709 |
| Version history: | 13 change(s) |
| Referenced in: | [show references] |