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