001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.bcel.generic;
020
021import org.apache.bcel.Const;
022import org.apache.bcel.Repository;
023import org.apache.bcel.classfile.JavaClass;
024
025/**
026 * Super class for object and array types.
027 */
028public abstract class ReferenceType extends Type {
029
030    /**
031     * Class is non-abstract but not instantiable from the outside
032     */
033    ReferenceType() {
034        super(Const.T_OBJECT, "<null object>");
035    }
036
037    protected ReferenceType(final byte t, final String s) {
038        super(t, s);
039    }
040
041    /**
042     * This commutative operation returns the first common superclass (narrowest ReferenceType referencing a class, not an
043     * interface). If one of the types is a superclass of the other, the former is returned. If "this" is NULL, then t
044     * is returned. If t is NULL, then "this" is returned. If "this" equals t ['this.equals(t)'] "this" is returned. If
045     * "this" or t is an ArrayType, then {@link #OBJECT} is returned. If "this" or t is a ReferenceType referencing an
046     * interface, then {@link #OBJECT} is returned. If not all of the two classes' superclasses cannot be found, "null" is
047     * returned. See the JVM specification edition 2, "�4.9.2 The Bytecode Verifier".
048     *
049     * @deprecated Use getFirstCommonSuperclass(ReferenceType t) which has slightly changed semantics.
050     * @throws ClassNotFoundException on failure to find superclasses of this type, or the type passed as a parameter.
051     */
052    @Deprecated
053    public ReferenceType firstCommonSuperclass(final ReferenceType t) throws ClassNotFoundException {
054        if (equals(NULL)) {
055            return t;
056        }
057        if (t.equals(NULL) || equals(t)) {
058            return this;
059            /*
060             * TODO: Above sounds a little arbitrary. On the other hand, there is no object referenced by {@link #NULL} so we can also
061             * say all the objects referenced by {@link #NULL} were derived from {@link Object}. However, the Java Language's
062             * "instanceof" operator proves us wrong: "null" is not referring to an instance of {@link Object} :)
063             */
064        }
065        if (this instanceof ArrayType || t instanceof ArrayType) {
066            return OBJECT;
067            // TODO: Is there a proof of {@link #OBJECT} being the direct ancestor of every ArrayType?
068        }
069        return getFirstCommonSuperclassInternal(t);
070    }
071
072    /**
073     * This commutative operation returns the first common superclass (narrowest ReferenceType referencing a class, not an
074     * interface). If one of the types is a superclass of the other, the former is returned. If "this" is NULL, then t
075     * is returned. If t is NULL, then "this" is returned. If "this" equals t ['this.equals(t)'] "this" is returned. If
076     * "this" or t is an ArrayType, then {@link #OBJECT} is returned; unless their dimensions match. Then an ArrayType of the
077     * same number of dimensions is returned, with its basic type being the first common super class of the basic types of
078     * "this" and t. If "this" or t is a ReferenceType referencing an interface, then {@link #OBJECT} is returned. If not all of
079     * the two classes' superclasses cannot be found, "null" is returned. See the JVM specification edition 2, "�4.9.2 The
080     * Bytecode Verifier".
081     *
082     * @throws ClassNotFoundException on failure to find superclasses of this type, or the type passed as a parameter
083     */
084    public ReferenceType getFirstCommonSuperclass(final ReferenceType t) throws ClassNotFoundException {
085        if (equals(NULL)) {
086            return t;
087        }
088        if (t.equals(NULL) || equals(t)) {
089            return this;
090            /*
091             * TODO: Above sounds a little arbitrary. On the other hand, there is no object referenced by {@link #NULL} so we can also
092             * say all the objects referenced by {@link #NULL} were derived from {@link Object}. However, the Java Language's
093             * "instanceof" operator proves us wrong: "null" is not referring to an instance of {@link Object} :)
094             */
095        }
096        /* This code is from a bug report by Konstantin Shagin <konst@cs.technion.ac.il> */
097        if (this instanceof ArrayType && t instanceof ArrayType) {
098            final ArrayType arrType1 = (ArrayType) this;
099            final ArrayType arrType2 = (ArrayType) t;
100            if (arrType1.getDimensions() == arrType2.getDimensions() && arrType1.getBasicType() instanceof ObjectType
101                && arrType2.getBasicType() instanceof ObjectType) {
102                return new ArrayType(((ObjectType) arrType1.getBasicType()).getFirstCommonSuperclass((ObjectType) arrType2.getBasicType()),
103                    arrType1.getDimensions());
104            }
105        }
106        if (this instanceof ArrayType || t instanceof ArrayType) {
107            return OBJECT;
108            // TODO: Is there a proof of {@link #OBJECT} being the direct ancestor of every ArrayType?
109        }
110        return getFirstCommonSuperclassInternal(t);
111    }
112
113    private ReferenceType getFirstCommonSuperclassInternal(final ReferenceType t) throws ClassNotFoundException {
114        if (this instanceof ObjectType && ((ObjectType) this).referencesInterfaceExact()
115            || t instanceof ObjectType && ((ObjectType) t).referencesInterfaceExact()) {
116            return OBJECT;
117            // TODO: The above line is correct comparing to the vmspec2. But one could
118            // make class file verification a bit stronger here by using the notion of
119            // superinterfaces or even castability or assignment compatibility.
120        }
121        // this and t are ObjectTypes, see above.
122        final ObjectType thiz = (ObjectType) this;
123        final ObjectType other = (ObjectType) t;
124        final JavaClass[] thizSups = Repository.getSuperClasses(thiz.getClassName());
125        final JavaClass[] otherSups = Repository.getSuperClasses(other.getClassName());
126        if (thizSups == null || otherSups == null) {
127            return null;
128        }
129        // Waaahh...
130        final JavaClass[] thisSups = new JavaClass[thizSups.length + 1];
131        final JavaClass[] tSups = new JavaClass[otherSups.length + 1];
132        System.arraycopy(thizSups, 0, thisSups, 1, thizSups.length);
133        System.arraycopy(otherSups, 0, tSups, 1, otherSups.length);
134        thisSups[0] = Repository.lookupClass(thiz.getClassName());
135        tSups[0] = Repository.lookupClass(other.getClassName());
136        for (final JavaClass tSup : tSups) {
137            for (final JavaClass thisSup : thisSups) {
138                if (thisSup.equals(tSup)) {
139                    return ObjectType.getInstance(thisSup.getClassName());
140                }
141            }
142        }
143        // Huh? Did you ask for OBJECT's superclass??
144        return null;
145    }
146
147    /**
148     * Return true iff this is assignment compatible with another type t as defined in the JVM specification; see the
149     * AASTORE definition there.
150     *
151     * @throws ClassNotFoundException if any classes or interfaces required to determine assignment compatibility can't be
152     *         found
153     */
154    public boolean isAssignmentCompatibleWith(final Type t) throws ClassNotFoundException {
155        if (!(t instanceof ReferenceType)) {
156            return false;
157        }
158        final ReferenceType T = (ReferenceType) t;
159        if (equals(NULL)) {
160            return true; // This is not explicitly stated, but clear. Isn't it?
161        }
162        /*
163         * If this is a class type then
164         */
165        if (this instanceof ObjectType && ((ObjectType) this).referencesClassExact()) {
166            /*
167             * If T is a class type, then this must be the same class as T, or this must be a subclass of T;
168             */
169            if (T instanceof ObjectType && ((ObjectType) T).referencesClassExact()
170                && (equals(T) || Repository.instanceOf(((ObjectType) this).getClassName(), ((ObjectType) T).getClassName()))) {
171                return true;
172            }
173            /*
174             * If T is an interface type, this must implement interface T.
175             */
176            if (T instanceof ObjectType && ((ObjectType) T).referencesInterfaceExact()
177                && Repository.implementationOf(((ObjectType) this).getClassName(), ((ObjectType) T).getClassName())) {
178                return true;
179            }
180        }
181        /*
182         * If this is an interface type, then:
183         */
184        if (this instanceof ObjectType && ((ObjectType) this).referencesInterfaceExact()) {
185            /*
186             * If T is a class type, then T must be Object (�2.4.7).
187             */
188            if (T instanceof ObjectType && ((ObjectType) T).referencesClassExact() && T.equals(OBJECT)) {
189                return true;
190            }
191            /*
192             * If T is an interface type, then T must be the same interface as this or a superinterface of this (�2.13.2).
193             */
194            if (T instanceof ObjectType && ((ObjectType) T).referencesInterfaceExact()
195                && (equals(T) || Repository.implementationOf(((ObjectType) this).getClassName(), ((ObjectType) T).getClassName()))) {
196                return true;
197            }
198        }
199        /*
200         * If this is an array type, namely, the type SC[], that is, an array of components of type SC, then:
201         */
202        if (this instanceof ArrayType) {
203            /*
204             * If T is a class type, then T must be Object (�2.4.7).
205             */
206            if (T instanceof ObjectType && ((ObjectType) T).referencesClassExact() && T.equals(OBJECT)) {
207                return true;
208            }
209            /*
210             * If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
211             */
212            if (T instanceof ArrayType) {
213                /*
214                 * TC and SC are the same primitive type (�2.4.1).
215                 */
216                final Type sc = ((ArrayType) this).getElementType();
217                final Type tc = ((ArrayType) T).getElementType();
218                if (sc instanceof BasicType && tc instanceof BasicType && sc.equals(tc)) {
219                    return true;
220                }
221                /*
222                 * TC and SC are reference types (�2.4.6), and type SC is assignable to TC by these runtime rules.
223                 */
224                if (tc instanceof ReferenceType && sc instanceof ReferenceType && ((ReferenceType) sc).isAssignmentCompatibleWith(tc)) {
225                    return true;
226                }
227            }
228            /* If T is an interface type, T must be one of the interfaces implemented by arrays (�2.15). */
229            // TODO: Check if this is still valid or find a way to dynamically find out which
230            // interfaces arrays implement. However, as of the JVM specification edition 2, there
231            // are at least two different pages where assignment compatibility is defined and
232            // on one of them "interfaces implemented by arrays" is exchanged with "'Cloneable' or
233            // 'java.io.Serializable'"
234            if (T instanceof ObjectType && ((ObjectType) T).referencesInterfaceExact()) {
235                for (final String element : Const.getInterfacesImplementedByArrays()) {
236                    if (T.equals(ObjectType.getInstance(element))) {
237                        return true;
238                    }
239                }
240            }
241        }
242        return false; // default.
243    }
244
245    /**
246     * Return true iff this type is castable to another type t as defined in the JVM specification. The case where this is
247     * {@link #NULL} is not defined (see the CHECKCAST definition in the JVM specification). However, because for example CHECKCAST
248     * doesn't throw a ClassCastException when casting a null reference to any Object, true is returned in this case.
249     *
250     * @throws ClassNotFoundException if any classes or interfaces required to determine assignment compatibility can't be
251     *         found
252     */
253    public boolean isCastableTo(final Type t) throws ClassNotFoundException {
254        if (equals(NULL)) {
255            return t instanceof ReferenceType; // If this is ever changed in isAssignmentCompatible()
256        }
257        return isAssignmentCompatibleWith(t);
258        /*
259         * Yes, it's true: It's the same definition. See vmspec2 AASTORE / CHECKCAST definitions.
260         */
261    }
262}