1 /*
   2  * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package jdk.vm.ci.meta;
  24 
  25 /**
  26  * Miscellaneous collection of utility methods used by {@code jdk.vm.ci.meta} and its clients.
  27  */
  28 public class MetaUtil {
  29 
  30     /**
  31      * Extends the functionality of {@link Class#getSimpleName()} to include a non-empty string for
  32      * anonymous and local classes.
  33      *
  34      * @param clazz the class for which the simple name is being requested
  35      * @param withEnclosingClass specifies if the returned name should be qualified with the name(s)
  36      *            of the enclosing class/classes of {@code clazz} (if any). This option is ignored
  37      *            if {@code clazz} denotes an anonymous or local class.
  38      * @return the simple name
  39      */
  40     public static String getSimpleName(Class<?> clazz, boolean withEnclosingClass) {
  41         final String simpleName = clazz.getSimpleName();
  42         if (simpleName.length() != 0) {
  43             if (withEnclosingClass) {
  44                 String prefix = "";
  45                 Class<?> enclosingClass = clazz;
  46                 while ((enclosingClass = enclosingClass.getEnclosingClass()) != null) {
  47                     prefix = enclosingClass.getSimpleName() + "." + prefix;
  48                 }
  49                 return prefix + simpleName;
  50             }
  51             return simpleName;
  52         }
  53         // Must be an anonymous or local class
  54         final String name = clazz.getName();
  55         int index = name.indexOf('$');
  56         if (index == -1) {
  57             return name;
  58         }
  59         index = name.lastIndexOf('.', index);
  60         if (index == -1) {
  61             return name;
  62         }
  63         return name.substring(index + 1);
  64     }
  65 
  66     /**
  67      * Converts a type name in internal form to an external form.
  68      *
  69      * @param name the internal name to convert
  70      * @param qualified whether the returned name should be qualified with the package name
  71      * @param classForNameCompatible specifies if the returned name for array types should be in
  72      *            {@link Class#forName(String)} format (e.g., {@code "[Ljava.lang.Object;"},
  73      *            {@code "[[I"}) or in Java source code format (e.g., {@code "java.lang.Object[]"},
  74      *            {@code "int[][]"} ).
  75      */
  76     public static String internalNameToJava(String name, boolean qualified, boolean classForNameCompatible) {
  77         switch (name.charAt(0)) {
  78             case 'L': {
  79                 String result = name.substring(1, name.length() - 1).replace('/', '.');
  80                 if (!qualified) {
  81                     final int lastDot = result.lastIndexOf('.');
  82                     if (lastDot != -1) {
  83                         result = result.substring(lastDot + 1);
  84                     }
  85                 }
  86                 return result;
  87             }
  88             case '[':
  89                 return classForNameCompatible ? name.replace('/', '.') : internalNameToJava(name.substring(1), qualified, classForNameCompatible) + "[]";
  90             default:
  91                 if (name.length() != 1) {
  92                     throw new IllegalArgumentException("Illegal internal name: " + name);
  93                 }
  94                 return JavaKind.fromPrimitiveOrVoidTypeChar(name.charAt(0)).getJavaName();
  95         }
  96     }
  97 
  98     /**
  99      * Convenient shortcut for calling
 100      * {@link #appendLocation(StringBuilder, ResolvedJavaMethod, int)} without having to supply a
 101      * {@link StringBuilder} instance and convert the result to a string.
 102      */
 103     public static String toLocation(ResolvedJavaMethod method, int bci) {
 104         return appendLocation(new StringBuilder(), method, bci).toString();
 105     }
 106 
 107     /**
 108      * Appends a string representation of a location specified by a given method and bci to a given
 109      * {@link StringBuilder}. If a stack trace element with a non-null file name and non-negative
 110      * line number is {@linkplain ResolvedJavaMethod#asStackTraceElement(int) available} for the
 111      * given method, then the string returned is the {@link StackTraceElement#toString()} value of
 112      * the stack trace element, suffixed by the bci location. For example:
 113      *
 114      * <pre>
 115      *     java.lang.String.valueOf(String.java:2930) [bci: 12]
 116      * </pre>
 117      *
 118      * Otherwise, the string returned is the value of applying {@link JavaMethod#format(String)}
 119      * with the format string {@code "%H.%n(%p)"}, suffixed by the bci location. For example:
 120      *
 121      * <pre>
 122      *     java.lang.String.valueOf(int) [bci: 12]
 123      * </pre>
 124      *
 125      * @param sb
 126      * @param method
 127      * @param bci
 128      */
 129     public static StringBuilder appendLocation(StringBuilder sb, ResolvedJavaMethod method, int bci) {
 130         if (method != null) {
 131             StackTraceElement ste = method.asStackTraceElement(bci);
 132             if (ste.getFileName() != null && ste.getLineNumber() > 0) {
 133                 sb.append(ste);
 134             } else {
 135                 sb.append(method.format("%H.%n(%p)"));
 136             }
 137         } else {
 138             sb.append("Null method");
 139         }
 140         return sb.append(" [bci: ").append(bci).append(']');
 141     }
 142 
 143     static void appendProfile(StringBuilder buf, AbstractJavaProfile<?, ?> profile, int bci, String type, String sep) {
 144         if (profile != null) {
 145             AbstractProfiledItem<?>[] pitems = profile.getItems();
 146             if (pitems != null) {
 147                 buf.append(String.format("%s@%d:", type, bci));
 148                 for (int j = 0; j < pitems.length; j++) {
 149                     AbstractProfiledItem<?> pitem = pitems[j];
 150                     buf.append(String.format(" %.6f (%s)%s", pitem.getProbability(), pitem.getItem(), sep));
 151                 }
 152                 if (profile.getNotRecordedProbability() != 0) {
 153                     buf.append(String.format(" %.6f <other %s>%s", profile.getNotRecordedProbability(), type, sep));
 154                 } else {
 155                     buf.append(String.format(" <no other %s>%s", type, sep));
 156                 }
 157             }
 158         }
 159     }
 160 
 161     /**
 162      * Converts a Java source-language class name into the internal form.
 163      *
 164      * @param className the class name
 165      * @return the internal name form of the class name
 166      */
 167     public static String toInternalName(String className) {
 168         if (className.startsWith("[")) {
 169             /* Already in the correct array style. */
 170             return className.replace('.', '/');
 171         }
 172 
 173         StringBuilder result = new StringBuilder();
 174         String base = className;
 175         while (base.endsWith("[]")) {
 176             result.append("[");
 177             base = base.substring(0, base.length() - 2);
 178         }
 179 
 180         switch (base) {
 181             case "boolean":
 182                 result.append("Z");
 183                 break;
 184             case "byte":
 185                 result.append("B");
 186                 break;
 187             case "short":
 188                 result.append("S");
 189                 break;
 190             case "char":
 191                 result.append("C");
 192                 break;
 193             case "int":
 194                 result.append("I");
 195                 break;
 196             case "float":
 197                 result.append("F");
 198                 break;
 199             case "long":
 200                 result.append("J");
 201                 break;
 202             case "double":
 203                 result.append("D");
 204                 break;
 205             case "void":
 206                 result.append("V");
 207                 break;
 208             default:
 209                 result.append("L").append(base.replace('.', '/')).append(";");
 210                 break;
 211         }
 212         return result.toString();
 213     }
 214 
 215     /**
 216      * Gets a string representation of an object based soley on its class and its
 217      * {@linkplain System#identityHashCode(Object) identity hash code}. This avoids and calls to
 218      * virtual methods on the object such as {@link Object#hashCode()}.
 219      */
 220     public static String identityHashCodeString(Object obj) {
 221         if (obj == null) {
 222             return "null";
 223         }
 224         return obj.getClass().getName() + "@" + System.identityHashCode(obj);
 225     }
 226 }