Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

407
LINES

< > BotCompany Repo | #1009411 // structure function (v14, new list+map serializing)

JavaX fragment (include) [tags: use-pretranspiled]

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

Author comment

Began life as a copy of #1008806

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1009411
Snippet name: structure function (v14, new list+map serializing)
Eternal ID of this version: #1009411/55
Text MD5: 62949110e5c50a43ab64fb19caba977b
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-08-27 22:20:22
Source code size: 12560 bytes / 407 lines
Pitched / IR pitched: No / No
Views / Downloads: 675 / 876
Version history: 54 change(s)
Referenced in: [show references]