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;
018    
019    import com.google.common.collect.Lists;
020    import com.google.common.collect.Maps;
021    import com.google.common.collect.Sets;
022    import com.intellij.psi.PsiElement;
023    import kotlin.CollectionsKt;
024    import kotlin.SetsKt;
025    import kotlin.jvm.functions.Function0;
026    import kotlin.jvm.functions.Function1;
027    import org.jetbrains.annotations.NotNull;
028    import org.jetbrains.annotations.Nullable;
029    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
030    import org.jetbrains.kotlin.descriptors.*;
031    import org.jetbrains.kotlin.descriptors.annotations.AnnotationSplitter;
032    import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
033    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
034    import org.jetbrains.kotlin.descriptors.annotations.CompositeAnnotations;
035    import org.jetbrains.kotlin.descriptors.impl.*;
036    import org.jetbrains.kotlin.diagnostics.Errors;
037    import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
038    import org.jetbrains.kotlin.lexer.KtTokens;
039    import org.jetbrains.kotlin.name.FqName;
040    import org.jetbrains.kotlin.name.Name;
041    import org.jetbrains.kotlin.psi.*;
042    import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
043    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
044    import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant;
045    import org.jetbrains.kotlin.resolve.constants.ConstantValue;
046    import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator;
047    import org.jetbrains.kotlin.resolve.dataClassUtils.DataClassUtilsKt;
048    import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil;
049    import org.jetbrains.kotlin.resolve.scopes.JetScopeUtils;
050    import org.jetbrains.kotlin.resolve.scopes.LexicalScope;
051    import org.jetbrains.kotlin.resolve.scopes.LexicalWritableScope;
052    import org.jetbrains.kotlin.resolve.scopes.utils.ScopeUtilsKt;
053    import org.jetbrains.kotlin.resolve.source.KotlinSourceElementKt;
054    import org.jetbrains.kotlin.storage.StorageManager;
055    import org.jetbrains.kotlin.types.*;
056    import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
057    import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices;
058    import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor;
059    
060    import java.util.*;
061    
062    import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*;
063    import static org.jetbrains.kotlin.diagnostics.Errors.*;
064    import static org.jetbrains.kotlin.lexer.KtTokens.*;
065    import static org.jetbrains.kotlin.resolve.BindingContext.CONSTRUCTOR;
066    import static org.jetbrains.kotlin.resolve.BindingContext.PACKAGE_TO_FILES;
067    import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
068    import static org.jetbrains.kotlin.resolve.ModifiersChecker.resolveModalityFromModifiers;
069    import static org.jetbrains.kotlin.resolve.ModifiersChecker.resolveVisibilityFromModifiers;
070    
071    public class DescriptorResolver {
072        public static final Name COPY_METHOD_NAME = Name.identifier("copy");
073    
074        @NotNull private final TypeResolver typeResolver;
075        @NotNull private final AnnotationResolver annotationResolver;
076        @NotNull private final ExpressionTypingServices expressionTypingServices;
077        @NotNull private final DelegatedPropertyResolver delegatedPropertyResolver;
078        @NotNull private final StorageManager storageManager;
079        @NotNull private final KotlinBuiltIns builtIns;
080        @NotNull private final ConstantExpressionEvaluator constantExpressionEvaluator;
081        @NotNull private final SupertypeLoopChecker supertypeLoopsResolver;
082    
083        public DescriptorResolver(
084                @NotNull AnnotationResolver annotationResolver,
085                @NotNull KotlinBuiltIns builtIns,
086                @NotNull DelegatedPropertyResolver delegatedPropertyResolver,
087                @NotNull ExpressionTypingServices expressionTypingServices,
088                @NotNull StorageManager storageManager,
089                @NotNull TypeResolver typeResolver,
090                @NotNull ConstantExpressionEvaluator constantExpressionEvaluator,
091                @NotNull SupertypeLoopChecker supertypeLoopsResolver
092        ) {
093            this.annotationResolver = annotationResolver;
094            this.builtIns = builtIns;
095            this.delegatedPropertyResolver = delegatedPropertyResolver;
096            this.expressionTypingServices = expressionTypingServices;
097            this.storageManager = storageManager;
098            this.typeResolver = typeResolver;
099            this.constantExpressionEvaluator = constantExpressionEvaluator;
100            this.supertypeLoopsResolver = supertypeLoopsResolver;
101        }
102    
103        public List<KotlinType> resolveSupertypes(
104                @NotNull LexicalScope scope,
105                @NotNull ClassDescriptor classDescriptor,
106                @NotNull KtClassOrObject jetClass,
107                BindingTrace trace
108        ) {
109            List<KotlinType> supertypes = Lists.newArrayList();
110            List<KtDelegationSpecifier> delegationSpecifiers = jetClass.getDelegationSpecifiers();
111            Collection<KotlinType> declaredSupertypes = resolveDelegationSpecifiers(
112                    scope,
113                    delegationSpecifiers,
114                    typeResolver, trace, false);
115    
116            for (KotlinType declaredSupertype : declaredSupertypes) {
117                addValidSupertype(supertypes, declaredSupertype);
118            }
119    
120            if (classDescriptor.getKind() == ClassKind.ENUM_CLASS && !containsClass(supertypes)) {
121                supertypes.add(0, builtIns.getEnumType(classDescriptor.getDefaultType()));
122            }
123    
124            if (supertypes.isEmpty()) {
125                KotlinType defaultSupertype = getDefaultSupertype(jetClass, trace, classDescriptor.getKind() == ClassKind.ANNOTATION_CLASS);
126                addValidSupertype(supertypes, defaultSupertype);
127            }
128    
129            return supertypes;
130        }
131    
132        private static void addValidSupertype(List<KotlinType> supertypes, KotlinType declaredSupertype) {
133            if (!declaredSupertype.isError()) {
134                supertypes.add(declaredSupertype);
135            }
136        }
137    
138        private boolean containsClass(Collection<KotlinType> result) {
139            for (KotlinType type : result) {
140                ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
141                if (descriptor instanceof ClassDescriptor && ((ClassDescriptor) descriptor).getKind() != ClassKind.INTERFACE) {
142                    return true;
143                }
144            }
145            return false;
146        }
147    
148        private KotlinType getDefaultSupertype(KtClassOrObject jetClass, BindingTrace trace, boolean isAnnotation) {
149            // TODO : beautify
150            if (jetClass instanceof KtEnumEntry) {
151                KtClassOrObject parent = KtStubbedPsiUtil.getContainingDeclaration(jetClass, KtClassOrObject.class);
152                ClassDescriptor parentDescriptor = trace.getBindingContext().get(BindingContext.CLASS, parent);
153                if (parentDescriptor.getTypeConstructor().getParameters().isEmpty()) {
154                    return parentDescriptor.getDefaultType();
155                }
156                else {
157                    trace.report(NO_GENERICS_IN_SUPERTYPE_SPECIFIER.on(jetClass.getNameIdentifier()));
158                    return ErrorUtils.createErrorType("Supertype not specified");
159                }
160            }
161            else if (isAnnotation) {
162                return builtIns.getAnnotationType();
163            }
164            return builtIns.getAnyType();
165        }
166    
167        public Collection<KotlinType> resolveDelegationSpecifiers(
168                LexicalScope extensibleScope,
169                List<KtDelegationSpecifier> delegationSpecifiers,
170                @NotNull TypeResolver resolver,
171                BindingTrace trace,
172                boolean checkBounds
173        ) {
174            if (delegationSpecifiers.isEmpty()) {
175                return Collections.emptyList();
176            }
177            Collection<KotlinType> result = Lists.newArrayList();
178            for (KtDelegationSpecifier delegationSpecifier : delegationSpecifiers) {
179                KtTypeReference typeReference = delegationSpecifier.getTypeReference();
180                if (typeReference != null) {
181                    KotlinType supertype = resolver.resolveType(extensibleScope, typeReference, trace, checkBounds);
182                    if (DynamicTypesKt.isDynamic(supertype)) {
183                        trace.report(DYNAMIC_SUPERTYPE.on(typeReference));
184                    }
185                    else {
186                        result.add(supertype);
187                        KtTypeElement bareSuperType = checkNullableSupertypeAndStripQuestionMarks(trace, typeReference.getTypeElement());
188                        checkProjectionsInImmediateArguments(trace, bareSuperType);
189                    }
190                }
191                else {
192                    result.add(ErrorUtils.createErrorType("No type reference"));
193                }
194            }
195            return result;
196        }
197    
198        @Nullable
199        private static KtTypeElement checkNullableSupertypeAndStripQuestionMarks(@NotNull BindingTrace trace, @Nullable KtTypeElement typeElement) {
200            while (typeElement instanceof KtNullableType) {
201                KtNullableType nullableType = (KtNullableType) typeElement;
202                typeElement = nullableType.getInnerType();
203                // report only for innermost '?', the rest gets a 'redundant' warning
204                if (!(typeElement instanceof KtNullableType) && typeElement != null) {
205                    trace.report(NULLABLE_SUPERTYPE.on(nullableType));
206                }
207            }
208            return typeElement;
209        }
210    
211        private static void checkProjectionsInImmediateArguments(@NotNull BindingTrace trace, @Nullable KtTypeElement typeElement) {
212            if (typeElement instanceof KtUserType) {
213                KtUserType userType = (KtUserType) typeElement;
214                List<KtTypeProjection> typeArguments = userType.getTypeArguments();
215                for (KtTypeProjection typeArgument : typeArguments) {
216                    if (typeArgument.getProjectionKind() != KtProjectionKind.NONE) {
217                        trace.report(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE.on(typeArgument));
218                    }
219                }
220            }
221        }
222    
223        @NotNull
224        public static SimpleFunctionDescriptor createComponentFunctionDescriptor(
225                int parameterIndex,
226                @NotNull PropertyDescriptor property,
227                @NotNull ValueParameterDescriptor parameter,
228                @NotNull ClassDescriptor classDescriptor,
229                @NotNull BindingTrace trace
230        ) {
231            Name functionName = DataClassUtilsKt.createComponentName(parameterIndex);
232            KotlinType returnType = property.getType();
233    
234            SimpleFunctionDescriptorImpl functionDescriptor = SimpleFunctionDescriptorImpl.create(
235                    classDescriptor,
236                    Annotations.Companion.getEMPTY(),
237                    functionName,
238                    CallableMemberDescriptor.Kind.SYNTHESIZED,
239                    parameter.getSource()
240            );
241    
242            functionDescriptor.initialize(
243                    null,
244                    classDescriptor.getThisAsReceiverParameter(),
245                    Collections.<TypeParameterDescriptor>emptyList(),
246                    Collections.<ValueParameterDescriptor>emptyList(),
247                    returnType,
248                    Modality.FINAL,
249                    property.getVisibility()
250            );
251            functionDescriptor.setOperator(true);
252    
253            trace.record(BindingContext.DATA_CLASS_COMPONENT_FUNCTION, parameter, functionDescriptor);
254    
255            return functionDescriptor;
256        }
257    
258        @NotNull
259        public static SimpleFunctionDescriptor createCopyFunctionDescriptor(
260                @NotNull Collection<ValueParameterDescriptor> constructorParameters,
261                @NotNull ClassDescriptor classDescriptor,
262                @NotNull BindingTrace trace
263        ) {
264            KotlinType returnType = classDescriptor.getDefaultType();
265    
266            SimpleFunctionDescriptorImpl functionDescriptor = SimpleFunctionDescriptorImpl.create(
267                    classDescriptor,
268                    Annotations.Companion.getEMPTY(),
269                    COPY_METHOD_NAME,
270                    CallableMemberDescriptor.Kind.SYNTHESIZED,
271                    classDescriptor.getSource()
272            );
273    
274            List<ValueParameterDescriptor> parameterDescriptors = Lists.newArrayList();
275    
276            for (ValueParameterDescriptor parameter : constructorParameters) {
277                PropertyDescriptor propertyDescriptor = trace.getBindingContext().get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, parameter);
278                // If parameter hasn't corresponding property, so it mustn't have default value as a parameter in copy function for data class
279                boolean declaresDefaultValue = propertyDescriptor != null;
280                ValueParameterDescriptorImpl parameterDescriptor =
281                        new ValueParameterDescriptorImpl(functionDescriptor, null, parameter.getIndex(), parameter.getAnnotations(),
282                                                         parameter.getName(), parameter.getType(),
283                                                         declaresDefaultValue,
284                                                         parameter.isCrossinline(),
285                                                         parameter.isNoinline(),
286                                                         parameter.getVarargElementType(), parameter.getSource());
287                parameterDescriptors.add(parameterDescriptor);
288                if (declaresDefaultValue) {
289                    trace.record(BindingContext.VALUE_PARAMETER_AS_PROPERTY, parameterDescriptor, propertyDescriptor);
290                }
291            }
292    
293            functionDescriptor.initialize(
294                    null,
295                    classDescriptor.getThisAsReceiverParameter(),
296                    Collections.<TypeParameterDescriptor>emptyList(),
297                    parameterDescriptors,
298                    returnType,
299                    Modality.FINAL,
300                    Visibilities.PUBLIC
301            );
302    
303            trace.record(BindingContext.DATA_CLASS_COPY_FUNCTION, classDescriptor, functionDescriptor);
304            return functionDescriptor;
305        }
306    
307        public static Visibility getDefaultVisibility(KtModifierListOwner modifierListOwner, DeclarationDescriptor containingDescriptor) {
308            Visibility defaultVisibility;
309            if (containingDescriptor instanceof ClassDescriptor) {
310                KtModifierList modifierList = modifierListOwner.getModifierList();
311                defaultVisibility = modifierList != null && modifierList.hasModifier(OVERRIDE_KEYWORD)
312                                               ? Visibilities.INHERITED
313                                               : Visibilities.DEFAULT_VISIBILITY;
314            }
315            else if (containingDescriptor instanceof FunctionDescriptor || containingDescriptor instanceof PropertyDescriptor) {
316                defaultVisibility = Visibilities.LOCAL;
317            }
318            else {
319                defaultVisibility = Visibilities.DEFAULT_VISIBILITY;
320            }
321            return defaultVisibility;
322        }
323    
324        public static Modality getDefaultModality(DeclarationDescriptor containingDescriptor, Visibility visibility, boolean isBodyPresent) {
325            Modality defaultModality;
326            if (containingDescriptor instanceof ClassDescriptor) {
327                boolean isTrait = ((ClassDescriptor) containingDescriptor).getKind() == ClassKind.INTERFACE;
328                boolean isDefinitelyAbstract = isTrait && !isBodyPresent;
329                Modality basicModality = isTrait && !Visibilities.isPrivate(visibility) ? Modality.OPEN : Modality.FINAL;
330                defaultModality = isDefinitelyAbstract ? Modality.ABSTRACT : basicModality;
331            }
332            else {
333                defaultModality = Modality.FINAL;
334            }
335            return defaultModality;
336        }
337    
338        @NotNull
339        public ValueParameterDescriptorImpl resolveValueParameterDescriptor(
340                LexicalScope scope, FunctionDescriptor owner, KtParameter valueParameter, int index, KotlinType type, BindingTrace trace
341        ) {
342            KotlinType varargElementType = null;
343            KotlinType variableType = type;
344            if (valueParameter.hasModifier(VARARG_KEYWORD)) {
345                varargElementType = type;
346                variableType = getVarargParameterType(type);
347            }
348    
349            KtModifierList modifierList = valueParameter.getModifierList();
350    
351            Annotations allAnnotations =
352                    annotationResolver.resolveAnnotationsWithoutArguments(scope, valueParameter.getModifierList(), trace);
353            Annotations valueParameterAnnotations = Annotations.Companion.getEMPTY();
354    
355            if (modifierList != null) {
356                if (valueParameter.hasValOrVar()) {
357                    AnnotationSplitter annotationSplitter = AnnotationSplitter.create(
358                            storageManager, allAnnotations, SetsKt.setOf(CONSTRUCTOR_PARAMETER));
359                    valueParameterAnnotations = annotationSplitter.getAnnotationsForTarget(CONSTRUCTOR_PARAMETER);
360                }
361                else {
362                    valueParameterAnnotations = allAnnotations;
363                }
364            }
365    
366            ValueParameterDescriptorImpl valueParameterDescriptor = new ValueParameterDescriptorImpl(
367                    owner,
368                    null,
369                    index,
370                    valueParameterAnnotations,
371                    KtPsiUtil.safeName(valueParameter.getName()),
372                    variableType,
373                    valueParameter.hasDefaultValue(),
374                    valueParameter.hasModifier(CROSSINLINE_KEYWORD),
375                    valueParameter.hasModifier(NOINLINE_KEYWORD),
376                    varargElementType,
377                    KotlinSourceElementKt.toSourceElement(valueParameter)
378            );
379    
380            trace.record(BindingContext.VALUE_PARAMETER, valueParameter, valueParameterDescriptor);
381            return valueParameterDescriptor;
382        }
383    
384        @NotNull
385        private KotlinType getVarargParameterType(@NotNull KotlinType elementType) {
386            KotlinType primitiveArrayType = builtIns.getPrimitiveArrayKotlinTypeByPrimitiveKotlinType(elementType);
387            if (primitiveArrayType != null) {
388                return primitiveArrayType;
389            }
390            return builtIns.getArrayType(Variance.OUT_VARIANCE, elementType);
391        }
392    
393        public List<TypeParameterDescriptorImpl> resolveTypeParametersForCallableDescriptor(
394                DeclarationDescriptor containingDescriptor,
395                LexicalWritableScope extensibleScope,
396                LexicalScope scopeForAnnotationsResolve,
397                List<KtTypeParameter> typeParameters,
398                BindingTrace trace
399        ) {
400            List<TypeParameterDescriptorImpl> result = new ArrayList<TypeParameterDescriptorImpl>();
401            for (int i = 0, typeParametersSize = typeParameters.size(); i < typeParametersSize; i++) {
402                KtTypeParameter typeParameter = typeParameters.get(i);
403                result.add(resolveTypeParameterForCallableDescriptor(
404                        containingDescriptor, extensibleScope, scopeForAnnotationsResolve, typeParameter, i, trace));
405            }
406            return result;
407        }
408    
409        private TypeParameterDescriptorImpl resolveTypeParameterForCallableDescriptor(
410                DeclarationDescriptor containingDescriptor,
411                LexicalWritableScope extensibleScope,
412                LexicalScope scopeForAnnotationsResolve,
413                final KtTypeParameter typeParameter,
414                int index,
415                final BindingTrace trace
416        ) {
417            if (typeParameter.getVariance() != Variance.INVARIANT) {
418                assert !(containingDescriptor instanceof ClassifierDescriptor) : "This method is intended for functions/properties";
419                trace.report(VARIANCE_ON_TYPE_PARAMETER_OF_FUNCTION_OR_PROPERTY.on(typeParameter));
420            }
421    
422            Annotations annotations =
423                    annotationResolver.resolveAnnotationsWithArguments(scopeForAnnotationsResolve, typeParameter.getModifierList(), trace);
424    
425            TypeParameterDescriptorImpl typeParameterDescriptor = TypeParameterDescriptorImpl.createForFurtherModification(
426                    containingDescriptor,
427                    annotations,
428                    typeParameter.hasModifier(KtTokens.REIFIED_KEYWORD),
429                    typeParameter.getVariance(),
430                    KtPsiUtil.safeName(typeParameter.getName()),
431                    index,
432                    KotlinSourceElementKt.toSourceElement(typeParameter),
433                    new Function1<KotlinType, Void>() {
434                        @Override
435                        public Void invoke(KotlinType type) {
436                            trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(typeParameter));
437                            return null;
438                        }
439                    },
440                    supertypeLoopsResolver
441                    );
442            trace.record(BindingContext.TYPE_PARAMETER, typeParameter, typeParameterDescriptor);
443            extensibleScope.addClassifierDescriptor(typeParameterDescriptor);
444            return typeParameterDescriptor;
445        }
446    
447        @NotNull
448        public static ConstructorDescriptorImpl createAndRecordPrimaryConstructorForObject(
449                @Nullable KtClassOrObject object,
450                @NotNull ClassDescriptor classDescriptor,
451                @NotNull BindingTrace trace
452        ) {
453            ConstructorDescriptorImpl constructorDescriptor =
454                    DescriptorFactory.createPrimaryConstructorForObject(classDescriptor, KotlinSourceElementKt.toSourceElement(object));
455            if (object != null) {
456                KtPrimaryConstructor primaryConstructor = object.getPrimaryConstructor();
457                trace.record(CONSTRUCTOR, primaryConstructor != null ? primaryConstructor : object, constructorDescriptor);
458            }
459            return constructorDescriptor;
460        }
461    
462        static final class UpperBoundCheckerTask {
463            KtTypeReference upperBound;
464            KotlinType upperBoundType;
465    
466            private UpperBoundCheckerTask(KtTypeReference upperBound, KotlinType upperBoundType) {
467                this.upperBound = upperBound;
468                this.upperBoundType = upperBoundType;
469            }
470        }
471    
472        public void resolveGenericBounds(
473                @NotNull KtTypeParameterListOwner declaration,
474                @NotNull DeclarationDescriptor descriptor,
475                LexicalScope scope,
476                List<TypeParameterDescriptorImpl> parameters,
477                BindingTrace trace
478        ) {
479            List<UpperBoundCheckerTask> deferredUpperBoundCheckerTasks = Lists.newArrayList();
480    
481            List<KtTypeParameter> typeParameters = declaration.getTypeParameters();
482            Map<Name, TypeParameterDescriptorImpl> parameterByName = Maps.newHashMap();
483            for (int i = 0; i < typeParameters.size(); i++) {
484                KtTypeParameter jetTypeParameter = typeParameters.get(i);
485                TypeParameterDescriptorImpl typeParameterDescriptor = parameters.get(i);
486    
487                parameterByName.put(typeParameterDescriptor.getName(), typeParameterDescriptor);
488    
489                KtTypeReference extendsBound = jetTypeParameter.getExtendsBound();
490                if (extendsBound != null) {
491                    KotlinType type = typeResolver.resolveType(scope, extendsBound, trace, false);
492                    typeParameterDescriptor.addUpperBound(type);
493                    deferredUpperBoundCheckerTasks.add(new UpperBoundCheckerTask(extendsBound, type));
494                }
495            }
496            for (KtTypeConstraint constraint : declaration.getTypeConstraints()) {
497                KtSimpleNameExpression subjectTypeParameterName = constraint.getSubjectTypeParameterName();
498                if (subjectTypeParameterName == null) {
499                    continue;
500                }
501                Name referencedName = subjectTypeParameterName.getReferencedNameAsName();
502                TypeParameterDescriptorImpl typeParameterDescriptor = parameterByName.get(referencedName);
503                KtTypeReference boundTypeReference = constraint.getBoundTypeReference();
504                KotlinType bound = null;
505                if (boundTypeReference != null) {
506                    bound = typeResolver.resolveType(scope, boundTypeReference, trace, false);
507                    deferredUpperBoundCheckerTasks.add(new UpperBoundCheckerTask(boundTypeReference, bound));
508                }
509    
510                if (typeParameterDescriptor != null) {
511                    trace.record(BindingContext.REFERENCE_TARGET, subjectTypeParameterName, typeParameterDescriptor);
512                    if (bound != null) {
513                        typeParameterDescriptor.addUpperBound(bound);
514                    }
515                }
516            }
517    
518            for (TypeParameterDescriptorImpl parameter : parameters) {
519                parameter.addDefaultUpperBound();
520                parameter.setInitialized();
521            }
522    
523            for (TypeParameterDescriptorImpl parameter : parameters) {
524                checkConflictingUpperBounds(trace, parameter, typeParameters.get(parameter.getIndex()));
525            }
526    
527            if (!(declaration instanceof KtClass)) {
528                for (UpperBoundCheckerTask checkerTask : deferredUpperBoundCheckerTasks) {
529                    checkUpperBoundType(checkerTask.upperBound, checkerTask.upperBoundType, trace);
530                }
531    
532                checkNamesInConstraints(declaration, descriptor, scope, trace);
533            }
534        }
535    
536        public static void checkConflictingUpperBounds(
537                @NotNull BindingTrace trace,
538                @NotNull TypeParameterDescriptor parameter,
539                @NotNull KtTypeParameter typeParameter
540        ) {
541            if (KotlinBuiltIns.isNothing(TypeIntersector.getUpperBoundsAsType(parameter))) {
542                trace.report(CONFLICTING_UPPER_BOUNDS.on(typeParameter, parameter));
543            }
544        }
545    
546        public void checkNamesInConstraints(
547                @NotNull KtTypeParameterListOwner declaration,
548                @NotNull DeclarationDescriptor descriptor,
549                @NotNull LexicalScope scope,
550                @NotNull BindingTrace trace
551        ) {
552            for (KtTypeConstraint constraint : declaration.getTypeConstraints()) {
553                KtSimpleNameExpression nameExpression = constraint.getSubjectTypeParameterName();
554                if (nameExpression == null) continue;
555    
556                Name name = nameExpression.getReferencedNameAsName();
557    
558                ClassifierDescriptor classifier = ScopeUtilsKt.findClassifier(scope, name, NoLookupLocation.FOR_NON_TRACKED_SCOPE);
559                if (classifier instanceof TypeParameterDescriptor && classifier.getContainingDeclaration() == descriptor) continue;
560    
561                if (classifier != null) {
562                    // To tell the user that we look only for locally defined type parameters
563                    trace.report(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER.on(nameExpression, constraint, declaration));
564                    trace.record(BindingContext.REFERENCE_TARGET, nameExpression, classifier);
565                }
566                else {
567                    trace.report(UNRESOLVED_REFERENCE.on(nameExpression, nameExpression));
568                }
569    
570                KtTypeReference boundTypeReference = constraint.getBoundTypeReference();
571                if (boundTypeReference != null) {
572                    typeResolver.resolveType(scope, boundTypeReference, trace, true);
573                }
574            }
575        }
576    
577        public static void checkUpperBoundType(
578                KtTypeReference upperBound,
579                @NotNull KotlinType upperBoundType,
580                BindingTrace trace
581        ) {
582            if (!TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, upperBoundType)) {
583                ClassifierDescriptor descriptor = upperBoundType.getConstructor().getDeclarationDescriptor();
584                if (descriptor instanceof ClassDescriptor) {
585                    if (((ClassDescriptor) descriptor).getModality() == Modality.SEALED) return;
586                }
587                trace.report(FINAL_UPPER_BOUND.on(upperBound, upperBoundType));
588            }
589            if (DynamicTypesKt.isDynamic(upperBoundType)) {
590                trace.report(DYNAMIC_UPPER_BOUND.on(upperBound));
591            }
592            if (KotlinBuiltIns.isExactExtensionFunctionType(upperBoundType)) {
593                trace.report(UPPER_BOUND_IS_EXTENSION_FUNCTION_TYPE.on(upperBound));
594            }
595        }
596    
597        @NotNull
598        public VariableDescriptor resolveLocalVariableDescriptor(
599                @NotNull LexicalScope scope,
600                @NotNull KtParameter parameter,
601                BindingTrace trace
602        ) {
603            KotlinType type = resolveParameterType(scope, parameter, trace);
604            return resolveLocalVariableDescriptor(parameter, type, trace, scope);
605        }
606    
607        private KotlinType resolveParameterType(LexicalScope scope, KtParameter parameter, BindingTrace trace) {
608            KtTypeReference typeReference = parameter.getTypeReference();
609            KotlinType type;
610            if (typeReference != null) {
611                type = typeResolver.resolveType(scope, typeReference, trace, true);
612            }
613            else {
614                // Error is reported by the parser
615                type = ErrorUtils.createErrorType("Annotation is absent");
616            }
617            if (parameter.hasModifier(VARARG_KEYWORD)) {
618                return getVarargParameterType(type);
619            }
620            return type;
621        }
622    
623        public VariableDescriptor resolveLocalVariableDescriptor(
624                @NotNull KtParameter parameter,
625                @NotNull KotlinType type,
626                BindingTrace trace,
627                @NotNull LexicalScope scope
628        ) {
629            VariableDescriptor variableDescriptor = new LocalVariableDescriptor(
630                    scope.getOwnerDescriptor(),
631                    annotationResolver.resolveAnnotationsWithArguments(scope, parameter.getModifierList(), trace),
632                    KtPsiUtil.safeName(parameter.getName()),
633                    type,
634                    false,
635                    KotlinSourceElementKt.toSourceElement(parameter)
636            );
637            trace.record(BindingContext.VALUE_PARAMETER, parameter, variableDescriptor);
638            // Type annotations also should be resolved
639            ForceResolveUtil.forceResolveAllContents(type.getAnnotations());
640            return variableDescriptor;
641        }
642    
643        @NotNull
644        public VariableDescriptor resolveLocalVariableDescriptor(
645                LexicalScope scope,
646                KtVariableDeclaration variable,
647                DataFlowInfo dataFlowInfo,
648                BindingTrace trace
649        ) {
650            DeclarationDescriptor containingDeclaration = scope.getOwnerDescriptor();
651            VariableDescriptor result;
652            KotlinType type;
653            if (KtPsiUtil.isScriptDeclaration(variable)) {
654                PropertyDescriptorImpl propertyDescriptor = PropertyDescriptorImpl.create(
655                        containingDeclaration,
656                        annotationResolver.resolveAnnotationsWithArguments(scope, variable.getModifierList(), trace),
657                        Modality.FINAL,
658                        Visibilities.INTERNAL,
659                        variable.isVar(),
660                        KtPsiUtil.safeName(variable.getName()),
661                        CallableMemberDescriptor.Kind.DECLARATION,
662                        KotlinSourceElementKt.toSourceElement(variable),
663                        /* lateInit = */ false,
664                        /* isConst = */ false
665                );
666                // For a local variable the type must not be deferred
667                type = getVariableType(propertyDescriptor, scope, variable, dataFlowInfo, false, trace);
668    
669                ReceiverParameterDescriptor receiverParameter = ((ScriptDescriptor) containingDeclaration).getThisAsReceiverParameter();
670                propertyDescriptor.setType(type, Collections.<TypeParameterDescriptor>emptyList(), receiverParameter, (KotlinType) null);
671                initializeWithDefaultGetterSetter(propertyDescriptor);
672                trace.record(BindingContext.VARIABLE, variable, propertyDescriptor);
673                result = propertyDescriptor;
674            }
675            else {
676                LocalVariableDescriptor variableDescriptor =
677                        resolveLocalVariableDescriptorWithType(scope, variable, null, trace);
678                // For a local variable the type must not be deferred
679                type = getVariableType(variableDescriptor, scope, variable, dataFlowInfo, false, trace);
680                variableDescriptor.setOutType(type);
681                result = variableDescriptor;
682            }
683            // Type annotations also should be resolved
684            ForceResolveUtil.forceResolveAllContents(type.getAnnotations());
685            return result;
686        }
687    
688        private static void initializeWithDefaultGetterSetter(PropertyDescriptorImpl propertyDescriptor) {
689            PropertyGetterDescriptorImpl getter = propertyDescriptor.getGetter();
690            if (getter == null && !Visibilities.isPrivate(propertyDescriptor.getVisibility())) {
691                getter = DescriptorFactory.createDefaultGetter(propertyDescriptor, Annotations.Companion.getEMPTY());
692                getter.initialize(propertyDescriptor.getType());
693            }
694    
695            PropertySetterDescriptor setter = propertyDescriptor.getSetter();
696            if (setter == null && propertyDescriptor.isVar()) {
697                setter = DescriptorFactory.createDefaultSetter(propertyDescriptor, Annotations.Companion.getEMPTY());
698            }
699            propertyDescriptor.initialize(getter, setter);
700        }
701    
702        @NotNull
703        public LocalVariableDescriptor resolveLocalVariableDescriptorWithType(
704                @NotNull LexicalScope scope,
705                @NotNull KtVariableDeclaration variable,
706                @Nullable KotlinType type,
707                @NotNull BindingTrace trace
708        ) {
709            LocalVariableDescriptor variableDescriptor = new LocalVariableDescriptor(
710                    scope.getOwnerDescriptor(),
711                    annotationResolver.resolveAnnotationsWithArguments(scope, variable.getModifierList(), trace),
712                    KtPsiUtil.safeName(variable.getName()),
713                    type,
714                    variable.isVar(),
715                    KotlinSourceElementKt.toSourceElement(variable)
716            );
717            trace.record(BindingContext.VARIABLE, variable, variableDescriptor);
718            return variableDescriptor;
719        }
720    
721        @NotNull
722        public PropertyDescriptor resolvePropertyDescriptor(
723                @NotNull DeclarationDescriptor containingDeclaration,
724                @NotNull LexicalScope scope,
725                @NotNull KtProperty property,
726                @NotNull final BindingTrace trace,
727                @NotNull DataFlowInfo dataFlowInfo
728        ) {
729            KtModifierList modifierList = property.getModifierList();
730            boolean isVar = property.isVar();
731    
732            boolean hasBody = hasBody(property);
733            Visibility visibility = resolveVisibilityFromModifiers(property, getDefaultVisibility(property, containingDeclaration));
734            Modality modality = containingDeclaration instanceof ClassDescriptor
735                                ? resolveModalityFromModifiers(property, getDefaultModality(containingDeclaration, visibility, hasBody))
736                                : Modality.FINAL;
737    
738            final AnnotationSplitter.PropertyWrapper wrapper = new AnnotationSplitter.PropertyWrapper();
739    
740            Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scope, modifierList, trace);
741            AnnotationSplitter annotationSplitter =
742                    new AnnotationSplitter(storageManager, allAnnotations, new Function0<Set<AnnotationUseSiteTarget>>() {
743                @Override
744                public Set<AnnotationUseSiteTarget> invoke() {
745                    return AnnotationSplitter.getTargetSet(false, trace.getBindingContext(), wrapper);
746                }
747            });
748    
749            Annotations propertyAnnotations = new CompositeAnnotations(CollectionsKt.listOf(
750                    annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD),
751                    annotationSplitter.getOtherAnnotations()));
752    
753            PropertyDescriptorImpl propertyDescriptor = PropertyDescriptorImpl.create(
754                    containingDeclaration,
755                    propertyAnnotations,
756                    modality,
757                    visibility,
758                    isVar,
759                    KtPsiUtil.safeName(property.getName()),
760                    CallableMemberDescriptor.Kind.DECLARATION,
761                    KotlinSourceElementKt.toSourceElement(property),
762                    modifierList != null && modifierList.hasModifier(KtTokens.LATEINIT_KEYWORD),
763                    modifierList != null && modifierList.hasModifier(KtTokens.CONST_KEYWORD)
764            );
765            wrapper.setProperty(propertyDescriptor);
766    
767            List<TypeParameterDescriptorImpl> typeParameterDescriptors;
768            LexicalScope scopeWithTypeParameters;
769            KotlinType receiverType = null;
770    
771            {
772                List<KtTypeParameter> typeParameters = property.getTypeParameters();
773                if (typeParameters.isEmpty()) {
774                    scopeWithTypeParameters = scope;
775                    typeParameterDescriptors = Collections.emptyList();
776                }
777                else {
778                    LexicalWritableScope writableScope = new LexicalWritableScope(
779                            scope, containingDeclaration, false, null, new TraceBasedRedeclarationHandler(trace),
780                            "Scope with type parameters of a property");
781                    typeParameterDescriptors = resolveTypeParametersForCallableDescriptor(
782                            propertyDescriptor, writableScope, scope, typeParameters, trace);
783                    writableScope.changeLockLevel(LexicalWritableScope.LockLevel.READING);
784                    resolveGenericBounds(property, propertyDescriptor, writableScope, typeParameterDescriptors, trace);
785                    scopeWithTypeParameters = writableScope;
786                }
787    
788                KtTypeReference receiverTypeRef = property.getReceiverTypeReference();
789                if (receiverTypeRef != null) {
790                    receiverType = typeResolver.resolveType(scopeWithTypeParameters, receiverTypeRef, trace, true);
791                }
792            }
793    
794            ReceiverParameterDescriptor receiverDescriptor =
795                    DescriptorFactory.createExtensionReceiverParameterForCallable(propertyDescriptor, receiverType);
796    
797            ReceiverParameterDescriptor implicitInitializerReceiver = property.hasDelegate() ? null : receiverDescriptor;
798    
799            LexicalScope propertyScope = JetScopeUtils.getPropertyDeclarationInnerScope(propertyDescriptor, scope, typeParameterDescriptors,
800                                                                                        implicitInitializerReceiver, trace);
801    
802            KotlinType type = getVariableType(propertyDescriptor, propertyScope, property, dataFlowInfo, true, trace);
803    
804            propertyDescriptor.setType(type, typeParameterDescriptors, getDispatchReceiverParameterIfNeeded(containingDeclaration),
805                                       receiverDescriptor);
806    
807            PropertyGetterDescriptorImpl getter = resolvePropertyGetterDescriptor(
808                    scopeWithTypeParameters, property, propertyDescriptor, annotationSplitter, trace);
809            PropertySetterDescriptor setter = resolvePropertySetterDescriptor(
810                    scopeWithTypeParameters, property, propertyDescriptor, annotationSplitter, trace);
811    
812            propertyDescriptor.initialize(getter, setter);
813    
814            trace.record(BindingContext.VARIABLE, property, propertyDescriptor);
815            return propertyDescriptor;
816        }
817    
818        /*package*/
819        static boolean hasBody(KtProperty property) {
820            boolean hasBody = property.hasDelegateExpressionOrInitializer();
821            if (!hasBody) {
822                KtPropertyAccessor getter = property.getGetter();
823                if (getter != null && getter.hasBody()) {
824                    hasBody = true;
825                }
826                KtPropertyAccessor setter = property.getSetter();
827                if (!hasBody && setter != null && setter.hasBody()) {
828                    hasBody = true;
829                }
830            }
831            return hasBody;
832        }
833    
834        @NotNull
835        private KotlinType getVariableType(
836                @NotNull final VariableDescriptorWithInitializerImpl variableDescriptor,
837                @NotNull final LexicalScope scope,
838                @NotNull final KtVariableDeclaration variable,
839                @NotNull final DataFlowInfo dataFlowInfo,
840                boolean notLocal,
841                @NotNull final BindingTrace trace
842        ) {
843            KtTypeReference propertyTypeRef = variable.getTypeReference();
844    
845            boolean hasDelegate = variable instanceof KtProperty && ((KtProperty) variable).hasDelegateExpression();
846            if (propertyTypeRef == null) {
847                if (!variable.hasInitializer()) {
848                    if (hasDelegate && variableDescriptor instanceof PropertyDescriptor) {
849                        final KtProperty property = (KtProperty) variable;
850                        if (property.hasDelegateExpression()) {
851                            return DeferredType.createRecursionIntolerant(
852                                    storageManager,
853                                    trace,
854                                    new Function0<KotlinType>() {
855                                        @Override
856                                        public KotlinType invoke() {
857                                            return resolveDelegatedPropertyType(property, (PropertyDescriptor) variableDescriptor, scope,
858                                                                                property.getDelegateExpression(), dataFlowInfo, trace);
859                                        }
860                                    });
861                        }
862                    }
863                    if (!notLocal) {
864                        trace.report(VARIABLE_WITH_NO_TYPE_NO_INITIALIZER.on(variable));
865                    }
866                    return ErrorUtils.createErrorType("No type, no body");
867                }
868                else {
869                    if (notLocal) {
870                        return DeferredType.createRecursionIntolerant(
871                                storageManager,
872                                trace,
873                                new Function0<KotlinType>() {
874                                    @Override
875                                    public KotlinType invoke() {
876                                        PreliminaryDeclarationVisitor.Companion.createForDeclaration(variable, trace);
877                                        KotlinType
878                                                initializerType = resolveInitializerType(scope, variable.getInitializer(), dataFlowInfo, trace);
879                                        setConstantForVariableIfNeeded(variableDescriptor, scope, variable, dataFlowInfo, initializerType, trace);
880                                        return transformAnonymousTypeIfNeeded(variableDescriptor, variable, initializerType, trace);
881                                    }
882                                }
883                        );
884                    }
885                    else {
886                        KotlinType initializerType = resolveInitializerType(scope, variable.getInitializer(), dataFlowInfo, trace);
887                        setConstantForVariableIfNeeded(variableDescriptor, scope, variable, dataFlowInfo, initializerType, trace);
888                        return initializerType;
889                    }
890                }
891            }
892            else {
893                KotlinType type = typeResolver.resolveType(scope, propertyTypeRef, trace, true);
894                setConstantForVariableIfNeeded(variableDescriptor, scope, variable, dataFlowInfo, type, trace);
895                return type;
896            }
897        }
898    
899        private void setConstantForVariableIfNeeded(
900                @NotNull final VariableDescriptorWithInitializerImpl variableDescriptor,
901                @NotNull final LexicalScope scope,
902                @NotNull final KtVariableDeclaration variable,
903                @NotNull final DataFlowInfo dataFlowInfo,
904                @NotNull final KotlinType variableType,
905                @NotNull final BindingTrace trace
906        ) {
907            if (!shouldRecordInitializerForProperty(variableDescriptor, variableType)) return;
908    
909            if (!variable.hasInitializer()) return;
910    
911            variableDescriptor.setCompileTimeInitializer(
912                storageManager.createRecursionTolerantNullableLazyValue(new Function0<ConstantValue<?>>() {
913                    @Nullable
914                    @Override
915                    public ConstantValue<?> invoke() {
916                        KtExpression initializer = variable.getInitializer();
917                        KotlinType initializerType = expressionTypingServices.safeGetType(scope, initializer, variableType, dataFlowInfo, trace);
918                        CompileTimeConstant<?> constant = constantExpressionEvaluator.evaluateExpression(initializer, trace, initializerType);
919    
920                        if (constant == null) return null;
921    
922                        if (constant.getUsesNonConstValAsConstant() && variableDescriptor.isConst()) {
923                            trace.report(Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION.on(initializer));
924                        }
925    
926                        return constant.toConstantValue(initializerType);
927                    }
928                }, null)
929            );
930        }
931    
932        @NotNull
933        private KotlinType resolveDelegatedPropertyType(
934                @NotNull KtProperty property,
935                @NotNull PropertyDescriptor propertyDescriptor,
936                @NotNull LexicalScope scope,
937                @NotNull KtExpression delegateExpression,
938                @NotNull DataFlowInfo dataFlowInfo,
939                @NotNull BindingTrace trace
940        ) {
941            LexicalScope accessorScope = JetScopeUtils.makeScopeForPropertyAccessor(propertyDescriptor, scope, trace);
942    
943            KotlinType type = delegatedPropertyResolver.resolveDelegateExpression(
944                    delegateExpression, property, propertyDescriptor, scope, accessorScope, trace, dataFlowInfo);
945    
946            if (type != null) {
947                KotlinType getterReturnType = delegatedPropertyResolver
948                        .getDelegatedPropertyGetMethodReturnType(propertyDescriptor, delegateExpression, type, trace, accessorScope);
949                if (getterReturnType != null) {
950                    return getterReturnType;
951                }
952            }
953            return ErrorUtils.createErrorType("Type from delegate");
954        }
955    
956        @Nullable
957        /*package*/ static KotlinType transformAnonymousTypeIfNeeded(
958                @NotNull DeclarationDescriptorWithVisibility descriptor,
959                @NotNull KtNamedDeclaration declaration,
960                @NotNull KotlinType type,
961                @NotNull BindingTrace trace
962        ) {
963            ClassifierDescriptor classifier = type.getConstructor().getDeclarationDescriptor();
964            if (classifier == null || !DescriptorUtils.isAnonymousObject(classifier) || DescriptorUtils.isLocal(descriptor)) {
965                return type;
966            }
967    
968            boolean definedInClass = DescriptorUtils.getParentOfType(descriptor, ClassDescriptor.class) != null;
969            if (!definedInClass || !Visibilities.isPrivate(descriptor.getVisibility())) {
970                if (type.getConstructor().getSupertypes().size() == 1) {
971                    return type.getConstructor().getSupertypes().iterator().next();
972                }
973                else {
974                    trace.report(AMBIGUOUS_ANONYMOUS_TYPE_INFERRED.on(declaration, type.getConstructor().getSupertypes()));
975                }
976            }
977    
978            return type;
979        }
980    
981        @NotNull
982        private KotlinType resolveInitializerType(
983                @NotNull LexicalScope scope,
984                @NotNull KtExpression initializer,
985                @NotNull DataFlowInfo dataFlowInfo,
986                @NotNull BindingTrace trace
987        ) {
988            return expressionTypingServices.safeGetType(scope, initializer, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, trace);
989        }
990    
991        @Nullable
992        private PropertySetterDescriptor resolvePropertySetterDescriptor(
993                @NotNull LexicalScope scope,
994                @NotNull KtProperty property,
995                @NotNull PropertyDescriptor propertyDescriptor,
996                @NotNull AnnotationSplitter annotationSplitter,
997                BindingTrace trace
998        ) {
999            KtPropertyAccessor setter = property.getSetter();
1000            PropertySetterDescriptorImpl setterDescriptor = null;
1001            if (setter != null) {
1002                Annotations annotations = new CompositeAnnotations(CollectionsKt.listOf(
1003                        annotationSplitter.getAnnotationsForTarget(PROPERTY_SETTER),
1004                        annotationResolver.resolveAnnotationsWithoutArguments(scope, setter.getModifierList(), trace)));
1005                KtParameter parameter = setter.getParameter();
1006    
1007                setterDescriptor = new PropertySetterDescriptorImpl(propertyDescriptor, annotations,
1008                                                                    resolveModalityFromModifiers(setter, propertyDescriptor.getModality()),
1009                                                                    resolveVisibilityFromModifiers(setter, propertyDescriptor.getVisibility()),
1010                                                                    setter.hasBody(), false, setter.hasModifier(EXTERNAL_KEYWORD),
1011                                                                    CallableMemberDescriptor.Kind.DECLARATION, null, KotlinSourceElementKt
1012                                                                            .toSourceElement(setter));
1013                KtTypeReference returnTypeReference = setter.getReturnTypeReference();
1014                if (returnTypeReference != null) {
1015                    KotlinType returnType = typeResolver.resolveType(scope, returnTypeReference, trace, true);
1016                    if (!KotlinBuiltIns.isUnit(returnType)) {
1017                        trace.report(WRONG_SETTER_RETURN_TYPE.on(returnTypeReference));
1018                    }
1019                }
1020    
1021                if (parameter != null) {
1022    
1023                    // This check is redundant: the parser does not allow a default value, but we'll keep it just in case
1024                    if (parameter.hasDefaultValue()) {
1025                        trace.report(SETTER_PARAMETER_WITH_DEFAULT_VALUE.on(parameter.getDefaultValue()));
1026                    }
1027    
1028                    KotlinType type;
1029                    KtTypeReference typeReference = parameter.getTypeReference();
1030                    if (typeReference == null) {
1031                        type = propertyDescriptor.getType(); // TODO : this maybe unknown at this point
1032                    }
1033                    else {
1034                        type = typeResolver.resolveType(scope, typeReference, trace, true);
1035                        KotlinType inType = propertyDescriptor.getType();
1036                        if (inType != null) {
1037                            if (!TypeUtils.equalTypes(type, inType)) {
1038                                trace.report(WRONG_SETTER_PARAMETER_TYPE.on(typeReference, inType, type));
1039                            }
1040                        }
1041                        else {
1042                            // TODO : the same check may be needed later???
1043                        }
1044                    }
1045    
1046                    ValueParameterDescriptorImpl valueParameterDescriptor =
1047                            resolveValueParameterDescriptor(scope, setterDescriptor, parameter, 0, type, trace);
1048                    setterDescriptor.initialize(valueParameterDescriptor);
1049                }
1050                else {
1051                    setterDescriptor.initializeDefault();
1052                }
1053    
1054                trace.record(BindingContext.PROPERTY_ACCESSOR, setter, setterDescriptor);
1055            }
1056            else if (property.isVar()) {
1057                Annotations setterAnnotations = annotationSplitter.getAnnotationsForTarget(PROPERTY_SETTER);
1058                setterDescriptor = DescriptorFactory.createSetter(propertyDescriptor, setterAnnotations, !property.hasDelegate(),
1059                                                                  /* isExternal = */ false, propertyDescriptor.getSource());
1060            }
1061    
1062            if (!property.isVar()) {
1063                if (setter != null) {
1064                    //                trace.getErrorHandler().genericError(setter.asElement().getNode(), "A 'val'-property cannot have a setter");
1065                    trace.report(VAL_WITH_SETTER.on(setter));
1066                }
1067            }
1068            return setterDescriptor;
1069        }
1070    
1071        @Nullable
1072        private PropertyGetterDescriptorImpl resolvePropertyGetterDescriptor(
1073                @NotNull LexicalScope scope,
1074                @NotNull KtProperty property,
1075                @NotNull PropertyDescriptor propertyDescriptor,
1076                @NotNull AnnotationSplitter annotationSplitter,
1077                BindingTrace trace
1078        ) {
1079            PropertyGetterDescriptorImpl getterDescriptor;
1080            KtPropertyAccessor getter = property.getGetter();
1081            if (getter != null) {
1082                Annotations getterAnnotations = new CompositeAnnotations(CollectionsKt.listOf(
1083                        annotationSplitter.getAnnotationsForTarget(PROPERTY_GETTER),
1084                        annotationResolver.resolveAnnotationsWithoutArguments(scope, getter.getModifierList(), trace)));
1085    
1086                KotlinType outType = propertyDescriptor.getType();
1087                KotlinType returnType = outType;
1088                KtTypeReference returnTypeReference = getter.getReturnTypeReference();
1089                if (returnTypeReference != null) {
1090                    returnType = typeResolver.resolveType(scope, returnTypeReference, trace, true);
1091                    if (outType != null && !TypeUtils.equalTypes(returnType, outType)) {
1092                        trace.report(WRONG_GETTER_RETURN_TYPE.on(returnTypeReference, propertyDescriptor.getReturnType(), outType));
1093                    }
1094                }
1095    
1096                getterDescriptor = new PropertyGetterDescriptorImpl(propertyDescriptor, getterAnnotations,
1097                                                                    resolveModalityFromModifiers(getter, propertyDescriptor.getModality()),
1098                                                                    resolveVisibilityFromModifiers(getter, propertyDescriptor.getVisibility()),
1099                                                                    getter.hasBody(), false, getter.hasModifier(EXTERNAL_KEYWORD),
1100                                                                    CallableMemberDescriptor.Kind.DECLARATION, null, KotlinSourceElementKt
1101                                                                            .toSourceElement(getter));
1102                getterDescriptor.initialize(returnType);
1103                trace.record(BindingContext.PROPERTY_ACCESSOR, getter, getterDescriptor);
1104            }
1105            else {
1106                Annotations getterAnnotations = annotationSplitter.getAnnotationsForTarget(PROPERTY_GETTER);
1107                getterDescriptor = DescriptorFactory.createGetter(propertyDescriptor, getterAnnotations, !property.hasDelegate(),
1108                                                                  /* isExternal = */ false);
1109                getterDescriptor.initialize(propertyDescriptor.getType());
1110            }
1111            return getterDescriptor;
1112        }
1113    
1114        @NotNull
1115        public PropertyDescriptor resolvePrimaryConstructorParameterToAProperty(
1116                @NotNull ClassDescriptor classDescriptor,
1117                @NotNull ValueParameterDescriptor valueParameter,
1118                @NotNull LexicalScope scope,
1119                @NotNull KtParameter parameter, final BindingTrace trace
1120        ) {
1121            KotlinType type = resolveParameterType(scope, parameter, trace);
1122            Name name = parameter.getNameAsSafeName();
1123            boolean isMutable = parameter.isMutable();
1124            KtModifierList modifierList = parameter.getModifierList();
1125    
1126            if (modifierList != null) {
1127                if (modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
1128                    trace.report(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS.on(parameter));
1129                }
1130            }
1131    
1132            final AnnotationSplitter.PropertyWrapper propertyWrapper = new AnnotationSplitter.PropertyWrapper();
1133            Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scope, parameter.getModifierList(), trace);
1134            AnnotationSplitter annotationSplitter =
1135                    new AnnotationSplitter(storageManager, allAnnotations, new Function0<Set<AnnotationUseSiteTarget>>() {
1136                        @Override
1137                        public Set<AnnotationUseSiteTarget> invoke() {
1138                            return AnnotationSplitter.getTargetSet(true, trace.getBindingContext(), propertyWrapper);
1139                        }
1140                    });
1141    
1142            Annotations propertyAnnotations = new CompositeAnnotations(
1143                    annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD),
1144                    annotationSplitter.getOtherAnnotations());
1145    
1146            PropertyDescriptorImpl propertyDescriptor = PropertyDescriptorImpl.create(
1147                    classDescriptor,
1148                    propertyAnnotations,
1149                    resolveModalityFromModifiers(parameter, Modality.FINAL),
1150                    resolveVisibilityFromModifiers(parameter, getDefaultVisibility(parameter, classDescriptor)),
1151                    isMutable,
1152                    name,
1153                    CallableMemberDescriptor.Kind.DECLARATION,
1154                    KotlinSourceElementKt.toSourceElement(parameter),
1155                    /* lateInit = */ false,
1156                    /* isConst = */ false
1157            );
1158            propertyWrapper.setProperty(propertyDescriptor);
1159            propertyDescriptor.setType(type, Collections.<TypeParameterDescriptor>emptyList(),
1160                                       getDispatchReceiverParameterIfNeeded(classDescriptor), (ReceiverParameterDescriptor) null);
1161    
1162            Annotations setterAnnotations = annotationSplitter.getAnnotationsForTarget(PROPERTY_SETTER);
1163            Annotations getterAnnotations = new CompositeAnnotations(CollectionsKt.listOf(
1164                    annotationSplitter.getAnnotationsForTarget(PROPERTY_GETTER)));
1165    
1166            PropertyGetterDescriptorImpl getter = DescriptorFactory.createDefaultGetter(propertyDescriptor, getterAnnotations);
1167            PropertySetterDescriptor setter =
1168                    propertyDescriptor.isVar() ? DescriptorFactory.createDefaultSetter(propertyDescriptor, setterAnnotations) : null;
1169    
1170            propertyDescriptor.initialize(getter, setter);
1171            getter.initialize(propertyDescriptor.getType());
1172    
1173            trace.record(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, parameter, propertyDescriptor);
1174            trace.record(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter, propertyDescriptor);
1175            return propertyDescriptor;
1176        }
1177    
1178        public static void checkBounds(@NotNull KtTypeReference typeReference, @NotNull KotlinType type, @NotNull BindingTrace trace) {
1179            if (type.isError()) return;
1180    
1181            KtTypeElement typeElement = typeReference.getTypeElement();
1182            if (typeElement == null) return;
1183    
1184            List<TypeParameterDescriptor> parameters = type.getConstructor().getParameters();
1185            List<TypeProjection> arguments = type.getArguments();
1186            assert parameters.size() == arguments.size();
1187    
1188            List<KtTypeReference> jetTypeArguments = typeElement.getTypeArgumentsAsTypes();
1189    
1190            // A type reference from Kotlin code can yield a flexible type only if it's `ft<T1, T2>`, whose bounds should not be checked
1191            if (FlexibleTypesKt.isFlexible(type) && !DynamicTypesKt.isDynamic(type)) {
1192                assert jetTypeArguments.size() == 2
1193                        : "Flexible type cannot be denoted in Kotlin otherwise than as ft<T1, T2>, but was: "
1194                          + PsiUtilsKt.getElementTextWithContext(typeReference);
1195                // it's really ft<Foo, Bar>
1196                Flexibility flexibility = FlexibleTypesKt.flexibility(type);
1197                checkBounds(jetTypeArguments.get(0), flexibility.getLowerBound(), trace);
1198                checkBounds(jetTypeArguments.get(1), flexibility.getUpperBound(), trace);
1199                return;
1200            }
1201    
1202            assert jetTypeArguments.size() == arguments.size() : typeElement.getText() + ": " + jetTypeArguments + " - " + arguments;
1203    
1204            TypeSubstitutor substitutor = TypeSubstitutor.create(type);
1205            for (int i = 0; i < jetTypeArguments.size(); i++) {
1206                KtTypeReference jetTypeArgument = jetTypeArguments.get(i);
1207    
1208                if (jetTypeArgument == null) continue;
1209    
1210                KotlinType typeArgument = arguments.get(i).getType();
1211                checkBounds(jetTypeArgument, typeArgument, trace);
1212    
1213                TypeParameterDescriptor typeParameterDescriptor = parameters.get(i);
1214                checkBounds(jetTypeArgument, typeArgument, typeParameterDescriptor, substitutor, trace);
1215            }
1216        }
1217    
1218        public static void checkBounds(
1219                @NotNull KtTypeReference jetTypeArgument,
1220                @NotNull KotlinType typeArgument,
1221                @NotNull TypeParameterDescriptor typeParameterDescriptor,
1222                @NotNull TypeSubstitutor substitutor,
1223                @NotNull BindingTrace trace
1224        ) {
1225            for (KotlinType bound : typeParameterDescriptor.getUpperBounds()) {
1226                KotlinType substitutedBound = substitutor.safeSubstitute(bound, Variance.INVARIANT);
1227                if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(typeArgument, substitutedBound)) {
1228                    trace.report(UPPER_BOUND_VIOLATED.on(jetTypeArgument, substitutedBound, typeArgument));
1229                }
1230            }
1231        }
1232    
1233        public static boolean checkHasOuterClassInstance(
1234                @NotNull LexicalScope scope,
1235                @NotNull BindingTrace trace,
1236                @NotNull PsiElement reportErrorsOn,
1237                @NotNull ClassDescriptor target
1238        ) {
1239            ClassDescriptor classDescriptor = getContainingClass(scope);
1240    
1241            if (!isInsideOuterClassOrItsSubclass(classDescriptor, target)) {
1242                return true;
1243            }
1244    
1245            while (classDescriptor != null) {
1246                if (isSubclass(classDescriptor, target)) {
1247                    return true;
1248                }
1249    
1250                if (isStaticNestedClass(classDescriptor)) {
1251                    trace.report(INACCESSIBLE_OUTER_CLASS_EXPRESSION.on(reportErrorsOn, classDescriptor));
1252                    return false;
1253                }
1254                classDescriptor = getParentOfType(classDescriptor, ClassDescriptor.class, true);
1255            }
1256            return true;
1257        }
1258    
1259        private static boolean isInsideOuterClassOrItsSubclass(@Nullable DeclarationDescriptor nested, @NotNull ClassDescriptor outer) {
1260            if (nested == null) return false;
1261    
1262            if (nested instanceof ClassDescriptor && isSubclass((ClassDescriptor) nested, outer)) return true;
1263    
1264            return isInsideOuterClassOrItsSubclass(nested.getContainingDeclaration(), outer);
1265        }
1266    
1267        @Nullable
1268        public static ClassDescriptor getContainingClass(@NotNull LexicalScope scope) {
1269            return getParentOfType(scope.getOwnerDescriptor(), ClassDescriptor.class, false);
1270        }
1271    
1272        public static void registerFileInPackage(@NotNull BindingTrace trace, @NotNull KtFile file) {
1273            // Register files corresponding to this package
1274            // The trace currently does not support bi-di multimaps that would handle this task nicer
1275            FqName fqName = file.getPackageFqName();
1276            Collection<KtFile> files = trace.get(PACKAGE_TO_FILES, fqName);
1277            if (files == null) {
1278                files = Sets.newIdentityHashSet();
1279            }
1280            files.add(file);
1281            trace.record(BindingContext.PACKAGE_TO_FILES, fqName, files);
1282        }
1283    }