001    /*
002     * Copyright 2010-2015 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.kotlin.types;
018    
019    import com.google.common.base.Function;
020    import com.google.common.collect.Collections2;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.kotlin.descriptors.CallableDescriptor;
023    import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
024    import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
025    import org.jetbrains.kotlin.utils.DFS;
026    
027    import java.util.Collections;
028    import java.util.HashMap;
029    import java.util.List;
030    import java.util.Map;
031    
032    public class BoundsSubstitutor {
033        private static final Function<TypeProjection,KotlinType> PROJECTIONS_TO_TYPES = new Function<TypeProjection, KotlinType>() {
034            @Override
035            public KotlinType apply(TypeProjection projection) {
036                return projection.getType();
037            }
038        };
039    
040        private BoundsSubstitutor() {
041        }
042    
043        @NotNull
044        public static <D extends CallableDescriptor> D substituteBounds(@NotNull D functionDescriptor) {
045            List<TypeParameterDescriptor> typeParameters = functionDescriptor.getTypeParameters();
046            if (typeParameters.isEmpty()) return functionDescriptor;
047    
048            // TODO: this does not handle any recursion in the bounds
049            @SuppressWarnings("unchecked")
050            D substitutedFunction = (D) functionDescriptor.substitute(createUpperBoundsSubstitutor(typeParameters));
051            assert substitutedFunction != null : "Substituting upper bounds should always be legal";
052    
053            return substitutedFunction;
054        }
055    
056        @NotNull
057        private static TypeSubstitutor createUpperBoundsSubstitutor(@NotNull List<TypeParameterDescriptor> typeParameters) {
058            Map<TypeConstructor, TypeProjection> mutableSubstitution = new HashMap<TypeConstructor, TypeProjection>();
059            TypeSubstitutor substitutor = TypeSubstitutor.create(mutableSubstitution);
060    
061            // todo assert: no loops
062            for (TypeParameterDescriptor descriptor : topologicallySortTypeParameters(typeParameters)) {
063                KotlinType upperBoundsAsType = TypeIntersector.getUpperBoundsAsType(descriptor);
064                KotlinType substitutedUpperBoundsAsType = substitutor.substitute(upperBoundsAsType, Variance.INVARIANT);
065                mutableSubstitution.put(descriptor.getTypeConstructor(), new TypeProjectionImpl(substitutedUpperBoundsAsType));
066            }
067    
068            return substitutor;
069        }
070    
071        @NotNull
072        private static List<TypeParameterDescriptor> topologicallySortTypeParameters(@NotNull final List<TypeParameterDescriptor> typeParameters) {
073            // In the end, we want every parameter to have no references to those after it in the list
074            // This gives us the reversed order: the one that refers to everybody else comes first
075            List<TypeParameterDescriptor> topOrder = DFS.topologicalOrder(
076                    typeParameters,
077                    new DFS.Neighbors<TypeParameterDescriptor>() {
078                        @NotNull
079                        @Override
080                        public Iterable<TypeParameterDescriptor> getNeighbors(TypeParameterDescriptor current) {
081                            return getTypeParametersFromUpperBounds(current, typeParameters);
082                        }
083                    });
084    
085            assert topOrder.size() == typeParameters.size() : "All type parameters must be visited, but only " + topOrder + " were";
086    
087            // Now, the one that refers to everybody else stands in the last position
088            Collections.reverse(topOrder);
089            return topOrder;
090        }
091    
092        @NotNull
093        private static List<TypeParameterDescriptor> getTypeParametersFromUpperBounds(
094                @NotNull TypeParameterDescriptor current,
095                @NotNull final List<TypeParameterDescriptor> typeParameters
096        ) {
097            return DFS.dfs(
098                    current.getUpperBounds(),
099                    new DFS.Neighbors<KotlinType>() {
100                        @NotNull
101                        @Override
102                        public Iterable<KotlinType> getNeighbors(KotlinType current) {
103                            return Collections2.transform(current.getArguments(), PROJECTIONS_TO_TYPES);
104                        }
105                    },
106                    new DFS.NodeHandlerWithListResult<KotlinType, TypeParameterDescriptor>() {
107                        @Override
108                        public boolean beforeChildren(KotlinType current) {
109                            ClassifierDescriptor declarationDescriptor = current.getConstructor().getDeclarationDescriptor();
110                            // typeParameters in a list, but it contains very few elements, so it's fine to call contains() on it
111                            //noinspection SuspiciousMethodCalls
112                            if (typeParameters.contains(declarationDescriptor)) {
113                                result.add((TypeParameterDescriptor) declarationDescriptor);
114                            }
115    
116                            return true;
117                        }
118                    }
119            );
120        }
121    }