1 /*
   2  * Copyright (c) 2018, 2019, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.lang.constant;
  26 
  27 import jdk.internal.lang.annotation.Foldable;
  28 import java.lang.invoke.MethodHandles;
  29 import java.lang.invoke.TypeDescriptor;
  30 import java.util.stream.Stream;
  31 
  32 import sun.invoke.util.Wrapper;
  33 
  34 import static java.lang.constant.ConstantUtils.binaryToInternal;
  35 import static java.lang.constant.ConstantUtils.dropLastChar;
  36 import static java.lang.constant.ConstantUtils.internalToBinary;
  37 import static java.lang.constant.ConstantUtils.validateMemberName;
  38 import static java.util.Objects.requireNonNull;
  39 import static java.util.stream.Collectors.joining;
  40 
  41 /**
  42  * A <a href="package-summary.html#nominal">nominal descriptor</a> for a
  43  * {@link Class} constant.
  44  *
  45  * <p>For common system types, including all the primitive types, there are
  46  * predefined {@linkplain ClassDesc} constants in {@link ConstantDescs}.
  47  * (The {@code java.lang.constant} APIs consider {@code void} to be a primitive type.)
  48  * To create a {@linkplain ClassDesc} for a class or interface type, use {@link #of} or
  49  * {@link #ofDescriptor(String)}; to create a {@linkplain ClassDesc} for an array
  50  * type, use {@link #ofDescriptor(String)}, or first obtain a
  51  * {@linkplain ClassDesc} for the component type and then call the {@link #arrayType()}
  52  * or {@link #arrayType(int)} methods.
  53  *
  54  * @apiNote In the future, if the Java language permits, {@linkplain ClassDesc}
  55  * may become a {@code sealed} interface, which would prohibit subclassing except
  56  * by explicitly permitted types.  Non-platform classes should not implement
  57  * {@linkplain ClassDesc} directly.
  58  *
  59  * @see ConstantDescs
  60  *
  61  * @since 12
  62  */
  63 public interface ClassDesc
  64         extends ConstantDesc,
  65                 Constable,
  66                 TypeDescriptor.OfField<ClassDesc> {
  67 
  68     /**
  69      * Returns a {@linkplain ClassDesc} for a class or interface type,
  70      * given the name of the class or interface, such as {@code "java.lang.String"}.
  71      * (To create a descriptor for an array type, either use {@link #ofDescriptor(String)}
  72      * or {@link #arrayType()}; to create a descriptor for a primitive type, use
  73      * {@link #ofDescriptor(String)} or use the predefined constants in
  74      * {@link ConstantDescs}).
  75      *
  76      * @param name the fully qualified (dot-separated) binary class name
  77      * @return a {@linkplain ClassDesc} describing the desired class
  78      * @throws NullPointerException if any argument is {@code null}
  79      * @throws IllegalArgumentException if the name string is not in the
  80      * correct format
  81      */
  82     @Foldable
  83     static ClassDesc of(String name) {
  84         ConstantUtils.validateBinaryClassName(requireNonNull(name));
  85         return ClassDesc.ofDescriptor("L" + binaryToInternal(name) + ";");
  86     }
  87 
  88     /**
  89      * Returns a {@linkplain ClassDesc} for a class or interface type,
  90      * given a package name and the unqualified (simple) name for the
  91      * class or interface.
  92      *
  93      * @param packageName the package name (dot-separated); if the package
  94      *                    name is the empty string, the class is considered to
  95      *                    be in the unnamed package
  96      * @param className the unqualified (simple) class name
  97      * @return a {@linkplain ClassDesc} describing the desired class
  98      * @throws NullPointerException if any argument is {@code null}
  99      * @throws IllegalArgumentException if the package name or class name are
 100      * not in the correct format
 101      */
 102     @Foldable
 103     static ClassDesc of(String packageName, String className) {
 104         ConstantUtils.validateBinaryClassName(requireNonNull(packageName));
 105         if (packageName.isEmpty()) {
 106             return of(className);
 107         }
 108         validateMemberName(requireNonNull(className), false);
 109         return ofDescriptor("L" + binaryToInternal(packageName) +
 110                 (packageName.length() > 0 ? "/" : "") + className + ";");
 111     }
 112 
 113     /**
 114      * Returns a {@linkplain ClassDesc} given a descriptor string for a class,
 115      * interface, array, or primitive type.
 116      *
 117      * @apiNote
 118      *
 119      * A field type descriptor string for a non-array type is either
 120      * a one-letter code corresponding to a primitive type
 121      * ({@code "J", "I", "C", "S", "B", "D", "F", "Z", "V"}), or the letter {@code "L"}, followed
 122      * by the fully qualified binary name of a class, followed by {@code ";"}.
 123      * A field type descriptor for an array type is the character {@code "["}
 124      * followed by the field descriptor for the component type.  Examples of
 125      * valid type descriptor strings include {@code "Ljava/lang/String;"}, {@code "I"},
 126      * {@code "[I"}, {@code "V"}, {@code "[Ljava/lang/String;"}, etc.
 127      * See JVMS 4.3.2 ("Field Descriptors") for more detail.
 128      *
 129      * @param descriptor a field descriptor string
 130      * @return a {@linkplain ClassDesc} describing the desired class
 131      * @throws NullPointerException if any argument is {@code null}
 132      * @throws IllegalArgumentException if the name string is not in the
 133      * correct format
 134      * @jvms 4.3.2 Field Descriptors
 135      * @jvms 4.4.1 The CONSTANT_Class_info Structure
 136      */
 137     @Foldable
 138     static ClassDesc ofDescriptor(String descriptor) {
 139         requireNonNull(descriptor);
 140         if (descriptor.isEmpty()) {
 141             throw new IllegalArgumentException(
 142                     "not a valid reference type descriptor: " + descriptor);
 143         }
 144         int depth = ConstantUtils.arrayDepth(descriptor);
 145         if (depth > ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS) {
 146             throw new IllegalArgumentException(
 147                     "Cannot create an array type descriptor with more than " +
 148                     ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS + " dimensions");
 149         }
 150         return (descriptor.length() == 1)
 151                ? new PrimitiveClassDescImpl(descriptor)
 152                : new ReferenceClassDescImpl(descriptor);
 153     }
 154 
 155     /**
 156      * Returns a {@linkplain ClassDesc} for an array type whose component type
 157      * is described by this {@linkplain ClassDesc}.
 158      *
 159      * @return a {@linkplain ClassDesc} describing the array type
 160      * @throws IllegalStateException if the resulting {@linkplain ClassDesc} would have an array rank of greater than 255
 161      * @jvms 4.4.1 The CONSTANT_Class_info Structure
 162      */
 163     @Foldable
 164     default ClassDesc arrayType() {
 165         int depth = ConstantUtils.arrayDepth(descriptorString());
 166         if (depth >= ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS) {
 167             throw new IllegalStateException(
 168                     "Cannot create an array type descriptor with more than " +
 169                     ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS + " dimensions");
 170         }
 171         return arrayType(1);
 172     }
 173 
 174     /**
 175      * Returns a {@linkplain ClassDesc} for an array type of the specified rank,
 176      * whose component type is described by this {@linkplain ClassDesc}.
 177      *
 178      * @param rank the rank of the array
 179      * @return a {@linkplain ClassDesc} describing the array type
 180      * @throws IllegalArgumentException if the rank is less than or equal to zero or if the rank of the resulting array type is
 181      * greater than 255
 182      * @jvms 4.4.1 The CONSTANT_Class_info Structure
 183      */
 184     @Foldable
 185     default ClassDesc arrayType(int rank) {
 186         int currentDepth = ConstantUtils.arrayDepth(descriptorString());
 187         if (rank <= 0 || currentDepth + rank > ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS)
 188             throw new IllegalArgumentException("rank: " + currentDepth + rank);
 189         return ClassDesc.ofDescriptor("[".repeat(rank) + descriptorString());
 190     }
 191 
 192     /**
 193      * Returns a {@linkplain ClassDesc} for a nested class of the class or
 194      * interface type described by this {@linkplain ClassDesc}.
 195      *
 196      * @apiNote
 197      *
 198      * Example: If descriptor {@code d} describes the class {@code java.util.Map}, a
 199      * descriptor for the class {@code java.util.Map.Entry} could be obtained
 200      * by {@code d.nested("Entry")}.
 201      *
 202      * @param nestedName the unqualified name of the nested class
 203      * @return a {@linkplain ClassDesc} describing the nested class
 204      * @throws NullPointerException if any argument is {@code null}
 205      * @throws IllegalStateException if this {@linkplain ClassDesc} does not
 206      * describe a class or interface type
 207      * @throws IllegalArgumentException if the nested class name is invalid
 208      */
 209     @Foldable
 210     default ClassDesc nested(String nestedName) {
 211         validateMemberName(nestedName, false);
 212         if (!isClassOrInterface())
 213             throw new IllegalStateException("Outer class is not a class or interface type");
 214         return ClassDesc.ofDescriptor(dropLastChar(descriptorString()) + "$" + nestedName + ";");
 215     }
 216 
 217     /**
 218      * Returns a {@linkplain ClassDesc} for a nested class of the class or
 219      * interface type described by this {@linkplain ClassDesc}.
 220      *
 221      * @param firstNestedName the unqualified name of the first level of nested class
 222      * @param moreNestedNames the unqualified name(s) of the remaining levels of
 223      *                       nested class
 224      * @return a {@linkplain ClassDesc} describing the nested class
 225      * @throws NullPointerException if any argument is {@code null}
 226      * @throws IllegalStateException if this {@linkplain ClassDesc} does not
 227      * describe a class or interface type
 228      * @throws IllegalArgumentException if the nested class name is invalid
 229      */
 230     @Foldable
 231     default ClassDesc nested(String firstNestedName, String... moreNestedNames) {
 232         if (!isClassOrInterface())
 233             throw new IllegalStateException("Outer class is not a class or interface type");
 234         return moreNestedNames.length == 0
 235                ? nested(firstNestedName)
 236                : nested(firstNestedName + Stream.of(moreNestedNames).collect(joining("$", "$", "")));
 237     }
 238 
 239     /**
 240      * Returns whether this {@linkplain ClassDesc} describes an array type.
 241      *
 242      * @return whether this {@linkplain ClassDesc} describes an array type
 243      */
 244     default boolean isArray() {
 245         return descriptorString().startsWith("[");
 246     }
 247 
 248     /**
 249      * Returns whether this {@linkplain ClassDesc} describes a primitive type.
 250      *
 251      * @return whether this {@linkplain ClassDesc} describes a primitive type
 252      */
 253     default boolean isPrimitive() {
 254         return descriptorString().length() == 1;
 255     }
 256 
 257     /**
 258      * Returns whether this {@linkplain ClassDesc} describes a class or interface type.
 259      *
 260      * @return whether this {@linkplain ClassDesc} describes a class or interface type
 261      */
 262     default boolean isClassOrInterface() {
 263         return descriptorString().startsWith("L");
 264     }
 265 
 266     /**
 267      * Returns the component type of this {@linkplain ClassDesc}, if it describes
 268      * an array type, or {@code null} otherwise.
 269      *
 270      * @return a {@linkplain ClassDesc} describing the component type, or {@code null}
 271      * if this descriptor does not describe an array type
 272      */
 273     @Foldable
 274     default ClassDesc componentType() {
 275         return isArray() ? ClassDesc.ofDescriptor(descriptorString().substring(1)) : null;
 276     }
 277 
 278     /**
 279      * Returns the package name of this {@linkplain ClassDesc}, if it describes
 280      * a class or interface type.
 281      *
 282      * @return the package name, or the empty string if the class is in the
 283      * default package, or this {@linkplain ClassDesc} does not describe a class or interface type
 284      */
 285     default String packageName() {
 286         if (!isClassOrInterface())
 287             return "";
 288         String className = internalToBinary(ConstantUtils.dropFirstAndLastChar(descriptorString()));
 289         int index = className.lastIndexOf('.');
 290         return (index == -1) ? "" : className.substring(0, index);
 291     }
 292 
 293     /**
 294      * Returns a human-readable name for the type described by this descriptor.
 295      *
 296      * @implSpec
 297      * <p>The default implementation returns the simple name
 298      * (e.g., {@code int}) for primitive types, the unqualified class name
 299      * for class or interface types, or the display name of the component type
 300      * suffixed with the appropriate number of {@code []} pairs for array types.
 301      *
 302      * @return the human-readable name
 303      */
 304     default String displayName() {
 305         if (isPrimitive())
 306             return Wrapper.forBasicType(descriptorString().charAt(0)).primitiveSimpleName();
 307         else if (isClassOrInterface()) {
 308             return descriptorString().substring(Math.max(1, descriptorString().lastIndexOf('/') + 1),
 309                                                 descriptorString().length() - 1);
 310         }
 311         else if (isArray()) {
 312             int depth = ConstantUtils.arrayDepth(descriptorString());
 313             ClassDesc c = this;
 314             for (int i=0; i<depth; i++)
 315                 c = c.componentType();
 316             return c.displayName() + "[]".repeat(depth);
 317         }
 318         else
 319             throw new IllegalStateException(descriptorString());
 320     }
 321 
 322     /**
 323      * Returns a field type descriptor string for this type
 324      *
 325      * @return the descriptor string
 326      * @jvms 4.3.2 Field Descriptors
 327      */
 328     @Foldable
 329     String descriptorString();
 330 
 331     /**
 332      * Compare the specified object with this descriptor for equality.  Returns
 333      * {@code true} if and only if the specified object is also a
 334      * {@linkplain ClassDesc} and both describe the same type.
 335      *
 336      * @param o the other object
 337      * @return whether this descriptor is equal to the other object
 338      */
 339     boolean equals(Object o);
 340 }