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

314
LINES

< > BotCompany Repo | #1005374 // structure function (v7, using one buffer, outdated)

JavaX fragment (include)

sbool structure_showTiming;

static String structure(Object o) {
  new HashSet refd;
  new StringBuilder out;
  structure_1(out, o, new structure_Data(refd));
  long time = now();
  S s = str(out);
  out = null;
  s = structure_2(s, refd);
  if (structure_showTiming) done_always("structure_2", time);
  ret s;
}

// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;

static int structure_shareStringsLongerThan = 20;

static class structure_Data {
  int stringSizeLimit;
  new IdentityHashMap<O, Integer> seen;
  HashSet<Integer> refd;
  new HashMap<S, Int> strings;
  new HashSet<S> concepts;
  Class conceptClass = findClass("Concept");
  
  *(HashSet<Int> *refd) {}
}

static void structure_1(StringBuilder out, Object o, structure_Data d) {
  if (o == null) { out.append("null"); ret; }
  
  // these are never back-referenced (for readability)
  
  if (o instanceof BigInteger) {
    out.append("bigint(").append(o).append(")"); ret;
  }
  
  if (o instanceof Double) {
    out.append("d(").append(quote(str(o))).append(")"); ret;
  }
    
  if (o instanceof Float) {
    out.append("fl ").append(quote(str(o))); ret;
  }
    
  if (o instanceof Long) {
    out.append(o).append("L"); ret;
  }
  
  if (o instanceof Integer) {
    out.append(str(o)); ret;
  }
    
  if (o instanceof Boolean) {
    out.append(((Boolean) o).booleanValue() ? "t" : "f"); ret;
  }
    
  if (o instanceof Character) {
    out.append(quoteCharacter((Character) o)); ret;
  }
    
  if (o instanceof File) {
    out.append("File ").append(quote(((File) o).getPath())); ret;
  }
    
  // referencable objects follow
  
  Integer ref = null;
  if (!(o instanceof S)) {
    ref = d.seen.get(o);
    if (ref != null) {
      d.refd.add(ref);
      out.append("r").append(ref); ret;
    }
  }
  
  if (o instanceof S && (ref = d.strings.get((S) o)) != null) {
    d.refd.add(ref);
    out.append("r").append(ref); ret;
  }
  
  ref = d.seen.size()+1;
  d.seen.put(o, ref);
  out.append("m").append(ref).append(" "); // marker

  if (o instanceof S) {
    S s = d.stringSizeLimit != 0 ? shorten((S) o, d.stringSizeLimit) : (S) o;
    if (l(s) >= structure_shareStringsLongerThan)
      d.strings.put(s, ref);
    out.append(quote(s)); ret;
  }
    
  if (o instanceof HashSet) {
    out.append("hashset ");
    structure_1(out, new ArrayList((Set) o), d);
    ret;
  }

  if (o instanceof TreeSet) {
    out.append("treeset ");
    structure_1(out, new ArrayList((Set) o), d);
    ret;
  }
  
  Class c = o.getClass();
  String name = c.getName();
  
  if (o instanceof Collection && neq(name, "main$Concept$RefL")) {
    out.append("[");
    int l = out.length();
    for (Object x : (Collection) o) {
      if (out.length() != l) out.append(", ");
      structure_1(out, x, d);
    }
    out.append("]");
    ret;
  }
  
  if (o instanceof Map) {
    if (o instanceof HashMap) out.append("hm");
    out.append("{");
    int l = out.length();
    for (Object e : ((Map) o).entrySet()) {
      if (out.length() != l) out.append(", ");
      structure_1(out, ((Map.Entry) e).getKey(), d);
      out.append("=");
      structure_1(out, ((Map.Entry) e).getValue(), d);
    }
    out.append("}");
    ret;
  }
  
  if (c.isArray()) {
    if (o instanceof byte[]) {
      out.append("ba ").append(quote(bytesToHex((byte[]) o))); ret;
    }

    int n = Array.getLength(o);

    if (o instanceof bool[]) {
      S hex = boolArrayToHex((bool[]) o);
      int i = l(hex);
      while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
      out.append("boolarray ").append(n).append(" ").append(quote(substring(hex, 0, i))); ret;
    }
    
    S atype = "array", sep = ", ";

    if (o instanceof int[]) {
      //ret "intarray " + quote(intArrayToHex((int[]) o));
      atype = "intarray";
      sep = " ";
    }
    
    out.append(atype).append("{");
    for (int i = 0; i < n; i++) {
      if (i != 0) out.append(sep);
      structure_1(out, Array.get(o, i), d);
    }
    out.append("}"); ret;
  }

  if (o instanceof Class) {
    out.append("class(").append(quote(((Class) o).getName())).append(")"); ret;
  }
    
  if (o instanceof Throwable) {
    out.append("exception(").append(quote(((Throwable) o).getMessage())).append(")"); ret;
  }
    
  if (o instanceof BitSet) {
    BitSet bs = (BitSet) o;
    out.append("bitset{");
    int l = out.length();
    for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
      if (out.length() != l) out.append(", ");
      out.append(i);
    }
    out.append("}"); ret;
  }
    
  // Need more cases? This should cover all library classes...
  if (name.startsWith("java.") || name.startsWith("javax.")) {
    out.append(str(o)); ret;
  }
    
  if (name.equals("main$Lisp")) {
    out.append("l(");
    structure_1(out, getOpt(o, "head"), d);
    L args = cast getOpt(o, "args");
    if (nempty(args))
      for (int i = 0; i < l(args); i++) {
        out.append(", ");
        O arg = args.get(i);
        
        // sweet shortening
        if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty")))
          arg = get(arg, "head");
          
        structure_1(out, arg, d);
      }
    out.append(")"); ret;
  }
  
  bool concept = d.conceptClass != null && d.conceptClass.isInstance(o);
  S dynName = shortDynamicClassName(o);
  if (concept && !d.concepts.contains(dynName)) {
    d.concepts.add(dynName);
    out.append("c ");
  }
  
  // serialize an object with fields.
  // first, collect all fields and values in fv.
  
  String shortName = dropPrefix("main$", name);
  
  new TreeMap<S, O> fv;
  while (c != Object.class) {
    for (Field field : getDeclaredFields_cached(c)) {
      if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
        continue;
      S fieldName = field.getName();
      
      Object value;
      try {
        value = field.get(o);
      } catch (Exception e) {
        value = "?";
      }
      
      // omit field "className" if equal to class's name
      if (concept && eq(fieldName, "className")
        && eq(value, shortName)) value = null;
      
      // put special cases here...
      
      if (value != null)
        fv.put(fieldName, value);
    }
    c = c.getSuperclass();
  }
  
  // Now we have fields & values. Process fieldValues if it's a DynamicObject.
  
  if (o instanceof DynamicObject) {
    fv.putAll((Map) fv.get("fieldValues"));
    fv.remove("fieldValues");
    shortName = dynName;
    fv.remove("className");
  }
  
  S singleField = fv.size() == 1 ? first(fv.keySet()) : null;
  
  // Render this$1 first because unstructure needs it for constructor call.
  
  out.append(shortName).append("(");
  int l = out.length();
  
  if (fv.containsKey("this$1")) {
    out.append("this$1=");
    structure_1(out, fv.get("this$1"), d);
    fv.remove("this$1");
  }
  
  // Render the other fields.

  for (S fieldName : fv.keySet()) {
    if (out.length() != l) out.append(", ");
    out.append(fieldName).append("=");
    structure_1(out, fv.get(fieldName), d);
  }

  /*if (structure_allowShortening && singleField != null)
    b = b.replaceAll("^" + singleField + "=", ""); // drop field name if only one*/
    
  if (out.length() == l) out.setLength(l-1); // drop "("
  else out.append(")");
}

// drop unused markers
static S structure_2(final S s, final HashSet<Integer> refd) {
  final new StringBuilder out;
  
  javaTok_streaming(s, new JavaTok_Stream {
    int n = -1;
    bool drop;
    
    void add(int i, int j) {
      ++n;
      if ((n & 1) != 0 && s.charAt(i) == 'm') {
        S t;
        try {
          t = s.substring(i+1, j);
        } catch e {
          print("i=" + i + ", j=" + j);
          ret;
        }
        if (isInteger(t)
          && !refd.contains(parseInt(t))) {
          drop = true;
          ret;
        }
      }
      if (drop)
        drop = false;
      else
        out.append(s, i, j);
    }
  });
  
  ret str(out);
}

Author comment

Began life as a copy of #1003037

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1005374
Snippet name: structure function (v7, using one buffer, outdated)
Eternal ID of this version: #1005374/1
Text MD5: 6c72c3a2ea31a17cc76cc2f09b78bc0a
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-11-28 20:47:16
Source code size: 8306 bytes / 314 lines
Pitched / IR pitched: No / No
Views / Downloads: 596 / 610
Referenced in: [show references]