1 /*
   2  * Copyright (c) 2018, 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 java.lang.invoke.TypeDescriptor;
  28 import java.util.stream.Stream;
  29 
  30 import sun.invoke.util.Wrapper;
  31 
  32 import static java.lang.constant.ConstantUtils.binaryToInternal;
  33 import static java.lang.constant.ConstantUtils.dropLastChar;
  34 import static java.lang.constant.ConstantUtils.internalToBinary;
  35 import static java.lang.constant.ConstantUtils.validateMemberName;
  36 import static java.util.Objects.requireNonNull;
  37 import static java.util.stream.Collectors.joining;
  38 
  39 /**
  40  * A <a href="package-summary.html#nominal">nominal descriptor</a> for a
  41  * {@link Class} constant.
  42  *
  43  * <p>For common system types, including all the primitive types, there are
  44  * predefined {@linkplain ClassDesc} constants in {@link ConstantDescs}.
  45  * (The {@code java.lang.constant} APIs consider {@code void} to be a primitive type.)
  46  * To create a {@linkplain ClassDesc} for a class or interface type, use {@link #of} or
  47  * {@link #ofDescriptor(String)}; to create a {@linkplain ClassDesc} for an array
  48  * type, use {@link #ofDescriptor(String)}, or first obtain a
  49  * {@linkplain ClassDesc} for the component type and then call the {@link #arrayType()}
  50  * or {@link #arrayType(int)} methods.
  51  *
  52  * <p>Two {@linkplain ClassDesc} objects are considered {@link Object#equals(Object)}
  53  * if they describe exactly the same type.
  54  *
  55  * @apiNote In the future, if the Java language permits, {@linkplain ClassDesc}
  56  * may become a {@code sealed} interface, which would prohibit subclassing except
  57  * by explicitly permitted types.  Non-platform classes should not implement
  58  * {@linkplain ClassDesc} directly.
  59  *
  60  * @see ConstantDescs
  61  *
  62  * @since 12
  63  */
  64 public interface ClassDesc
  65         extends ConstantDesc,
  66                 TypeDescriptor.OfField<ClassDesc> {
  67 
  68     /**
  69      * Create 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     static ClassDesc of(String name) {
  83         ConstantUtils.validateBinaryClassName(requireNonNull(name));
  84         return ClassDesc.ofDescriptor("L" + binaryToInternal(name) + ";");
  85     }
  86 
  87     /**
  88      * Create a {@linkplain ClassDesc} for a class or interface type,
  89      * given a package name and the unqualified (simple) name for the
  90      * class or interface.
  91      *
  92      * @param packageName the package name (dot-separated); if the package
  93      *                    name is the empty string, the class is considered to
  94      *                    be in the unnamed package
  95      * @param className the unqualified (simple) class name
  96      * @return a {@linkplain ClassDesc} describing the desired class
  97      * @throws NullPointerException if any argument is {@code null}
  98      * @throws IllegalArgumentException if the package name or class name are
  99      * not in the correct format
 100      */
 101     static ClassDesc of(String packageName, String className) {
 102         ConstantUtils.validateBinaryClassName(requireNonNull(packageName));
 103         validateMemberName(requireNonNull(className));
 104         return ofDescriptor(String.format("L%s%s%s;",
 105                                           binaryToInternal(packageName),
 106                                           (packageName.length() > 0 ? "/" : ""),
 107                                           className));
 108     }
 109 
 110     /**
 111      * Create a {@linkplain ClassDesc} given a descriptor string for a class,
 112      * interface, array, or primitive type.
 113      *
 114      * @apiNote
 115      *
 116      * A field type descriptor string for a non-array type is either
 117      * a one-letter code corresponding to a primitive type
 118      * ({@code J,I,C,S,B,D,F,Z,V}), or the letter {@code L}, followed
 119      * by the fully qualified binary name of a class, followed by {@code ;}.
 120      * A field type descriptor for an array type is the character {@code [}
 121      * followed by the field descriptor for the component type.  Examples of
 122      * valid type descriptor strings include {@code Ljava/lang/String;}, {@code I},
 123      * {@code [I}, {@code V}, {@code [Ljava/lang/String;}, etc.
 124      * for more detail.
 125      *
 126      * @param descriptor a field descriptor string
 127      * @return a {@linkplain ClassDesc} describing the desired class
 128      * @throws NullPointerException if any argument is {@code null}
 129      * @throws IllegalArgumentException if the name string is not in the
 130      * correct format
 131      * @jvms 4.3.2 Field Descriptors
 132      */
 133     static ClassDesc ofDescriptor(String descriptor) {
 134         requireNonNull(descriptor);
 135         return (descriptor.length() == 1)
 136                ? new PrimitiveClassDescImpl(descriptor)
 137                : new ReferenceClassDescImpl(descriptor);
 138     }
 139 
 140     /**
 141      * Create a {@linkplain ClassDesc} for an array type whose component type
 142      * is described by this {@linkplain ClassDesc}.
 143      *
 144      * @return a {@linkplain ClassDesc} describing the array type
 145      */
 146     default ClassDesc arrayType() {
 147         return arrayType(1);
 148     }
 149 
 150     /**
 151      * Create a {@linkplain ClassDesc} for an array type of the specified rank,
 152      * whose component type is described by this {@linkplain ClassDesc}.
 153      *
 154      * @param rank the rank of the array
 155      * @return a {@linkplain ClassDesc} describing the array type
 156      * @throws IllegalArgumentException if the rank is zero or negative
 157      */
 158     default ClassDesc arrayType(int rank) {
 159         if (rank <= 0)
 160             throw new IllegalArgumentException("rank: " + rank);
 161         return ClassDesc.ofDescriptor("[".repeat(rank) + descriptorString());
 162     }
 163 
 164     /**
 165      * Create a {@linkplain ClassDesc} for an inner class of the class or
 166      * interface type described by this {@linkplain ClassDesc}.
 167      *
 168      * @param innerName the unqualified name of the inner class
 169      * @return a {@linkplain ClassDesc} describing the inner class
 170      * @throws NullPointerException if any argument is {@code null}
 171      * @throws IllegalStateException if this {@linkplain ClassDesc} does not
 172      * describe a class or interface type
 173      */
 174     default ClassDesc inner(String innerName) {
 175         validateMemberName(innerName);
 176         if (!isClassOrInterface())
 177             throw new IllegalStateException("Outer class is not a class or interface type");
 178         return ClassDesc.ofDescriptor(String.format("%s$%s;", dropLastChar(descriptorString()), innerName));
 179     }
 180 
 181     /**
 182      * Create a {@linkplain ClassDesc} for an inner class of the class or
 183      * interface type described by this {@linkplain ClassDesc}.
 184      *
 185      * @param firstInnerName the unqualified name of the first level of inner class
 186      * @param moreInnerNames the unqualified name(s) of the remaining levels of
 187      *                       inner class
 188      * @return a {@linkplain ClassDesc} describing the inner class
 189      * @throws NullPointerException if any argument is {@code null}
 190      * @throws IllegalStateException if this {@linkplain ClassDesc} does not
 191      * describe a class or interface type
 192      */
 193     default ClassDesc inner(String firstInnerName, String... moreInnerNames) {
 194         if (!isClassOrInterface())
 195             throw new IllegalStateException("Outer class is not a class or interface type");
 196         return moreInnerNames.length == 0
 197                ? inner(firstInnerName)
 198                : inner(firstInnerName + Stream.of(moreInnerNames).collect(joining("$", "$", "")));
 199     }
 200 
 201     /**
 202      * Returns whether this {@linkplain ClassDesc} describes an array type.
 203      *
 204      * @return whether this {@linkplain ClassDesc} describes an array type
 205      */
 206     default boolean isArray() {
 207         return descriptorString().startsWith("[");
 208     }
 209 
 210     /**
 211      * Returns whether this {@linkplain ClassDesc} describes a primitive type.
 212      *
 213      * @return whether this {@linkplain ClassDesc} describes a primitive type
 214      */
 215     default boolean isPrimitive() {
 216         return descriptorString().length() == 1;
 217     }
 218 
 219     /**
 220      * Returns whether this {@linkplain ClassDesc} describes a class or interface type.
 221      *
 222      * @return whether this {@linkplain ClassDesc} describes a class or interface type
 223      */
 224     default boolean isClassOrInterface() {
 225         return descriptorString().startsWith("L");
 226     }
 227 
 228     /**
 229      * Returns the component type of this {@linkplain ClassDesc}, if it describes
 230      * an array type, or {@code null} otherwise.
 231      *
 232      * @return a {@linkplain ClassDesc} describing the component type, or {@code null}
 233      * if this descriptor does not describe an array type
 234      */
 235     default ClassDesc componentType() {
 236         return isArray() ? ClassDesc.ofDescriptor(descriptorString().substring(1)) : null;
 237     }
 238 
 239     /**
 240      * Returns the package name of this {@linkplain ClassDesc}, if it describes
 241      * a class or interface type.
 242      *
 243      * @return the package name, or the empty string if the class is in the
 244      * default package, or this {@linkplain ClassDesc} does not describe a class or interface type
 245      */
 246     default String packageName() {
 247         if (!isClassOrInterface())
 248             return "";
 249         String className = internalToBinary(ConstantUtils.dropFirstAndLastChar(descriptorString()));
 250         int index = className.lastIndexOf('.');
 251         return (index == -1) ? "" : className.substring(0, index);
 252     }
 253 
 254     /**
 255      * Returns a human-readable name for the type described by this descriptor.
 256      *
 257      * @implSpec
 258      * <p>The default implementation returns the simple name
 259      * (e.g., {@code int}) for primitive types, the unqualified class name
 260      * for class or interface types, or the display name of the component type
 261      * suffixed with the appropriate number of {@code []} pairs for array types.
 262      *
 263      * @return the human-readable name
 264      */
 265     default String displayName() {
 266         if (isPrimitive())
 267             return Wrapper.forBasicType(descriptorString().charAt(0)).primitiveSimpleName();
 268         else if (isClassOrInterface()) {
 269             return descriptorString().substring(Math.max(1, descriptorString().lastIndexOf('/') + 1),
 270                                                 descriptorString().length() - 1);
 271         }
 272         else if (isArray()) {
 273             int depth = ConstantUtils.arrayDepth(descriptorString());
 274             ClassDesc c = this;
 275             for (int i=0; i<depth; i++)
 276                 c = c.componentType();
 277             return c.displayName() + "[]".repeat(depth);
 278         }
 279         else
 280             throw new IllegalStateException(descriptorString());
 281     }
 282 
 283     /**
 284      * Return a field type descriptor string for this type
 285      *
 286      * @return the descriptor string
 287      * @jvms 4.3.2 Field Descriptors
 288      */
 289     String descriptorString();
 290 }