001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.lang.types;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.annotations.Nullable;
021    import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
022    
023    import java.util.Iterator;
024    import java.util.List;
025    
026    public abstract class AbstractJetType implements JetType {
027        @Nullable
028        @Override
029        public <T extends TypeCapability> T getCapability(@NotNull Class<T> capabilityClass) {
030            if (capabilityClass.isInstance(this)) {
031                //noinspection unchecked
032                return (T) this;
033            }
034            return null;
035        }
036    
037        @Override
038        public final int hashCode() {
039            int result = getConstructor().hashCode();
040            result = 31 * result + getArguments().hashCode();
041            result = 31 * result + (isNullable() ? 1 : 0);
042            return result;
043        }
044    
045        @Override
046        public final boolean equals(Object obj) {
047            if (this == obj) return true;
048            if (!(obj instanceof JetType)) return false;
049    
050            JetType type = (JetType) obj;
051    
052            return isNullable() == type.isNullable() && JetTypeChecker.DEFAULT.equalTypes(this, type);
053        }
054    
055        @Override
056        public String toString() {
057            List<TypeProjection> arguments = getArguments();
058            return getConstructor() + (arguments.isEmpty() ? "" : "<" + argumentsToString(arguments) + ">") + (isNullable() ? "?" : "");
059        }
060    
061        private static StringBuilder argumentsToString(List<TypeProjection> arguments) {
062            StringBuilder stringBuilder = new StringBuilder();
063            for (Iterator<TypeProjection> iterator = arguments.iterator(); iterator.hasNext();) {
064                TypeProjection argument = iterator.next();
065                stringBuilder.append(argument);
066                if (iterator.hasNext()) {
067                    stringBuilder.append(", ");
068                }
069            }
070            return stringBuilder;
071        }
072    }