001// ASM: a very small and fast Java bytecode manipulation framework
002// Copyright (c) 2000-2011 INRIA, France Telecom
003// All rights reserved.
004//
005// Redistribution and use in source and binary forms, with or without
006// modification, are permitted provided that the following conditions
007// are met:
008// 1. Redistributions of source code must retain the above copyright
009//    notice, this list of conditions and the following disclaimer.
010// 2. Redistributions in binary form must reproduce the above copyright
011//    notice, this list of conditions and the following disclaimer in the
012//    documentation and/or other materials provided with the distribution.
013// 3. Neither the name of the copyright holders nor the names of its
014//    contributors may be used to endorse or promote products derived from
015//    this software without specific prior written permission.
016//
017// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
018// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
019// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
020// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
021// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
022// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
023// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
024// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
025// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
026// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
027// THE POSSIBILITY OF SUCH DAMAGE.
028package io.ebean.enhance.asm;
029
030import java.lang.reflect.Constructor;
031import java.lang.reflect.Method;
032
033/**
034 * A Java field or method type. This class can be used to make it easier to manipulate type and
035 * method descriptors.
036 *
037 * @author Eric Bruneton
038 * @author Chris Nokleberg
039 */
040public final class Type {
041
042  /** The sort of the {@code void} type. See {@link #getSort}. */
043  public static final int VOID = 0;
044
045  /** The sort of the {@code boolean} type. See {@link #getSort}. */
046  public static final int BOOLEAN = 1;
047
048  /** The sort of the {@code char} type. See {@link #getSort}. */
049  public static final int CHAR = 2;
050
051  /** The sort of the {@code byte} type. See {@link #getSort}. */
052  public static final int BYTE = 3;
053
054  /** The sort of the {@code short} type. See {@link #getSort}. */
055  public static final int SHORT = 4;
056
057  /** The sort of the {@code int} type. See {@link #getSort}. */
058  public static final int INT = 5;
059
060  /** The sort of the {@code float} type. See {@link #getSort}. */
061  public static final int FLOAT = 6;
062
063  /** The sort of the {@code long} type. See {@link #getSort}. */
064  public static final int LONG = 7;
065
066  /** The sort of the {@code double} type. See {@link #getSort}. */
067  public static final int DOUBLE = 8;
068
069  /** The sort of array reference types. See {@link #getSort}. */
070  public static final int ARRAY = 9;
071
072  /** The sort of object reference types. See {@link #getSort}. */
073  public static final int OBJECT = 10;
074
075  /** The sort of method types. See {@link #getSort}. */
076  public static final int METHOD = 11;
077
078  /** The (private) sort of object reference types represented with an internal name. */
079  private static final int INTERNAL = 12;
080
081  /** The descriptors of the primitive types. */
082  private static final String PRIMITIVE_DESCRIPTORS = "VZCBSIFJD";
083
084  /** The {@code void} type. */
085  public static final Type VOID_TYPE = new Type(VOID, PRIMITIVE_DESCRIPTORS, VOID, VOID + 1);
086
087  /** The {@code boolean} type. */
088  public static final Type BOOLEAN_TYPE =
089      new Type(BOOLEAN, PRIMITIVE_DESCRIPTORS, BOOLEAN, BOOLEAN + 1);
090
091  /** The {@code char} type. */
092  public static final Type CHAR_TYPE = new Type(CHAR, PRIMITIVE_DESCRIPTORS, CHAR, CHAR + 1);
093
094  /** The {@code byte} type. */
095  public static final Type BYTE_TYPE = new Type(BYTE, PRIMITIVE_DESCRIPTORS, BYTE, BYTE + 1);
096
097  /** The {@code short} type. */
098  public static final Type SHORT_TYPE = new Type(SHORT, PRIMITIVE_DESCRIPTORS, SHORT, SHORT + 1);
099
100  /** The {@code int} type. */
101  public static final Type INT_TYPE = new Type(INT, PRIMITIVE_DESCRIPTORS, INT, INT + 1);
102
103  /** The {@code float} type. */
104  public static final Type FLOAT_TYPE = new Type(FLOAT, PRIMITIVE_DESCRIPTORS, FLOAT, FLOAT + 1);
105
106  /** The {@code long} type. */
107  public static final Type LONG_TYPE = new Type(LONG, PRIMITIVE_DESCRIPTORS, LONG, LONG + 1);
108
109  /** The {@code double} type. */
110  public static final Type DOUBLE_TYPE =
111      new Type(DOUBLE, PRIMITIVE_DESCRIPTORS, DOUBLE, DOUBLE + 1);
112
113  // -----------------------------------------------------------------------------------------------
114  // Fields
115  // -----------------------------------------------------------------------------------------------
116
117  /**
118   * The sort of this type. Either {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE},
119   * {@link #SHORT}, {@link #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY},
120   * {@link #OBJECT}, {@link #METHOD} or {@link #INTERNAL}.
121   */
122  private final int sort;
123
124  /**
125   * A buffer containing the value of this field or method type. This value is an internal name for
126   * {@link #OBJECT} and {@link #INTERNAL} types, and a field or method descriptor in the other
127   * cases.
128   *
129   * <p>For {@link #OBJECT} types, this field also contains the descriptor: the characters in
130   * [{@link #valueBegin},{@link #valueEnd}) contain the internal name, and those in [{@link
131   * #valueBegin} - 1, {@link #valueEnd} + 1) contain the descriptor.
132   */
133  private final String valueBuffer;
134
135  /**
136   * The beginning index, inclusive, of the value of this Java field or method type in {@link
137   * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,
138   * and a field or method descriptor in the other cases.
139   */
140  private final int valueBegin;
141
142  /**
143   * The end index, exclusive, of the value of this Java field or method type in {@link
144   * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,
145   * and a field or method descriptor in the other cases.
146   */
147  private final int valueEnd;
148
149  /**
150   * Constructs a reference type.
151   *
152   * @param sort the sort of this type, see {@link #sort}.
153   * @param valueBuffer a buffer containing the value of this field or method type.
154   * @param valueBegin the beginning index, inclusive, of the value of this field or method type in
155   *     valueBuffer.
156   * @param valueEnd the end index, exclusive, of the value of this field or method type in
157   *     valueBuffer.
158   */
159  private Type(final int sort, final String valueBuffer, final int valueBegin, final int valueEnd) {
160    this.sort = sort;
161    this.valueBuffer = valueBuffer;
162    this.valueBegin = valueBegin;
163    this.valueEnd = valueEnd;
164  }
165
166  // -----------------------------------------------------------------------------------------------
167  // Methods to get Type(s) from a descriptor, a reflected Method or Constructor, other types, etc.
168  // -----------------------------------------------------------------------------------------------
169
170  /**
171   * Returns the {@link Type} corresponding to the given type descriptor.
172   *
173   * @param typeDescriptor a field or method type descriptor.
174   * @return the {@link Type} corresponding to the given type descriptor.
175   */
176  public static Type getType(final String typeDescriptor) {
177    return getTypeInternal(typeDescriptor, 0, typeDescriptor.length());
178  }
179
180  /**
181   * Returns the {@link Type} corresponding to the given class.
182   *
183   * @param clazz a class.
184   * @return the {@link Type} corresponding to the given class.
185   */
186  public static Type getType(final Class<?> clazz) {
187    if (clazz.isPrimitive()) {
188      if (clazz == Integer.TYPE) {
189        return INT_TYPE;
190      } else if (clazz == Void.TYPE) {
191        return VOID_TYPE;
192      } else if (clazz == Boolean.TYPE) {
193        return BOOLEAN_TYPE;
194      } else if (clazz == Byte.TYPE) {
195        return BYTE_TYPE;
196      } else if (clazz == Character.TYPE) {
197        return CHAR_TYPE;
198      } else if (clazz == Short.TYPE) {
199        return SHORT_TYPE;
200      } else if (clazz == Double.TYPE) {
201        return DOUBLE_TYPE;
202      } else if (clazz == Float.TYPE) {
203        return FLOAT_TYPE;
204      } else if (clazz == Long.TYPE) {
205        return LONG_TYPE;
206      } else {
207        throw new AssertionError();
208      }
209    } else {
210      return getType(getDescriptor(clazz));
211    }
212  }
213
214  /**
215   * Returns the method {@link Type} corresponding to the given constructor.
216   *
217   * @param constructor a {@link Constructor} object.
218   * @return the method {@link Type} corresponding to the given constructor.
219   */
220  public static Type getType(final Constructor<?> constructor) {
221    return getType(getConstructorDescriptor(constructor));
222  }
223
224  /**
225   * Returns the method {@link Type} corresponding to the given method.
226   *
227   * @param method a {@link Method} object.
228   * @return the method {@link Type} corresponding to the given method.
229   */
230  public static Type getType(final Method method) {
231    return getType(getMethodDescriptor(method));
232  }
233
234  /**
235   * Returns the type of the elements of this array type. This method should only be used for an
236   * array type.
237   *
238   * @return Returns the type of the elements of this array type.
239   */
240  public Type getElementType() {
241    final int numDimensions = getDimensions();
242    return getTypeInternal(valueBuffer, valueBegin + numDimensions, valueEnd);
243  }
244
245  /**
246   * Returns the {@link Type} corresponding to the given internal name.
247   *
248   * @param internalName an internal name.
249   * @return the {@link Type} corresponding to the given internal name.
250   */
251  public static Type getObjectType(final String internalName) {
252    return new Type(
253        internalName.charAt(0) == '[' ? ARRAY : INTERNAL, internalName, 0, internalName.length());
254  }
255
256  /**
257   * Returns the {@link Type} corresponding to the given method descriptor. Equivalent to <code>
258   * Type.getType(methodDescriptor)</code>.
259   *
260   * @param methodDescriptor a method descriptor.
261   * @return the {@link Type} corresponding to the given method descriptor.
262   */
263  public static Type getMethodType(final String methodDescriptor) {
264    return new Type(METHOD, methodDescriptor, 0, methodDescriptor.length());
265  }
266
267  /**
268   * Returns the method {@link Type} corresponding to the given argument and return types.
269   *
270   * @param returnType the return type of the method.
271   * @param argumentTypes the argument types of the method.
272   * @return the method {@link Type} corresponding to the given argument and return types.
273   */
274  public static Type getMethodType(final Type returnType, final Type... argumentTypes) {
275    return getType(getMethodDescriptor(returnType, argumentTypes));
276  }
277
278  /**
279   * Returns the argument types of methods of this type. This method should only be used for method
280   * types.
281   *
282   * @return the argument types of methods of this type.
283   */
284  public Type[] getArgumentTypes() {
285    return getArgumentTypes(getDescriptor());
286  }
287
288  /**
289   * Returns the {@link Type} values corresponding to the argument types of the given method
290   * descriptor.
291   *
292   * @param methodDescriptor a method descriptor.
293   * @return the {@link Type} values corresponding to the argument types of the given method
294   *     descriptor.
295   */
296  public static Type[] getArgumentTypes(final String methodDescriptor) {
297    // First step: compute the number of argument types in methodDescriptor.
298    int numArgumentTypes = 0;
299    // Skip the first character, which is always a '('.
300    int currentOffset = 1;
301    // Parse the argument types, one at a each loop iteration.
302    while (methodDescriptor.charAt(currentOffset) != ')') {
303      while (methodDescriptor.charAt(currentOffset) == '[') {
304        currentOffset++;
305      }
306      if (methodDescriptor.charAt(currentOffset++) == 'L') {
307        // Skip the argument descriptor content.
308        currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1;
309      }
310      ++numArgumentTypes;
311    }
312
313    // Second step: create a Type instance for each argument type.
314    Type[] argumentTypes = new Type[numArgumentTypes];
315    // Skip the first character, which is always a '('.
316    currentOffset = 1;
317    // Parse and create the argument types, one at each loop iteration.
318    int currentArgumentTypeIndex = 0;
319    while (methodDescriptor.charAt(currentOffset) != ')') {
320      final int currentArgumentTypeOffset = currentOffset;
321      while (methodDescriptor.charAt(currentOffset) == '[') {
322        currentOffset++;
323      }
324      if (methodDescriptor.charAt(currentOffset++) == 'L') {
325        // Skip the argument descriptor content.
326        currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1;
327      }
328      argumentTypes[currentArgumentTypeIndex++] =
329          getTypeInternal(methodDescriptor, currentArgumentTypeOffset, currentOffset);
330    }
331    return argumentTypes;
332  }
333
334  /**
335   * Returns the {@link Type} values corresponding to the argument types of the given method.
336   *
337   * @param method a method.
338   * @return the {@link Type} values corresponding to the argument types of the given method.
339   */
340  public static Type[] getArgumentTypes(final Method method) {
341    Class<?>[] classes = method.getParameterTypes();
342    Type[] types = new Type[classes.length];
343    for (int i = classes.length - 1; i >= 0; --i) {
344      types[i] = getType(classes[i]);
345    }
346    return types;
347  }
348
349  /**
350   * Returns the return type of methods of this type. This method should only be used for method
351   * types.
352   *
353   * @return the return type of methods of this type.
354   */
355  public Type getReturnType() {
356    return getReturnType(getDescriptor());
357  }
358
359  /**
360   * Returns the {@link Type} corresponding to the return type of the given method descriptor.
361   *
362   * @param methodDescriptor a method descriptor.
363   * @return the {@link Type} corresponding to the return type of the given method descriptor.
364   */
365  public static Type getReturnType(final String methodDescriptor) {
366    return getTypeInternal(
367        methodDescriptor, getReturnTypeOffset(methodDescriptor), methodDescriptor.length());
368  }
369
370  /**
371   * Returns the {@link Type} corresponding to the return type of the given method.
372   *
373   * @param method a method.
374   * @return the {@link Type} corresponding to the return type of the given method.
375   */
376  public static Type getReturnType(final Method method) {
377    return getType(method.getReturnType());
378  }
379
380  /**
381   * Returns the start index of the return type of the given method descriptor.
382   *
383   * @param methodDescriptor a method descriptor.
384   * @return the start index of the return type of the given method descriptor.
385   */
386  static int getReturnTypeOffset(final String methodDescriptor) {
387    // Skip the first character, which is always a '('.
388    int currentOffset = 1;
389    // Skip the argument types, one at a each loop iteration.
390    while (methodDescriptor.charAt(currentOffset) != ')') {
391      while (methodDescriptor.charAt(currentOffset) == '[') {
392        currentOffset++;
393      }
394      if (methodDescriptor.charAt(currentOffset++) == 'L') {
395        // Skip the argument descriptor content.
396        currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1;
397      }
398    }
399    return currentOffset + 1;
400  }
401
402  /**
403   * Returns the {@link Type} corresponding to the given field or method descriptor.
404   *
405   * @param descriptorBuffer a buffer containing the field or method descriptor.
406   * @param descriptorBegin the beginning index, inclusive, of the field or method descriptor in
407   *     descriptorBuffer.
408   * @param descriptorEnd the end index, exclusive, of the field or method descriptor in
409   *     descriptorBuffer.
410   * @return the {@link Type} corresponding to the given type descriptor.
411   */
412  private static Type getTypeInternal(
413      final String descriptorBuffer, final int descriptorBegin, final int descriptorEnd) {
414    switch (descriptorBuffer.charAt(descriptorBegin)) {
415      case 'V':
416        return VOID_TYPE;
417      case 'Z':
418        return BOOLEAN_TYPE;
419      case 'C':
420        return CHAR_TYPE;
421      case 'B':
422        return BYTE_TYPE;
423      case 'S':
424        return SHORT_TYPE;
425      case 'I':
426        return INT_TYPE;
427      case 'F':
428        return FLOAT_TYPE;
429      case 'J':
430        return LONG_TYPE;
431      case 'D':
432        return DOUBLE_TYPE;
433      case '[':
434        return new Type(ARRAY, descriptorBuffer, descriptorBegin, descriptorEnd);
435      case 'L':
436        return new Type(OBJECT, descriptorBuffer, descriptorBegin + 1, descriptorEnd - 1);
437      case '(':
438        return new Type(METHOD, descriptorBuffer, descriptorBegin, descriptorEnd);
439      default:
440        throw new IllegalArgumentException();
441    }
442  }
443
444  // -----------------------------------------------------------------------------------------------
445  // Methods to get class names, internal names or descriptors.
446  // -----------------------------------------------------------------------------------------------
447
448  /**
449   * Returns the binary name of the class corresponding to this type. This method must not be used
450   * on method types.
451   *
452   * @return the binary name of the class corresponding to this type.
453   */
454  public String getClassName() {
455    switch (sort) {
456      case VOID:
457        return "void";
458      case BOOLEAN:
459        return "boolean";
460      case CHAR:
461        return "char";
462      case BYTE:
463        return "byte";
464      case SHORT:
465        return "short";
466      case INT:
467        return "int";
468      case FLOAT:
469        return "float";
470      case LONG:
471        return "long";
472      case DOUBLE:
473        return "double";
474      case ARRAY:
475        StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName());
476        for (int i = getDimensions(); i > 0; --i) {
477          stringBuilder.append("[]");
478        }
479        return stringBuilder.toString();
480      case OBJECT:
481      case INTERNAL:
482        return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.');
483      default:
484        throw new AssertionError();
485    }
486  }
487
488  /**
489   * Returns the internal name of the class corresponding to this object or array type. The internal
490   * name of a class is its fully qualified name (as returned by Class.getName(), where '.' are
491   * replaced by '/'). This method should only be used for an object or array type.
492   *
493   * @return the internal name of the class corresponding to this object type.
494   */
495  public String getInternalName() {
496    return valueBuffer.substring(valueBegin, valueEnd);
497  }
498
499  /**
500   * Returns the internal name of the given class. The internal name of a class is its fully
501   * qualified name, as returned by Class.getName(), where '.' are replaced by '/'.
502   *
503   * @param clazz an object or array class.
504   * @return the internal name of the given class.
505   */
506  public static String getInternalName(final Class<?> clazz) {
507    return clazz.getName().replace('.', '/');
508  }
509
510  /**
511   * Returns the descriptor corresponding to this type.
512   *
513   * @return the descriptor corresponding to this type.
514   */
515  public String getDescriptor() {
516    if (sort == OBJECT) {
517      return valueBuffer.substring(valueBegin - 1, valueEnd + 1);
518    } else if (sort == INTERNAL) {
519      return 'L' + valueBuffer.substring(valueBegin, valueEnd) + ';';
520    } else {
521      return valueBuffer.substring(valueBegin, valueEnd);
522    }
523  }
524
525  /**
526   * Returns the descriptor corresponding to the given class.
527   *
528   * @param clazz an object class, a primitive class or an array class.
529   * @return the descriptor corresponding to the given class.
530   */
531  public static String getDescriptor(final Class<?> clazz) {
532    StringBuilder stringBuilder = new StringBuilder();
533    appendDescriptor(clazz, stringBuilder);
534    return stringBuilder.toString();
535  }
536
537  /**
538   * Returns the descriptor corresponding to the given constructor.
539   *
540   * @param constructor a {@link Constructor} object.
541   * @return the descriptor of the given constructor.
542   */
543  public static String getConstructorDescriptor(final Constructor<?> constructor) {
544    StringBuilder stringBuilder = new StringBuilder();
545    stringBuilder.append('(');
546    Class<?>[] parameters = constructor.getParameterTypes();
547    for (Class<?> parameter : parameters) {
548      appendDescriptor(parameter, stringBuilder);
549    }
550    return stringBuilder.append(")V").toString();
551  }
552
553  /**
554   * Returns the descriptor corresponding to the given argument and return types.
555   *
556   * @param returnType the return type of the method.
557   * @param argumentTypes the argument types of the method.
558   * @return the descriptor corresponding to the given argument and return types.
559   */
560  public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) {
561    StringBuilder stringBuilder = new StringBuilder();
562    stringBuilder.append('(');
563    for (Type argumentType : argumentTypes) {
564      argumentType.appendDescriptor(stringBuilder);
565    }
566    stringBuilder.append(')');
567    returnType.appendDescriptor(stringBuilder);
568    return stringBuilder.toString();
569  }
570
571  /**
572   * Returns the descriptor corresponding to the given method.
573   *
574   * @param method a {@link Method} object.
575   * @return the descriptor of the given method.
576   */
577  public static String getMethodDescriptor(final Method method) {
578    StringBuilder stringBuilder = new StringBuilder();
579    stringBuilder.append('(');
580    Class<?>[] parameters = method.getParameterTypes();
581    for (Class<?> parameter : parameters) {
582      appendDescriptor(parameter, stringBuilder);
583    }
584    stringBuilder.append(')');
585    appendDescriptor(method.getReturnType(), stringBuilder);
586    return stringBuilder.toString();
587  }
588
589  /**
590   * Appends the descriptor corresponding to this type to the given string buffer.
591   *
592   * @param stringBuilder the string builder to which the descriptor must be appended.
593   */
594  private void appendDescriptor(final StringBuilder stringBuilder) {
595    if (sort == OBJECT) {
596      stringBuilder.append(valueBuffer, valueBegin - 1, valueEnd + 1);
597    } else if (sort == INTERNAL) {
598      stringBuilder.append('L').append(valueBuffer, valueBegin, valueEnd).append(';');
599    } else {
600      stringBuilder.append(valueBuffer, valueBegin, valueEnd);
601    }
602  }
603
604  /**
605   * Appends the descriptor of the given class to the given string builder.
606   *
607   * @param clazz the class whose descriptor must be computed.
608   * @param stringBuilder the string builder to which the descriptor must be appended.
609   */
610  private static void appendDescriptor(final Class<?> clazz, final StringBuilder stringBuilder) {
611    Class<?> currentClass = clazz;
612    while (currentClass.isArray()) {
613      stringBuilder.append('[');
614      currentClass = currentClass.getComponentType();
615    }
616    if (currentClass.isPrimitive()) {
617      char descriptor;
618      if (currentClass == Integer.TYPE) {
619        descriptor = 'I';
620      } else if (currentClass == Void.TYPE) {
621        descriptor = 'V';
622      } else if (currentClass == Boolean.TYPE) {
623        descriptor = 'Z';
624      } else if (currentClass == Byte.TYPE) {
625        descriptor = 'B';
626      } else if (currentClass == Character.TYPE) {
627        descriptor = 'C';
628      } else if (currentClass == Short.TYPE) {
629        descriptor = 'S';
630      } else if (currentClass == Double.TYPE) {
631        descriptor = 'D';
632      } else if (currentClass == Float.TYPE) {
633        descriptor = 'F';
634      } else if (currentClass == Long.TYPE) {
635        descriptor = 'J';
636      } else {
637        throw new AssertionError();
638      }
639      stringBuilder.append(descriptor);
640    } else {
641      stringBuilder.append('L').append(getInternalName(currentClass)).append(';');
642    }
643  }
644
645  // -----------------------------------------------------------------------------------------------
646  // Methods to get the sort, dimension, size, and opcodes corresponding to a Type or descriptor.
647  // -----------------------------------------------------------------------------------------------
648
649  /**
650   * Returns the sort of this type.
651   *
652   * @return {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE}, {@link #SHORT}, {@link
653   *     #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY}, {@link #OBJECT} or
654   *     {@link #METHOD}.
655   */
656  public int getSort() {
657    return sort == INTERNAL ? OBJECT : sort;
658  }
659
660  /**
661   * Returns the number of dimensions of this array type. This method should only be used for an
662   * array type.
663   *
664   * @return the number of dimensions of this array type.
665   */
666  public int getDimensions() {
667    int numDimensions = 1;
668    while (valueBuffer.charAt(valueBegin + numDimensions) == '[') {
669      numDimensions++;
670    }
671    return numDimensions;
672  }
673
674  /**
675   * Returns the size of values of this type. This method must not be used for method types.
676   *
677   * @return the size of values of this type, i.e., 2 for {@code long} and {@code double}, 0 for
678   *     {@code void} and 1 otherwise.
679   */
680  public int getSize() {
681    switch (sort) {
682      case VOID:
683        return 0;
684      case BOOLEAN:
685      case CHAR:
686      case BYTE:
687      case SHORT:
688      case INT:
689      case FLOAT:
690      case ARRAY:
691      case OBJECT:
692      case INTERNAL:
693        return 1;
694      case LONG:
695      case DOUBLE:
696        return 2;
697      default:
698        throw new AssertionError();
699    }
700  }
701
702  /**
703   * Returns the size of the arguments and of the return value of methods of this type. This method
704   * should only be used for method types.
705   *
706   * @return the size of the arguments of the method (plus one for the implicit this argument),
707   *     argumentsSize, and the size of its return value, returnSize, packed into a single int i =
708   *     {@code (argumentsSize &lt;&lt; 2) | returnSize} (argumentsSize is therefore equal to {@code
709   *     i &gt;&gt; 2}, and returnSize to {@code i &amp; 0x03}).
710   */
711  public int getArgumentsAndReturnSizes() {
712    return getArgumentsAndReturnSizes(getDescriptor());
713  }
714
715  /**
716   * Computes the size of the arguments and of the return value of a method.
717   *
718   * @param methodDescriptor a method descriptor.
719   * @return the size of the arguments of the method (plus one for the implicit this argument),
720   *     argumentsSize, and the size of its return value, returnSize, packed into a single int i =
721   *     {@code (argumentsSize &lt;&lt; 2) | returnSize} (argumentsSize is therefore equal to {@code
722   *     i &gt;&gt; 2}, and returnSize to {@code i &amp; 0x03}).
723   */
724  public static int getArgumentsAndReturnSizes(final String methodDescriptor) {
725    int argumentsSize = 1;
726    // Skip the first character, which is always a '('.
727    int currentOffset = 1;
728    int currentChar = methodDescriptor.charAt(currentOffset);
729    // Parse the argument types and compute their size, one at a each loop iteration.
730    while (currentChar != ')') {
731      if (currentChar == 'J' || currentChar == 'D') {
732        currentOffset++;
733        argumentsSize += 2;
734      } else {
735        while (methodDescriptor.charAt(currentOffset) == '[') {
736          currentOffset++;
737        }
738        if (methodDescriptor.charAt(currentOffset++) == 'L') {
739          // Skip the argument descriptor content.
740          currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1;
741        }
742        argumentsSize += 1;
743      }
744      currentChar = methodDescriptor.charAt(currentOffset);
745    }
746    currentChar = methodDescriptor.charAt(currentOffset + 1);
747    if (currentChar == 'V') {
748      return argumentsSize << 2;
749    } else {
750      int returnSize = (currentChar == 'J' || currentChar == 'D') ? 2 : 1;
751      return argumentsSize << 2 | returnSize;
752    }
753  }
754
755  /**
756   * Returns a JVM instruction opcode adapted to this {@link Type}. This method must not be used for
757   * method types.
758   *
759   * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, ISTORE, IALOAD,
760   *     IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, ISHR, IUSHR, IAND, IOR, IXOR and
761   *     IRETURN.
762   * @return an opcode that is similar to the given opcode, but adapted to this {@link Type}. For
763   *     example, if this type is {@code float} and {@code opcode} is IRETURN, this method returns
764   *     FRETURN.
765   */
766  public int getOpcode(final int opcode) {
767    if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
768      switch (sort) {
769        case BOOLEAN:
770        case BYTE:
771          return opcode + (Opcodes.BALOAD - Opcodes.IALOAD);
772        case CHAR:
773          return opcode + (Opcodes.CALOAD - Opcodes.IALOAD);
774        case SHORT:
775          return opcode + (Opcodes.SALOAD - Opcodes.IALOAD);
776        case INT:
777          return opcode;
778        case FLOAT:
779          return opcode + (Opcodes.FALOAD - Opcodes.IALOAD);
780        case LONG:
781          return opcode + (Opcodes.LALOAD - Opcodes.IALOAD);
782        case DOUBLE:
783          return opcode + (Opcodes.DALOAD - Opcodes.IALOAD);
784        case ARRAY:
785        case OBJECT:
786        case INTERNAL:
787          return opcode + (Opcodes.AALOAD - Opcodes.IALOAD);
788        case METHOD:
789        case VOID:
790          throw new UnsupportedOperationException();
791        default:
792          throw new AssertionError();
793      }
794    } else {
795      switch (sort) {
796        case VOID:
797          if (opcode != Opcodes.IRETURN) {
798            throw new UnsupportedOperationException();
799          }
800          return Opcodes.RETURN;
801        case BOOLEAN:
802        case BYTE:
803        case CHAR:
804        case SHORT:
805        case INT:
806          return opcode;
807        case FLOAT:
808          return opcode + (Opcodes.FRETURN - Opcodes.IRETURN);
809        case LONG:
810          return opcode + (Opcodes.LRETURN - Opcodes.IRETURN);
811        case DOUBLE:
812          return opcode + (Opcodes.DRETURN - Opcodes.IRETURN);
813        case ARRAY:
814        case OBJECT:
815        case INTERNAL:
816          if (opcode != Opcodes.ILOAD && opcode != Opcodes.ISTORE && opcode != Opcodes.IRETURN) {
817            throw new UnsupportedOperationException();
818          }
819          return opcode + (Opcodes.ARETURN - Opcodes.IRETURN);
820        case METHOD:
821          throw new UnsupportedOperationException();
822        default:
823          throw new AssertionError();
824      }
825    }
826  }
827
828  // -----------------------------------------------------------------------------------------------
829  // Equals, hashCode and toString.
830  // -----------------------------------------------------------------------------------------------
831
832  /**
833   * Tests if the given object is equal to this type.
834   *
835   * @param object the object to be compared to this type.
836   * @return {@literal true} if the given object is equal to this type.
837   */
838  @Override
839  public boolean equals(final Object object) {
840    if (this == object) {
841      return true;
842    }
843    if (!(object instanceof Type)) {
844      return false;
845    }
846    Type other = (Type) object;
847    if ((sort == INTERNAL ? OBJECT : sort) != (other.sort == INTERNAL ? OBJECT : other.sort)) {
848      return false;
849    }
850    int begin = valueBegin;
851    int end = valueEnd;
852    int otherBegin = other.valueBegin;
853    int otherEnd = other.valueEnd;
854    // Compare the values.
855    if (end - begin != otherEnd - otherBegin) {
856      return false;
857    }
858    for (int i = begin, j = otherBegin; i < end; i++, j++) {
859      if (valueBuffer.charAt(i) != other.valueBuffer.charAt(j)) {
860        return false;
861      }
862    }
863    return true;
864  }
865
866  /**
867   * Returns a hash code value for this type.
868   *
869   * @return a hash code value for this type.
870   */
871  @Override
872  public int hashCode() {
873    int hashCode = 13 * (sort == INTERNAL ? OBJECT : sort);
874    if (sort >= ARRAY) {
875      for (int i = valueBegin, end = valueEnd; i < end; i++) {
876        hashCode = 17 * (hashCode + valueBuffer.charAt(i));
877      }
878    }
879    return hashCode;
880  }
881
882  /**
883   * Returns a string representation of this type.
884   *
885   * @return the descriptor of this type.
886   */
887  @Override
888  public String toString() {
889    return getDescriptor();
890  }
891}