andytill / erlyberly

erlang tracing for the masses
https://twitter.com/erlyberlytips
GNU General Public License v3.0
694 stars 43 forks source link

Add support for Elixir Struct #141

Closed aboroska closed 7 years ago

aboroska commented 7 years ago

Elixir structs are Erlang maps with a special key: __struct__. The value of that key is the name of the Struct. This commit hides the metakey and displays the name of the Struct.

andytill commented 7 years ago

Showing metadata about structures is a great feature, and has the same syntax as elixir.

A structure under elixir and erlang display modes. I like that we can switch to erlang mode and view the raw terms.

elixir-struct-display

I made the changes in this diff to make checkstyle happy.

diff --git a/src/main/java/erlyberly/format/ElixirFormatter.java b/src/main/java/erlyberly/format/ElixirFormatter.java
index 41cd906..2e1d070 100644
--- a/src/main/java/erlyberly/format/ElixirFormatter.java
+++ b/src/main/java/erlyberly/format/ElixirFormatter.java
@@ -27,16 +27,14 @@ import com.ericsson.otp.erlang.OtpErlangString;
 import com.ericsson.otp.erlang.OtpErlangMap;
 import erlyberly.node.OtpUtil;

-import java.lang.reflect.Array;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Map;
 import java.util.Iterator;
 import java.nio.charset.StandardCharsets;

 public class ElixirFormatter implements TermFormatter {

-    private final String STRUCTKEY = "__struct__";
+    private static final String STRUCT_KEY = "__struct__";

     private String stripElixirPrefix(String str) {
         if (str.startsWith("\'Elixir.")) {
@@ -120,7 +118,7 @@ public class ElixirFormatter implements TermFormatter {
         }
         else if(obj instanceof OtpErlangMap) {
             OtpErlangMap map = (OtpErlangMap) obj;
-            OtpErlangAtom structNameKey = new OtpErlangAtom(STRUCTKEY);
+            OtpErlangAtom structNameKey = new OtpErlangAtom(STRUCT_KEY);
             if (map.get(structNameKey) != null) {
                 String structName = stripElixirPrefix(map.get(structNameKey).toString());
                 sb.append("%" + structName + "{");

Only comment is that the atom should be a static final field instead of the atom string.

aboroska commented 7 years ago

Thank you for the review! Updated the PR. Note, that struct support is still not perfect, I think it still has issues with nested structures/maps. Will fix that separately.