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

441
LINES

< > BotCompany Repo | #1024876 // structure function (v17, better sync maps)

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

Transpiled version (3340L) 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  
// 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  
      && !isJavaXClassName(name)
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  
        d.append("sync ");
158  
        ret with structure_1(unwrapSynchronizedList(o/List), d);
159  
      }
160  
      else if (name.equals("java.util.LinkedList")) d.append("ll");
161  
      d.append("[");
162  
      final int l = d.n;
163  
      final Iterator it = ((Collection) o).iterator();
164  
      d.stack.add(r {
165  
        if (!it.hasNext())
166  
          d.append("]");
167  
        else {
168  
          d.stack.add(this);
169  
          if (d.n != l) d.append(", ");
170  
          structure_1(it.next(), d);
171  
        }
172  
      });
173  
      ret;
174  
    }
175  
    
176  
    if (o instanceof Map && !startsWith(name, "main$")) {
177  
      if (o instanceof LinkedHashMap) d.append("lhm");
178  
      else if (o instanceof HashMap) d.append("hm");
179  
      else if (o cast TreeMap)
180  
        d.append(isCIMap_gen(o) ? "cimap" : "tm");
181  
      else if (name.equals("java.util.Collections$SynchronizedMap")
182  
        || name.equals("java.util.Collections$SynchronizedSortedMap")
183  
        || name.equals("java.util.Collections$SynchronizedNavigableMap")) {
184  
        d.append("sync "); 
185  
        ret with structure_1(unwrapSynchronizedMap(o/Map), d);
186  
      }
187  
      
188  
      d.append("{");
189  
      final int l = d.n;
190  
      final Iterator it = ((Map) o).entrySet().iterator();
191  
      
192  
      d.stack.add(new Runnable() {
193  
        bool v;
194  
        Map.Entry e;
195  
        
196  
        public void run() {
197  
          if (v) {
198  
            d.append("=");
199  
            v = false;
200  
            d.stack.add(this);
201  
            structure_1(e.getValue(), d);
202  
          } else {
203  
            if (!it.hasNext())
204  
              d.append("}");
205  
            else {
206  
              e = (Map.Entry) it.next();
207  
              v = true;
208  
              d.stack.add(this);
209  
              if (d.n != l) d.append(", ");
210  
              structure_1(e.getKey(), d);
211  
            }
212  
          }
213  
        }
214  
      });
215  
      ret;
216  
    }
217  
    
218  
    if (c.isArray()) {
219  
      if (o instanceof byte[]) {
220  
        d.append("ba ").append(quote(bytesToHex((byte[]) o))); ret;
221  
      }
222  
  
223  
      final int n = Array.getLength(o);
224  
  
225  
      if (o instanceof bool[]) {
226  
        S hex = boolArrayToHex((bool[]) o);
227  
        int i = l(hex);
228  
        while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
229  
        d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); ret;
230  
      }
231  
      
232  
      S atype = "array"/*, sep = ", "*/; // sep is not used yet
233  
  
234  
      if (o instanceof int[]) {
235  
        //ret "intarray " + quote(intArrayToHex((int[]) o));
236  
        atype = "intarray";
237  
        //sep = " ";
238  
      } else if (o instanceof double[]) {
239  
        atype = "dblarray";
240  
        //sep = " ";
241  
      }
242  
      
243  
      d.append(atype).append("{");
244  
      d.stack.add(new Runnable() {
245  
        int i;
246  
        public void run() {
247  
          if (i >= n)
248  
            d.append("}");
249  
          else {
250  
            d.stack.add(this);
251  
            if (i > 0) d.append(", ");
252  
            structure_1(Array.get(o, i++), d);
253  
          }
254  
        }
255  
      });
256  
      ret;
257  
    }
258  
  
259  
    if (o instanceof Class) {
260  
      d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); ret;
261  
    }
262  
      
263  
    if (o instanceof Throwable) {
264  
      d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); ret;
265  
    }
266  
      
267  
    if (o instanceof BitSet) {
268  
      BitSet bs = (BitSet) o;
269  
      d.append("bitset{", 2);
270  
      int l = d.n;
271  
      for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
272  
        if (d.n != l) d.append(", ");
273  
        d.append(i);
274  
      }
275  
      d.append("}"); ret;
276  
    }
277  
      
278  
    // Need more cases? This should cover all library classes...
279  
    if (name.startsWith("java.") || name.startsWith("javax.")) {
280  
      d.append("j ").append(quote(str(o))); ret; // Hm. this is not unstructure-able
281  
    }
282  
    
283  
    ifclass Lisp
284  
      if (o instanceof Lisp) {
285  
        d.append("l(", 2);
286  
        final Lisp lisp = cast o;
287  
        structure_1(lisp.head, d);
288  
        final Iterator it = lisp.args == null ? emptyIterator() : lisp.args.iterator();
289  
        d.stack.add(r {
290  
          if (!it.hasNext())
291  
            d.append(")");
292  
          else {
293  
            d.stack.add(this);
294  
            d.append(", ");
295  
            structure_1(it.next(), d);
296  
          }
297  
        });
298  
        ret;
299  
      }
300  
    endif
301  
      
302  
    /*if (name.equals("main$Lisp")) {
303  
      fail("lisp not supported right now");
304  
    }*/
305  
    
306  
    if (info.special) {
307  
      if (info.customSerializer != null) {
308  
        // custom serialization (_serialize method)
309  
        O o2 = invokeMethod(info.customSerializer, o);
310  
        d.append("cu ");
311  
        S shortName = dropPrefix("main$", name);
312  
        d.append(shortName);
313  
        d.out.append(' ');
314  
        structure_1(o2, d);
315  
        ret;
316  
      } else
317  
        if (info.nullInstances) ret with d.append("null");
318  
      else fail("unknown special type");
319  
    }
320  
    
321  
    S dynName = shortDynamicClassName(o);
322  
    if (concept && !d.concepts.contains(dynName)) {
323  
      d.concepts.add(dynName);
324  
      d.append("c ");
325  
    }
326  
    
327  
    // serialize an object with fields.
328  
    // first, collect all fields and values in fv.
329  
    
330  
    TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() {
331  
      public int compare(Field a, Field b) {
332  
        ret stdcompare(a.getName(), b.getName());
333  
      }
334  
    });
335  
    
336  
    Class cc = c;
337  
    while (cc != Object.class) {
338  
      for (Field field : getDeclaredFields_cached(cc)) {
339  
        S fieldName = field.getName();
340  
        if (fieldName.equals("_persistenceInfo"))
341  
          d.persistenceInfo.put(c, field);
342  
        if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
343  
          continue;
344  
345  
        fields.add(field);
346  
        
347  
        // put special cases here...?
348  
      }
349  
        
350  
      cc = cc.getSuperclass();
351  
    }
352  
    
353  
    // TODO: S fieldOrder = getOpt(c, "_fieldOrder");
354  
    lFields = asList(fields);
355  
    
356  
    // Render this$1 first because unstructure needs it for constructor call.
357  
    
358  
    int n = l(lFields);
359  
    for (int i = 0; i < n; i++) {
360  
      Field f = lFields.get(i);
361  
      if (f.getName().equals("this$1")) {
362  
        lFields.remove(i);
363  
        lFields.add(0, f);
364  
        break;
365  
      }
366  
    }
367  
  
368  
    ifdef structure_debug
369  
      print("Saving fields for " + c + ": " + lFields);
370  
    endifdef
371  
    info.fields = lFields;
372  
  } // << if (lFields == null)
373  
  else { // ref handling for lFields != null
374  
    Int ref = d.seen.get(o);
375  
    if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); ret; }
376  
    d.seen.put(o, d.n); // record token number
377  
  }
378  
379  
  Field persistenceInfoField = cast d.persistenceInfo.get(c);
380  
  Map<S, O> persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
381  
  ifdef structure_debug
382  
    print("persistenceInfo for " + c + ": " + persistenceInfo);
383  
  endifdef
384  
  new LinkedHashMap<S, O> fv;
385  
  for (Field f : lFields) {
386  
    Object value;
387  
    try {
388  
      value = f.get(o);
389  
    } catch (Exception e) {
390  
      value = "?";
391  
    }
392  
      
393  
    if (value != null && (persistenceInfo == null
394  
      || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
395  
      fv.put(f.getName(), value);
396  
    ifdef structure_debug
397  
      else print("Skipping null field " + f.getName() + " for " + identityHashCode(o));
398  
    endifdef
399  
  }
400  
  
401  
  S name = c.getName();
402  
  String shortName = dropPrefix("main$", name); // TODO: drop loadableUtils also
403  
  if (startsWithDigit(shortName)) shortName = name; // for anonymous classes
404  
    
405  
  // Now we have fields & values. Process fieldValues if it's a DynamicObject.
406  
  
407  
  // omit field "className" if equal to class's name
408  
  if (concept && eq(fv.get("className"), shortName))
409  
    fv.remove("className");
410  
          
411  
  if (o instanceof DynamicObject) {
412  
    putAll(fv, (Map) fv.get("fieldValues"));
413  
    fv.remove("fieldValues");
414  
    shortName = shortDynamicClassName(o);
415  
    fv.remove("className");
416  
  }
417  
  
418  
  S singleField = fv.size() == 1 ? first(fv.keySet()) : null;
419  
  
420  
  d.append(shortName);
421  
  d.n += countDots(shortName)*2; // correct token count
422  
  ifdef structure_debug
423  
    print("Fields for " + shortName + ": " + fv.keySet());
424  
  endifdef
425  
  
426  
  final int l = d.n;
427  
  final Iterator it = fv.entrySet().iterator();
428  
  
429  
  d.stack.add(r {
430  
    if (!it.hasNext()) {
431  
      if (d.n != l)
432  
        d.append(")");
433  
    } else {
434  
      Map.Entry e = (Map.Entry) it.next();
435  
      d.append(d.n == l ? "(" : ", ");
436  
      d.append((S) e.getKey()).append("=");
437  
      d.stack.add(this);
438  
      structure_1(e.getValue(), d);
439  
    }
440  
  });
441  
}

Author comment

Began life as a copy of #1024864

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1024876
Snippet name: structure function (v17, better sync maps)
Eternal ID of this version: #1024876/11
Text MD5: 920c7ea89b49e78bb415212b5454efdc
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-03-16 15:16:07
Source code size: 13687 bytes / 441 lines
Pitched / IR pitched: No / No
Views / Downloads: 299 / 489
Version history: 10 change(s)
Referenced in: [show references]