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.resolve.jvm.kotlinSignature;
018    
019    import com.google.common.collect.Lists;
020    import com.google.common.collect.Multimap;
021    import com.google.common.collect.Sets;
022    import com.intellij.util.Function;
023    import com.intellij.util.containers.ContainerUtil;
024    import kotlin.Function1;
025    import kotlin.KotlinPackage;
026    import org.jetbrains.annotations.NotNull;
027    import org.jetbrains.annotations.Nullable;
028    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
029    import org.jetbrains.kotlin.descriptors.*;
030    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
031    import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl;
032    import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl;
033    import org.jetbrains.kotlin.load.java.components.TypeUsage;
034    import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor;
035    import org.jetbrains.kotlin.load.java.structure.JavaMethod;
036    import org.jetbrains.kotlin.name.FqNameUnsafe;
037    import org.jetbrains.kotlin.name.Name;
038    import org.jetbrains.kotlin.renderer.DescriptorRenderer;
039    import org.jetbrains.kotlin.resolve.DescriptorUtils;
040    import org.jetbrains.kotlin.resolve.jvm.JavaResolverUtils;
041    import org.jetbrains.kotlin.resolve.jvm.JvmPackage;
042    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
043    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmSignaturePackage;
044    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.KotlinToJvmSignatureMapper;
045    import org.jetbrains.kotlin.resolve.scopes.JetScope;
046    import org.jetbrains.kotlin.types.*;
047    
048    import java.util.*;
049    
050    import static org.jetbrains.kotlin.load.java.components.TypeUsage.*;
051    import static org.jetbrains.kotlin.resolve.DescriptorUtils.getFqName;
052    import static org.jetbrains.kotlin.types.Variance.INVARIANT;
053    
054    public class SignaturesPropagationData {
055    
056        private static final KotlinToJvmSignatureMapper SIGNATURE_MAPPER = ServiceLoader.load(
057                KotlinToJvmSignatureMapper.class,
058                KotlinToJvmSignatureMapper.class.getClassLoader()
059        ).iterator().next();
060    
061        private final JavaMethodDescriptor autoMethodDescriptor;
062    
063        private final List<TypeParameterDescriptor> modifiedTypeParameters;
064        private final ValueParameters modifiedValueParameters;
065    
066        private final JetType modifiedReturnType;
067        private final List<String> signatureErrors = Lists.newArrayList();
068        private final List<FunctionDescriptor> superFunctions;
069        private final Map<TypeParameterDescriptor, TypeParameterDescriptorImpl> autoTypeParameterToModified;
070        final ClassDescriptor containingClass;
071    
072        public SignaturesPropagationData(
073                @NotNull ClassDescriptor containingClass,
074                @NotNull JetType autoReturnType, // type built by JavaTypeTransformer from Java signature and @NotNull annotations
075                @Nullable JetType receiverType,
076                @NotNull List<ValueParameterDescriptor> autoValueParameters, // descriptors built by parameters resolver
077                @NotNull List<TypeParameterDescriptor> autoTypeParameters, // descriptors built by signature resolver
078                @NotNull JavaMethod method
079        ) {
080            this.containingClass = containingClass;
081    
082            autoMethodDescriptor =
083                    createAutoMethodDescriptor(containingClass, method, autoReturnType, receiverType, autoValueParameters, autoTypeParameters);
084    
085            superFunctions = getSuperFunctionsForMethod(method, autoMethodDescriptor, containingClass);
086    
087            autoTypeParameterToModified = JavaResolverUtils.recreateTypeParametersAndReturnMapping(autoTypeParameters, null);
088    
089            modifiedTypeParameters = modifyTypeParametersAccordingToSuperMethods(autoTypeParameters);
090            modifiedReturnType = modifyReturnTypeAccordingToSuperMethods(autoReturnType);
091            modifiedValueParameters = modifyValueParametersAccordingToSuperMethods(receiverType, autoValueParameters);
092        }
093    
094        @NotNull
095        private static JavaMethodDescriptor createAutoMethodDescriptor(
096                @NotNull ClassDescriptor containingClass,
097                @NotNull JavaMethod method, JetType autoReturnType,
098                @Nullable JetType receiverType,
099                @NotNull List<ValueParameterDescriptor> autoValueParameters,
100                @NotNull List<TypeParameterDescriptor> autoTypeParameters
101        ) {
102            JavaMethodDescriptor autoMethodDescriptor = JavaMethodDescriptor.createJavaMethod(
103                    containingClass,
104                    Annotations.EMPTY,
105                    method.getName(),
106                    //TODO: what to do?
107                    SourceElement.NO_SOURCE
108            );
109            autoMethodDescriptor.initialize(
110                    receiverType,
111                    containingClass.getThisAsReceiverParameter(),
112                    autoTypeParameters,
113                    autoValueParameters,
114                    autoReturnType,
115                    Modality.OPEN,
116                    Visibilities.PUBLIC
117            );
118            return autoMethodDescriptor;
119        }
120    
121        public List<TypeParameterDescriptor> getModifiedTypeParameters() {
122            return modifiedTypeParameters;
123        }
124    
125        public JetType getModifiedReceiverType() {
126            return modifiedValueParameters.receiverType;
127        }
128    
129        public List<ValueParameterDescriptor> getModifiedValueParameters() {
130            return modifiedValueParameters.descriptors;
131        }
132    
133        public boolean getModifiedHasStableParameterNames() {
134            return modifiedValueParameters.hasStableParameterNames;
135        }
136    
137        public JetType getModifiedReturnType() {
138            return modifiedReturnType;
139        }
140    
141        public List<String> getSignatureErrors() {
142            return signatureErrors;
143        }
144    
145        public List<FunctionDescriptor> getSuperFunctions() {
146            return superFunctions;
147        }
148    
149        void reportError(String error) {
150            signatureErrors.add(error);
151        }
152    
153        private JetType modifyReturnTypeAccordingToSuperMethods(
154                @NotNull JetType autoType // type built by JavaTypeTransformer
155        ) {
156            if (JvmPackage.getPLATFORM_TYPES()) return autoType;
157    
158            List<TypeAndVariance> typesFromSuperMethods = ContainerUtil.map(superFunctions,
159                    new Function<FunctionDescriptor, TypeAndVariance>() {
160                        @Override
161                        public TypeAndVariance fun(FunctionDescriptor superFunction) {
162                            return new TypeAndVariance(superFunction.getReturnType(), Variance.OUT_VARIANCE);
163                        }
164                    });
165    
166            return modifyTypeAccordingToSuperMethods(autoType, typesFromSuperMethods, MEMBER_SIGNATURE_COVARIANT);
167        }
168    
169        private List<TypeParameterDescriptor> modifyTypeParametersAccordingToSuperMethods(List<TypeParameterDescriptor> autoTypeParameters) {
170            if (JvmPackage.getPLATFORM_TYPES()) return autoTypeParameters;
171    
172            List<TypeParameterDescriptor> result = Lists.newArrayList();
173    
174            for (TypeParameterDescriptor autoParameter : autoTypeParameters) {
175                int index = autoParameter.getIndex();
176                TypeParameterDescriptorImpl modifiedTypeParameter = autoTypeParameterToModified.get(autoParameter);
177    
178                List<Iterator<JetType>> upperBoundFromSuperFunctionsIterators = Lists.newArrayList();
179                for (FunctionDescriptor superFunction : superFunctions) {
180                    upperBoundFromSuperFunctionsIterators.add(superFunction.getTypeParameters().get(index).getUpperBounds().iterator());
181                }
182    
183                for (JetType autoUpperBound : autoParameter.getUpperBounds()) {
184                    List<TypeAndVariance> upperBoundsFromSuperFunctions = Lists.newArrayList();
185    
186                    for (Iterator<JetType> iterator : upperBoundFromSuperFunctionsIterators) {
187                        assert iterator.hasNext();
188                        upperBoundsFromSuperFunctions.add(new TypeAndVariance(iterator.next(), INVARIANT));
189                    }
190    
191                    JetType modifiedUpperBound = modifyTypeAccordingToSuperMethods(autoUpperBound, upperBoundsFromSuperFunctions, UPPER_BOUND);
192                    modifiedTypeParameter.addUpperBound(modifiedUpperBound);
193                }
194    
195                for (Iterator<JetType> iterator : upperBoundFromSuperFunctionsIterators) {
196                    assert !iterator.hasNext();
197                }
198    
199                modifiedTypeParameter.setInitialized();
200                result.add(modifiedTypeParameter);
201            }
202    
203            return result;
204        }
205    
206        private ValueParameters modifyValueParametersAccordingToSuperMethods(
207                @Nullable JetType receiverType,
208                @NotNull List<ValueParameterDescriptor> parameters // descriptors built by parameters resolver
209        ) {
210            assert receiverType == null : "Parameters before propagation have receiver type," +
211                                          " but propagation should be disabled for functions compiled from Kotlin in class: " +
212                                          DescriptorUtils.getFqName(containingClass);
213    
214            JetType resultReceiverType = null;
215            List<ValueParameterDescriptor> resultParameters = Lists.newArrayList();
216    
217            boolean shouldBeExtension = checkIfShouldBeExtension();
218    
219            for (final ValueParameterDescriptor originalParam : parameters) {
220                final int originalIndex = originalParam.getIndex();
221                List<TypeAndName> typesFromSuperMethods = ContainerUtil.map(superFunctions,
222                        new Function<FunctionDescriptor, TypeAndName>() {
223                            @Override
224                            public TypeAndName fun(FunctionDescriptor superFunction) {
225                                ReceiverParameterDescriptor receiver = superFunction.getExtensionReceiverParameter();
226                                int index = receiver != null ? originalIndex - 1 : originalIndex;
227                                if (index == -1) {
228                                    assert receiver != null : "can't happen: index is -1, while function is not extension";
229                                    return new TypeAndName(receiver.getType(), originalParam.getName());
230                                }
231                                ValueParameterDescriptor parameter = superFunction.getValueParameters().get(index);
232                                return new TypeAndName(parameter.getType(), parameter.getName());
233                            }
234                        });
235    
236                VarargCheckResult varargCheckResult = checkVarargInSuperFunctions(originalParam);
237    
238                JetType altType = modifyTypeAccordingToSuperMethods(varargCheckResult.parameterType,
239                                                                    convertToTypeVarianceList(typesFromSuperMethods),
240                                                                    MEMBER_SIGNATURE_CONTRAVARIANT);
241    
242                if (shouldBeExtension && originalIndex == 0) {
243                    resultReceiverType = altType;
244                }
245                else {
246                    Name stableName = null;
247                    for (int i = 0; i < superFunctions.size(); i++) {
248                        if (superFunctions.get(i).hasStableParameterNames()) {
249                            // When there's more than one stable name in super functions, we pick the first one. This behaviour is similar to
250                            // the compiler front-end, except that it reports a warning in such cases
251                            // TODO: report a warning somewhere if there's more than one stable name in super functions
252                            stableName = typesFromSuperMethods.get(i).name;
253                            break;
254                        }
255                    }
256    
257                    resultParameters.add(new ValueParameterDescriptorImpl(
258                            originalParam.getContainingDeclaration(),
259                            null,
260                            shouldBeExtension ? originalIndex - 1 : originalIndex,
261                            originalParam.getAnnotations(),
262                            stableName != null ? stableName : originalParam.getName(),
263                            altType,
264                            originalParam.declaresDefaultValue(),
265                            varargCheckResult.isVararg ? KotlinBuiltIns.getInstance().getArrayElementType(altType) : null,
266                            SourceElement.NO_SOURCE
267                    ));
268                }
269            }
270    
271            boolean hasStableParameterNames = KotlinPackage.any(superFunctions, new Function1<FunctionDescriptor, Boolean>() {
272                @Override
273                public Boolean invoke(FunctionDescriptor descriptor) {
274                    return descriptor.hasStableParameterNames();
275                }
276            });
277    
278            return new ValueParameters(resultReceiverType, resultParameters, hasStableParameterNames);
279        }
280    
281        @NotNull
282        private static List<TypeAndVariance> convertToTypeVarianceList(@NotNull List<TypeAndName> list) {
283            return KotlinPackage.map(list, new Function1<TypeAndName, TypeAndVariance>() {
284                @Override
285                public TypeAndVariance invoke(TypeAndName tvn) {
286                    return new TypeAndVariance(tvn.type, INVARIANT);
287                }
288            });
289        }
290    
291        private static List<FunctionDescriptor> getSuperFunctionsForMethod(
292                @NotNull JavaMethod method,
293                @NotNull JavaMethodDescriptor autoMethodDescriptor,
294                @NotNull ClassDescriptor containingClass
295        ) {
296            List<FunctionDescriptor> superFunctions = Lists.newArrayList();
297    
298            // TODO: Add propagation for other kotlin descriptors (KT-3621)
299            Name name = method.getName();
300            JvmMethodSignature autoSignature = SIGNATURE_MAPPER.mapToJvmMethodSignature(autoMethodDescriptor);
301            for (JetType supertype : containingClass.getTypeConstructor().getSupertypes()) {
302                Collection<FunctionDescriptor> superFunctionCandidates = supertype.getMemberScope().getFunctions(name);
303                for (FunctionDescriptor candidate : superFunctionCandidates) {
304                    JvmMethodSignature candidateSignature = SIGNATURE_MAPPER.mapToJvmMethodSignature(candidate);
305                    if (JvmSignaturePackage.erasedSignaturesEqualIgnoringReturnTypes(autoSignature, candidateSignature)) {
306                        superFunctions.add(candidate);
307                    }
308                }
309            }
310    
311            // sorting for diagnostic stability
312            Collections.sort(superFunctions, new Comparator<FunctionDescriptor>() {
313                @Override
314                public int compare(@NotNull FunctionDescriptor fun1, @NotNull FunctionDescriptor fun2) {
315                    FqNameUnsafe fqName1 = getFqName(fun1.getContainingDeclaration());
316                    FqNameUnsafe fqName2 = getFqName(fun2.getContainingDeclaration());
317                    return fqName1.asString().compareTo(fqName2.asString());
318                }
319            });
320            return superFunctions;
321        }
322    
323        private boolean checkIfShouldBeExtension() {
324            boolean someSupersExtension = false;
325            boolean someSupersNotExtension = false;
326    
327            for (FunctionDescriptor superFunction : superFunctions) {
328                if (superFunction.getExtensionReceiverParameter() != null)  {
329                    someSupersExtension = true;
330                }
331                else {
332                    someSupersNotExtension = true;
333                }
334            }
335    
336            if (someSupersExtension) {
337                if (someSupersNotExtension) {
338                    reportError("Incompatible super methods: some are extension functions, some are not");
339                }
340                else {
341                    return true;
342                }
343            }
344            return false;
345        }
346    
347        @NotNull
348        private VarargCheckResult checkVarargInSuperFunctions(@NotNull ValueParameterDescriptor originalParam) {
349            boolean someSupersVararg = false;
350            boolean someSupersNotVararg = false;
351            for (FunctionDescriptor superFunction : superFunctions) {
352                int originalIndex = originalParam.getIndex();
353                int index = superFunction.getExtensionReceiverParameter() != null ? originalIndex - 1 : originalIndex;
354                if (index != -1 && superFunction.getValueParameters().get(index).getVarargElementType() != null) {
355                    someSupersVararg = true;
356                }
357                else {
358                    someSupersNotVararg = true;
359                }
360            }
361    
362            JetType originalVarargElementType = originalParam.getVarargElementType();
363            JetType originalType = originalParam.getType();
364    
365            if (someSupersVararg && someSupersNotVararg) {
366                reportError("Incompatible super methods: some have vararg parameter, some have not");
367                return new VarargCheckResult(originalType, originalVarargElementType != null);
368            }
369    
370            if (someSupersVararg && originalVarargElementType == null) {
371                // convert to vararg
372    
373                assert isArrayType(originalType);
374                return new VarargCheckResult(TypeUtils.makeNotNullable(originalType), true);
375            }
376            else if (someSupersNotVararg && originalVarargElementType != null) {
377                // convert to non-vararg
378    
379                assert isArrayType(originalType);
380                return new VarargCheckResult(TypeUtils.makeNullable(originalType), false);
381            }
382            return new VarargCheckResult(originalType, originalVarargElementType != null);
383        }
384    
385        @NotNull
386        private JetType modifyTypeAccordingToSuperMethods(
387                @NotNull JetType autoType,
388                @NotNull List<TypeAndVariance> typesFromSuper,
389                @NotNull TypeUsage howThisTypeIsUsed
390        ) {
391            if (autoType.isError()) return autoType;
392    
393            if (JvmPackage.getPLATFORM_TYPES()) return autoType;
394    
395            boolean resultNullable = typeMustBeNullable(autoType, typesFromSuper, howThisTypeIsUsed);
396            ClassifierDescriptor resultClassifier = modifyTypeClassifier(autoType, typesFromSuper);
397            List<TypeProjection> resultArguments = getTypeArgsOfType(autoType, resultClassifier, typesFromSuper);
398            JetScope resultScope;
399            if (resultClassifier instanceof ClassDescriptor) {
400                resultScope = ((ClassDescriptor) resultClassifier).getMemberScope(resultArguments);
401            }
402            else {
403                resultScope = autoType.getMemberScope();
404            }
405    
406            JetTypeImpl type = new JetTypeImpl(autoType.getAnnotations(),
407                                               resultClassifier.getTypeConstructor(),
408                                               resultNullable,
409                                               resultArguments,
410                                               resultScope);
411    
412            PropagationHeuristics.checkArrayInReturnType(this, type, typesFromSuper);
413            return type;
414        }
415    
416        @NotNull
417        private List<TypeProjection> getTypeArgsOfType(
418                @NotNull JetType autoType,
419                @NotNull ClassifierDescriptor classifier,
420                @NotNull List<TypeAndVariance> typesFromSuper
421        ) {
422            if (typesFromSuper.isEmpty()) return autoType.getArguments();
423    
424            List<TypeProjection> autoArguments = autoType.getArguments();
425    
426            if (!(classifier instanceof ClassDescriptor)) {
427                assert autoArguments.isEmpty() :
428                        "Unexpected type arguments when type constructor is not ClassDescriptor, type = " + autoType +
429                        ", classifier = " + classifier + ", classifier class = " + classifier.getClass();
430                return autoArguments;
431            }
432    
433            List<List<TypeProjectionAndVariance>> typeArgumentsFromSuper = calculateTypeArgumentsFromSuper((ClassDescriptor) classifier,
434                                                                                                           typesFromSuper);
435    
436            // Modify type arguments using info from typesFromSuper
437            List<TypeProjection> resultArguments = Lists.newArrayList();
438            for (TypeParameterDescriptor parameter : classifier.getTypeConstructor().getParameters()) {
439                TypeProjection argument = autoArguments.get(parameter.getIndex());
440    
441                JetType argumentType = argument.getType();
442                List<TypeProjectionAndVariance> projectionsFromSuper = typeArgumentsFromSuper.get(parameter.getIndex());
443                List<TypeAndVariance> argTypesFromSuper = getTypes(projectionsFromSuper);
444    
445                JetType type = modifyTypeAccordingToSuperMethods(argumentType, argTypesFromSuper, TYPE_ARGUMENT);
446                Variance projectionKind = calculateArgumentProjectionKindFromSuper(argument, projectionsFromSuper);
447    
448                resultArguments.add(new TypeProjectionImpl(projectionKind, type));
449            }
450            return resultArguments;
451        }
452    
453        private Variance calculateArgumentProjectionKindFromSuper(
454                @NotNull TypeProjection argument,
455                @NotNull List<TypeProjectionAndVariance> projectionsFromSuper
456        ) {
457            if (projectionsFromSuper.isEmpty()) return argument.getProjectionKind();
458    
459            Set<Variance> projectionKindsInSuper = Sets.newLinkedHashSet();
460            for (TypeProjectionAndVariance projectionAndVariance : projectionsFromSuper) {
461                projectionKindsInSuper.add(projectionAndVariance.typeProjection.getProjectionKind());
462            }
463    
464            Variance defaultProjectionKind = argument.getProjectionKind();
465            if (projectionKindsInSuper.size() == 0) {
466                return defaultProjectionKind;
467            }
468            else if (projectionKindsInSuper.size() == 1) {
469                Variance projectionKindInSuper = projectionKindsInSuper.iterator().next();
470                if (defaultProjectionKind == INVARIANT || defaultProjectionKind == projectionKindInSuper) {
471                    return projectionKindInSuper;
472                }
473                else {
474                    reportError("Incompatible projection kinds in type arguments of super methods' return types: "
475                                + projectionsFromSuper + ", defined in current: " + argument);
476                    return defaultProjectionKind;
477                }
478            }
479            else {
480                reportError("Incompatible projection kinds in type arguments of super methods' return types: " + projectionsFromSuper);
481                return defaultProjectionKind;
482            }
483        }
484    
485        @NotNull
486        private static List<TypeAndVariance> getTypes(@NotNull List<TypeProjectionAndVariance> projections) {
487            List<TypeAndVariance> types = Lists.newArrayList();
488            for (TypeProjectionAndVariance projection : projections) {
489                types.add(new TypeAndVariance(projection.typeProjection.getType(),
490                                              merge(projection.varianceOfPosition, projection.typeProjection.getProjectionKind())));
491            }
492            return types;
493        }
494    
495        private static Variance merge(Variance positionOfOuter, Variance projectionKind) {
496            // Inv<Inv<out X>>, X is in invariant position
497            if (positionOfOuter == INVARIANT) return INVARIANT;
498            // Out<X>, X is in out-position
499            if (projectionKind == INVARIANT) return positionOfOuter;
500            // Out<Out<X>>, X is in out-position
501            // In<In<X>>, X is in out-position
502            // Out<In<X>>, X is in in-position
503            // In<Out<X>>, X is in in-position
504            return positionOfOuter.superpose(projectionKind);
505        }
506    
507        // Returns list with type arguments info from supertypes
508        // Example:
509        //     - Foo<A, B> is a subtype of Bar<A, List<B>>, Baz<Boolean, A>
510        //     - input: klass = Foo, typesFromSuper = [Bar<String, List<Int>>, Baz<Boolean, CharSequence>]
511        //     - output[0] = [String, CharSequence], output[1] = []
512        private static List<List<TypeProjectionAndVariance>> calculateTypeArgumentsFromSuper(
513                @NotNull ClassDescriptor klass,
514                @NotNull Collection<TypeAndVariance> typesFromSuper
515        ) {
516            // For each superclass of klass and its parameters, hold their mapping to klass' parameters
517            // #0 of Bar ->  A
518            // #1 of Bar ->  List<B>
519            // #0 of Baz ->  Boolean
520            // #1 of Baz ->  A
521            // #0 of Foo ->  A (mapped to itself)
522            // #1 of Foo ->  B (mapped to itself)
523            Multimap<TypeConstructor, TypeProjection> substitution = SubstitutionUtils.buildDeepSubstitutionMultimap(
524                    TypeUtils.makeUnsubstitutedType(klass, ErrorUtils.createErrorScope("Do not access this scope", true)));
525    
526            // for each parameter of klass, hold arguments in corresponding supertypes
527            List<List<TypeProjectionAndVariance>> parameterToArgumentsFromSuper = Lists.newArrayList();
528            for (TypeParameterDescriptor ignored : klass.getTypeConstructor().getParameters()) {
529                parameterToArgumentsFromSuper.add(new ArrayList<TypeProjectionAndVariance>());
530            }
531    
532            // Enumerate all types from super and all its parameters
533            for (TypeAndVariance typeFromSuper : typesFromSuper) {
534                for (TypeParameterDescriptor parameter : typeFromSuper.type.getConstructor().getParameters()) {
535                    TypeProjection argument = typeFromSuper.type.getArguments().get(parameter.getIndex());
536    
537                    // for given example, this block is executed four times:
538                    // 1. typeFromSuper = Bar<String, List<Int>>,      parameter = "#0 of Bar",  argument = String
539                    // 2. typeFromSuper = Bar<String, List<Int>>,      parameter = "#1 of Bar",  argument = List<Int>
540                    // 3. typeFromSuper = Baz<Boolean, CharSequence>,  parameter = "#0 of Baz",  argument = Boolean
541                    // 4. typeFromSuper = Baz<Boolean, CharSequence>,  parameter = "#1 of Baz",  argument = CharSequence
542    
543                    // if it is mapped to klass' parameter, then store it into map
544                    for (TypeProjection projection : substitution.get(parameter.getTypeConstructor())) {
545                        // 1. projection = A
546                        // 2. projection = List<B>
547                        // 3. projection = Boolean
548                        // 4. projection = A
549                        ClassifierDescriptor classifier = projection.getType().getConstructor().getDeclarationDescriptor();
550    
551                        // this condition is true for 1 and 4, false for 2 and 3
552                        if (classifier instanceof TypeParameterDescriptor && classifier.getContainingDeclaration() == klass) {
553                            int parameterIndex = ((TypeParameterDescriptor) classifier).getIndex();
554                            Variance effectiveVariance = parameter.getVariance().superpose(typeFromSuper.varianceOfPosition);
555                            parameterToArgumentsFromSuper.get(parameterIndex).add(new TypeProjectionAndVariance(argument, effectiveVariance));
556                        }
557                    }
558                }
559            }
560            return parameterToArgumentsFromSuper;
561        }
562    
563        private boolean typeMustBeNullable(
564                @NotNull JetType autoType,
565                @NotNull List<TypeAndVariance> typesFromSuper,
566                @NotNull TypeUsage howThisTypeIsUsed
567        ) {
568            boolean someSupersNotCovariantNullable = false;
569            boolean someSupersCovariantNullable = false;
570            boolean someSupersNotNull = false;
571            for (TypeAndVariance typeFromSuper : typesFromSuper) {
572                if (!TypeUtils.isNullableType(typeFromSuper.type)) {
573                    someSupersNotNull = true;
574                }
575                else {
576                    if (typeFromSuper.varianceOfPosition == Variance.OUT_VARIANCE) {
577                        someSupersCovariantNullable = true;
578                    }
579                    else {
580                        someSupersNotCovariantNullable = true;
581                    }
582                }
583            }
584    
585            if (someSupersNotNull && someSupersNotCovariantNullable) {
586                reportError("Incompatible types in superclasses: " + typesFromSuper);
587                return TypeUtils.isNullableType(autoType);
588            }
589            else if (someSupersNotNull) {
590                return false;
591            }
592            else if (someSupersNotCovariantNullable || someSupersCovariantNullable) {
593                boolean annotatedAsNotNull = howThisTypeIsUsed != TYPE_ARGUMENT && !TypeUtils.isNullableType(autoType);
594    
595                if (annotatedAsNotNull && someSupersNotCovariantNullable) {
596                    DescriptorRenderer renderer = DescriptorRenderer.SHORT_NAMES_IN_TYPES;
597                    reportError("In superclass type is nullable: " + typesFromSuper + ", in subclass it is not: " + renderer.renderType(autoType));
598                    return true;
599                }
600    
601                return !annotatedAsNotNull;
602            }
603            return TypeUtils.isNullableType(autoType);
604        }
605    
606        @NotNull
607        private ClassifierDescriptor modifyTypeClassifier(
608                @NotNull JetType autoType,
609                @NotNull List<TypeAndVariance> typesFromSuper
610        ) {
611            ClassifierDescriptor classifier = autoType.getConstructor().getDeclarationDescriptor();
612            if (!(classifier instanceof ClassDescriptor)) {
613                assert classifier != null : "no declaration descriptor for type " + autoType + ", auto method descriptor: " + autoMethodDescriptor;
614    
615                if (classifier instanceof TypeParameterDescriptor && autoTypeParameterToModified.containsKey(classifier)) {
616                    return autoTypeParameterToModified.get(classifier);
617                }
618                return classifier;
619            }
620            ClassDescriptor klass = (ClassDescriptor) classifier;
621    
622            CollectionClassMapping collectionMapping = CollectionClassMapping.getInstance();
623    
624            boolean someSupersMutable = false;
625            boolean someSupersCovariantReadOnly = false;
626            boolean someSupersNotCovariantReadOnly = false;
627            for (TypeAndVariance typeFromSuper : typesFromSuper) {
628                ClassifierDescriptor classifierFromSuper = typeFromSuper.type.getConstructor().getDeclarationDescriptor();
629                if (classifierFromSuper instanceof ClassDescriptor) {
630                    ClassDescriptor classFromSuper = (ClassDescriptor) classifierFromSuper;
631    
632                    if (collectionMapping.isMutableCollection(classFromSuper)) {
633                        someSupersMutable = true;
634                    }
635                    else if (collectionMapping.isReadOnlyCollection(classFromSuper)) {
636                        if (typeFromSuper.varianceOfPosition == Variance.OUT_VARIANCE) {
637                            someSupersCovariantReadOnly = true;
638                        }
639                        else {
640                            someSupersNotCovariantReadOnly = true;
641                        }
642                    }
643                }
644            }
645    
646            if (someSupersMutable && someSupersNotCovariantReadOnly) {
647                reportError("Incompatible types in superclasses: " + typesFromSuper);
648                return classifier;
649            }
650            else if (someSupersMutable) {
651                if (collectionMapping.isReadOnlyCollection(klass)) {
652                    return collectionMapping.convertReadOnlyToMutable(klass);
653                }
654            }
655            else if (someSupersNotCovariantReadOnly || someSupersCovariantReadOnly) {
656                if (collectionMapping.isMutableCollection(klass)) {
657                    return collectionMapping.convertMutableToReadOnly(klass);
658                }
659            }
660    
661            ClassifierDescriptor fixed = PropagationHeuristics.tryToFixOverridingTWithRawType(this, typesFromSuper);
662            return fixed != null ? fixed : classifier;
663        }
664    
665        private static boolean isArrayType(@NotNull JetType type) {
666            return KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type);
667        }
668    
669        private static class VarargCheckResult {
670            public final JetType parameterType;
671            public final boolean isVararg;
672    
673            public VarargCheckResult(JetType parameterType, boolean isVararg) {
674                this.parameterType = parameterType;
675                this.isVararg = isVararg;
676            }
677        }
678    
679        private static class TypeProjectionAndVariance {
680            public final TypeProjection typeProjection;
681            public final Variance varianceOfPosition;
682    
683            public TypeProjectionAndVariance(TypeProjection typeProjection, Variance varianceOfPosition) {
684                this.typeProjection = typeProjection;
685                this.varianceOfPosition = varianceOfPosition;
686            }
687    
688            public String toString() {
689                return typeProjection.toString();
690            }
691        }
692    
693        static class TypeAndVariance {
694            public final JetType type;
695            public final Variance varianceOfPosition;
696    
697            public TypeAndVariance(JetType type, Variance varianceOfPosition) {
698                this.type = type;
699                this.varianceOfPosition = varianceOfPosition;
700            }
701    
702            public String toString() {
703                return type.toString();
704            }
705        }
706    
707        private static class TypeAndName {
708            public final JetType type;
709            public final Name name;
710    
711            public TypeAndName(JetType type, Name name) {
712                this.type = type;
713                this.name = name;
714            }
715        }
716    
717        private static class ValueParameters {
718            private final JetType receiverType;
719            private final List<ValueParameterDescriptor> descriptors;
720            private final boolean hasStableParameterNames;
721    
722            public ValueParameters(
723                    @Nullable JetType receiverType,
724                    @NotNull List<ValueParameterDescriptor> descriptors,
725                    boolean hasStableParameterNames
726            ) {
727                this.receiverType = receiverType;
728                this.descriptors = descriptors;
729                this.hasStableParameterNames = hasStableParameterNames;
730            }
731        }
732    }