001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.lang.resolve.calls;
018    
019    import com.google.common.base.Function;
020    import com.google.common.collect.Lists;
021    import com.google.common.collect.Maps;
022    import com.google.common.collect.Sets;
023    import com.intellij.openapi.progress.ProgressIndicatorProvider;
024    import com.intellij.psi.PsiElement;
025    import org.jetbrains.annotations.NotNull;
026    import org.jetbrains.annotations.Nullable;
027    import org.jetbrains.jet.lang.descriptors.*;
028    import org.jetbrains.jet.lang.psi.*;
029    import org.jetbrains.jet.lang.resolve.*;
030    import org.jetbrains.jet.lang.resolve.calls.autocasts.*;
031    import org.jetbrains.jet.lang.resolve.calls.context.*;
032    import org.jetbrains.jet.lang.resolve.calls.inference.*;
033    import org.jetbrains.jet.lang.resolve.calls.model.*;
034    import org.jetbrains.jet.lang.resolve.calls.results.ResolutionDebugInfo;
035    import org.jetbrains.jet.lang.resolve.calls.results.ResolutionStatus;
036    import org.jetbrains.jet.lang.resolve.calls.tasks.ResolutionTask;
037    import org.jetbrains.jet.lang.resolve.calls.tasks.TaskPrioritizer;
038    import org.jetbrains.jet.lang.resolve.calls.util.ExpressionAsFunctionDescriptor;
039    import org.jetbrains.jet.lang.resolve.scopes.receivers.ExpressionReceiver;
040    import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue;
041    import org.jetbrains.jet.lang.types.*;
042    import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
043    import org.jetbrains.jet.lang.types.expressions.DataFlowUtils;
044    import org.jetbrains.jet.lang.types.expressions.ExpressionTypingUtils;
045    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
046    
047    import javax.inject.Inject;
048    import java.util.*;
049    
050    import static org.jetbrains.jet.lang.diagnostics.Errors.PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT;
051    import static org.jetbrains.jet.lang.diagnostics.Errors.SUPER_IS_NOT_AN_EXPRESSION;
052    import static org.jetbrains.jet.lang.resolve.calls.CallResolverUtil.ResolveArgumentsMode.RESOLVE_FUNCTION_ARGUMENTS;
053    import static org.jetbrains.jet.lang.resolve.calls.CallResolverUtil.ResolveArgumentsMode.SHAPE_FUNCTION_ARGUMENTS;
054    import static org.jetbrains.jet.lang.resolve.calls.CallTransformer.CallForImplicitInvoke;
055    import static org.jetbrains.jet.lang.resolve.calls.context.ContextDependency.INDEPENDENT;
056    import static org.jetbrains.jet.lang.resolve.calls.results.ResolutionStatus.*;
057    import static org.jetbrains.jet.lang.types.TypeUtils.*;
058    
059    public class CandidateResolver {
060        @NotNull
061        private ArgumentTypeResolver argumentTypeResolver;
062    
063        @Inject
064        public void setArgumentTypeResolver(@NotNull ArgumentTypeResolver argumentTypeResolver) {
065            this.argumentTypeResolver = argumentTypeResolver;
066        }
067    
068        public <D extends CallableDescriptor, F extends D> void performResolutionForCandidateCall(
069                @NotNull CallCandidateResolutionContext<D> context,
070                @NotNull ResolutionTask<D, F> task) {
071    
072            ProgressIndicatorProvider.checkCanceled();
073    
074            ResolvedCallImpl<D> candidateCall = context.candidateCall;
075            D candidate = candidateCall.getCandidateDescriptor();
076    
077            candidateCall.addStatus(checkReceiverTypeError(context.candidateCall));
078    
079            if (ErrorUtils.isError(candidate)) {
080                candidateCall.addStatus(SUCCESS);
081                markAllArgumentsAsUnmapped(context);
082                return;
083            }
084    
085            if (!checkOuterClassMemberIsAccessible(context)) {
086                candidateCall.addStatus(OTHER_ERROR);
087                markAllArgumentsAsUnmapped(context);
088                return;
089            }
090    
091    
092            DeclarationDescriptorWithVisibility invisibleMember =
093                    Visibilities.findInvisibleMember(candidate, context.scope.getContainingDeclaration());
094            if (invisibleMember != null) {
095                candidateCall.addStatus(OTHER_ERROR);
096                context.tracing.invisibleMember(context.trace, invisibleMember);
097                markAllArgumentsAsUnmapped(context);
098                return;
099            }
100    
101            if (task.checkArguments == CheckValueArgumentsMode.ENABLED) {
102                Set<ValueArgument> unmappedArguments = Sets.newLinkedHashSet();
103                ValueArgumentsToParametersMapper.Status
104                        argumentMappingStatus = ValueArgumentsToParametersMapper.mapValueArgumentsToParameters(context.call, context.tracing,
105                                                                                                                candidateCall, unmappedArguments);
106                if (!argumentMappingStatus.isSuccess()) {
107                    if (argumentMappingStatus == ValueArgumentsToParametersMapper.Status.STRONG_ERROR) {
108                        candidateCall.addStatus(RECEIVER_PRESENCE_ERROR);
109                    }
110                    else {
111                        candidateCall.addStatus(OTHER_ERROR);
112                    }
113                    candidateCall.setUnmappedArguments(unmappedArguments);
114                    if ((argumentMappingStatus == ValueArgumentsToParametersMapper.Status.ERROR && candidate.getTypeParameters().isEmpty()) ||
115                        argumentMappingStatus == ValueArgumentsToParametersMapper.Status.STRONG_ERROR) {
116                        return;
117                    }
118                }
119            }
120    
121            List<JetTypeProjection> jetTypeArguments = context.call.getTypeArguments();
122            if (jetTypeArguments.isEmpty()) {
123                if (!candidate.getTypeParameters().isEmpty()) {
124                    ResolutionStatus status = inferTypeArguments(context);
125                    candidateCall.addStatus(status);
126                }
127                else {
128                    candidateCall.addStatus(checkAllValueArguments(context, SHAPE_FUNCTION_ARGUMENTS).status);
129                }
130            }
131            else {
132                // Explicit type arguments passed
133    
134                List<JetType> typeArguments = new ArrayList<JetType>();
135                for (JetTypeProjection projection : jetTypeArguments) {
136                    if (projection.getProjectionKind() != JetProjectionKind.NONE) {
137                        context.trace.report(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT.on(projection));
138                    }
139                    typeArguments.add(argumentTypeResolver.resolveTypeRefWithDefault(
140                            projection.getTypeReference(), context.scope, context.trace, ErrorUtils.createErrorType("Star projection in a call")));
141                }
142                int expectedTypeArgumentCount = candidate.getTypeParameters().size();
143                if (expectedTypeArgumentCount == jetTypeArguments.size()) {
144    
145                    checkGenericBoundsInAFunctionCall(jetTypeArguments, typeArguments, candidate, context.trace);
146    
147                    Map<TypeConstructor, TypeProjection>
148                            substitutionContext = FunctionDescriptorUtil
149                            .createSubstitutionContext((FunctionDescriptor) candidate, typeArguments);
150                    TypeSubstitutor substitutor = TypeSubstitutor.create(substitutionContext);
151                    candidateCall.setResultingSubstitutor(substitutor);
152    
153                    candidateCall.addStatus(checkAllValueArguments(context, SHAPE_FUNCTION_ARGUMENTS).status);
154                }
155                else {
156                    candidateCall.addStatus(OTHER_ERROR);
157                    context.tracing.wrongNumberOfTypeArguments(context.trace, expectedTypeArgumentCount);
158                }
159            }
160    
161            task.performAdvancedChecks(candidate, context.trace, context.tracing);
162    
163            // 'super' cannot be passed as an argument, for receiver arguments expression typer does not track this
164            // See TaskPrioritizer for more
165            JetSuperExpression superExpression = TaskPrioritizer.getReceiverSuper(candidateCall.getReceiverArgument());
166            if (superExpression != null) {
167                context.trace.report(SUPER_IS_NOT_AN_EXPRESSION.on(superExpression, superExpression.getText()));
168                candidateCall.addStatus(OTHER_ERROR);
169            }
170    
171            AutoCastUtils.recordAutoCastIfNecessary(candidateCall.getReceiverArgument(), candidateCall.getTrace());
172            AutoCastUtils.recordAutoCastIfNecessary(candidateCall.getThisObject(), candidateCall.getTrace());
173        }
174    
175        private static void markAllArgumentsAsUnmapped(CallCandidateResolutionContext<?> context) {
176            if (context.checkArguments == CheckValueArgumentsMode.ENABLED) {
177                context.candidateCall.setUnmappedArguments(context.call.getValueArguments());
178            }
179        }
180    
181        private static boolean checkOuterClassMemberIsAccessible(@NotNull CallCandidateResolutionContext<?> context) {
182            // In "this@Outer.foo()" the error will be reported on "this@Outer" instead
183            if (context.call.getExplicitReceiver().exists() || context.call.getThisObject().exists()) return true;
184    
185            ClassDescriptor candidateThis = getDeclaringClass(context.candidateCall.getCandidateDescriptor());
186            if (candidateThis == null || candidateThis.getKind().isSingleton()) return true;
187    
188            return DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, context.call.getCallElement(), candidateThis);
189        }
190    
191        @Nullable
192        private static ClassDescriptor getDeclaringClass(@NotNull CallableDescriptor candidate) {
193            ReceiverParameterDescriptor expectedThis = candidate.getExpectedThisObject();
194            if (expectedThis == null) return null;
195            DeclarationDescriptor descriptor = expectedThis.getContainingDeclaration();
196            return descriptor instanceof ClassDescriptor ? (ClassDescriptor) descriptor : null;
197        }
198    
199        public <D extends CallableDescriptor> void completeTypeInferenceDependentOnFunctionLiteralsForCall(
200                CallCandidateResolutionContext<D> context
201        ) {
202            ResolvedCallImpl<D> resolvedCall = context.candidateCall;
203            ConstraintSystem constraintSystem = resolvedCall.getConstraintSystem();
204            if (!resolvedCall.hasIncompleteTypeParameters() || constraintSystem == null) return;
205    
206            // constraints for function literals
207            // Value parameters
208            for (Map.Entry<ValueParameterDescriptor, ResolvedValueArgument> entry : resolvedCall.getValueArguments().entrySet()) {
209                ResolvedValueArgument resolvedValueArgument = entry.getValue();
210                ValueParameterDescriptor valueParameterDescriptor = entry.getKey();
211    
212                for (ValueArgument valueArgument : resolvedValueArgument.getArguments()) {
213                    addConstraintForFunctionLiteral(valueArgument, valueParameterDescriptor, constraintSystem, context);
214                }
215            }
216            resolvedCall.setResultingSubstitutor(constraintSystem.getResultingSubstitutor());
217        }
218    
219        @Nullable
220        public <D extends CallableDescriptor> JetType completeTypeInferenceDependentOnExpectedTypeForCall(
221                @NotNull CallCandidateResolutionContext<D> context,
222                boolean isInnerCall
223        ) {
224            ResolvedCallImpl<D> resolvedCall = context.candidateCall;
225            assert resolvedCall.hasIncompleteTypeParameters();
226            assert resolvedCall.getConstraintSystem() != null;
227    
228            JetType unsubstitutedReturnType = resolvedCall.getCandidateDescriptor().getReturnType();
229            if (unsubstitutedReturnType != null) {
230                resolvedCall.getConstraintSystem().addSupertypeConstraint(
231                        context.expectedType, unsubstitutedReturnType, ConstraintPosition.EXPECTED_TYPE_POSITION);
232            }
233    
234            updateSystemWithConstraintSystemCompleter(context, resolvedCall);
235    
236            updateSystemIfExpectedTypeIsUnit(context, resolvedCall);
237    
238            ((ConstraintSystemImpl)resolvedCall.getConstraintSystem()).processDeclaredBoundConstraints();
239    
240            if (!resolvedCall.getConstraintSystem().getStatus().isSuccessful()) {
241                return reportInferenceError(context);
242            }
243            resolvedCall.setResultingSubstitutor(resolvedCall.getConstraintSystem().getResultingSubstitutor());
244    
245            completeNestedCallsInference(context);
246            // Here we type check the arguments with inferred types expected
247            checkAllValueArguments(context, context.trace, RESOLVE_FUNCTION_ARGUMENTS);
248    
249            resolvedCall.setHasUnknownTypeParameters(false);
250            ResolutionStatus status = resolvedCall.getStatus();
251            if (status == ResolutionStatus.UNKNOWN_STATUS || status == ResolutionStatus.INCOMPLETE_TYPE_INFERENCE) {
252                resolvedCall.setStatusToSuccess();
253            }
254            JetType returnType = resolvedCall.getResultingDescriptor().getReturnType();
255            if (isInnerCall) {
256                PsiElement callElement = context.call.getCallElement();
257                if (callElement instanceof JetCallExpression) {
258                    DataFlowUtils.checkType(returnType, (JetCallExpression) callElement, context, context.dataFlowInfo);
259                }
260            }
261            return returnType;
262        }
263    
264        private static <D extends CallableDescriptor> void updateSystemWithConstraintSystemCompleter(
265                @NotNull CallCandidateResolutionContext<D> context,
266                @NotNull ResolvedCallImpl<D> resolvedCall
267        ) {
268            ConstraintSystem constraintSystem = resolvedCall.getConstraintSystem();
269            assert constraintSystem != null;
270            ConstraintSystemCompleter constraintSystemCompleter = context.trace.get(
271                    BindingContext.CONSTRAINT_SYSTEM_COMPLETER, context.call.getCalleeExpression());
272            if (constraintSystemCompleter == null) return;
273    
274            ConstraintSystem copy = constraintSystem.copy();
275    
276            constraintSystemCompleter.completeConstraintSystem(copy, resolvedCall);
277    
278            //todo improve error reporting with errors in constraints from completer
279            if (!copy.getStatus().hasOnlyErrorsFromPosition(ConstraintPosition.FROM_COMPLETER)) {
280                resolvedCall.setConstraintSystem(copy);
281            }
282        }
283    
284        private static <D extends CallableDescriptor> void updateSystemIfExpectedTypeIsUnit(
285                @NotNull CallCandidateResolutionContext<D> context,
286                @NotNull ResolvedCallImpl<D> resolvedCall
287        ) {
288            ConstraintSystem constraintSystem = resolvedCall.getConstraintSystem();
289            assert constraintSystem != null;
290            JetType returnType = resolvedCall.getCandidateDescriptor().getReturnType();
291            if (returnType == null) return;
292    
293            if (!constraintSystem.getStatus().isSuccessful() && context.expectedType == TypeUtils.UNIT_EXPECTED_TYPE) {
294                ConstraintSystemImpl copy = (ConstraintSystemImpl) constraintSystem.copy();
295    
296                copy.addSupertypeConstraint(KotlinBuiltIns.getInstance().getUnitType(), returnType, ConstraintPosition.EXPECTED_TYPE_POSITION);
297                if (copy.getStatus().isSuccessful()) {
298                    resolvedCall.setConstraintSystem(copy);
299                }
300            }
301        }
302    
303        private <D extends CallableDescriptor> JetType reportInferenceError(
304                @NotNull CallCandidateResolutionContext<D> context
305        ) {
306            ResolvedCallImpl<D> resolvedCall = context.candidateCall;
307            ConstraintSystem constraintSystem = resolvedCall.getConstraintSystem();
308            assert constraintSystem != null;
309    
310            resolvedCall.setResultingSubstitutor(constraintSystem.getResultingSubstitutor());
311            completeNestedCallsInference(context);
312            List<JetType> argumentTypes = checkValueArgumentTypes(
313                    context, resolvedCall, context.trace, RESOLVE_FUNCTION_ARGUMENTS).argumentTypes;
314            JetType receiverType = resolvedCall.getReceiverArgument().exists() ? resolvedCall.getReceiverArgument().getType() : null;
315            InferenceErrorData errorData = InferenceErrorData
316                    .create(resolvedCall.getCandidateDescriptor(), constraintSystem, argumentTypes, receiverType, context.expectedType);
317    
318            context.tracing.typeInferenceFailed(context.trace, errorData);
319            resolvedCall.addStatus(ResolutionStatus.OTHER_ERROR);
320            if (!resolvedCall.hasInferredReturnType()) return null;
321            return resolvedCall.getResultingDescriptor().getReturnType();
322        }
323    
324        public <D extends CallableDescriptor> void completeNestedCallsInference(
325                @NotNull CallCandidateResolutionContext<D> context
326        ) {
327            if (context.call.getCallType() == Call.CallType.INVOKE) return;
328            ResolvedCallImpl<D> resolvedCall = context.candidateCall;
329            for (Map.Entry<ValueParameterDescriptor, ResolvedValueArgument> entry : resolvedCall.getValueArguments().entrySet()) {
330                ValueParameterDescriptor parameterDescriptor = entry.getKey();
331                ResolvedValueArgument resolvedArgument = entry.getValue();
332    
333                for (ValueArgument argument : resolvedArgument.getArguments()) {
334                    completeInferenceForArgument(argument, parameterDescriptor, context);
335                }
336            }
337            completeUnmappedArguments(context, context.candidateCall.getUnmappedArguments());
338            recordReferenceForInvokeFunction(context);
339        }
340    
341        private <D extends CallableDescriptor> void completeInferenceForArgument(
342                @NotNull ValueArgument argument,
343                @NotNull ValueParameterDescriptor parameterDescriptor,
344                @NotNull CallCandidateResolutionContext<D> context
345        ) {
346            JetExpression expression = argument.getArgumentExpression();
347            if (expression == null) return;
348    
349            JetType expectedType = getEffectiveExpectedType(parameterDescriptor, argument);
350            context = context.replaceExpectedType(expectedType);
351    
352            JetExpression keyExpression = getDeferredComputationKeyExpression(expression);
353            CallCandidateResolutionContext<? extends CallableDescriptor> storedContextForArgument =
354                    context.resolutionResultsCache.getDeferredComputation(keyExpression);
355    
356            PsiElement parent = expression.getParent();
357            if (parent instanceof JetWhenExpression && expression == ((JetWhenExpression) parent).getSubjectExpression()
358                || (expression instanceof JetFunctionLiteralExpression)) {
359                return;
360            }
361            if (storedContextForArgument == null) {
362                JetType type = argumentTypeResolver.updateResultArgumentTypeIfNotDenotable(context, expression);
363                checkResultArgumentType(type, argument, context);
364                return;
365            }
366    
367            CallCandidateResolutionContext<? extends CallableDescriptor> contextForArgument = storedContextForArgument
368                    .replaceContextDependency(INDEPENDENT).replaceBindingTrace(context.trace).replaceExpectedType(expectedType);
369            JetType type;
370            if (contextForArgument.candidateCall.hasIncompleteTypeParameters()) {
371                type = completeTypeInferenceDependentOnExpectedTypeForCall(contextForArgument, true);
372            }
373            else {
374                completeNestedCallsInference(contextForArgument);
375                type = contextForArgument.candidateCall.getResultingDescriptor().getReturnType();
376                checkValueArgumentTypes(contextForArgument);
377            }
378            JetType result = BindingContextUtils.updateRecordedType(
379                    type, expression, context.trace, isFairSafeCallExpression(expression, context.trace));
380    
381            markResultingCallAsCompleted(context, keyExpression);
382    
383            DataFlowUtils.checkType(result, expression, contextForArgument);
384        }
385    
386        public void completeNestedCallsForNotResolvedInvocation(@NotNull CallResolutionContext<?> context) {
387            completeNestedCallsForNotResolvedInvocation(context, context.call.getValueArguments());
388        }
389    
390        public void completeUnmappedArguments(@NotNull CallResolutionContext<?> context, @NotNull Collection<? extends ValueArgument> unmappedArguments) {
391            completeNestedCallsForNotResolvedInvocation(context, unmappedArguments);
392        }
393    
394        private void completeNestedCallsForNotResolvedInvocation(@NotNull CallResolutionContext<?> context, @NotNull Collection<? extends ValueArgument> arguments) {
395            if (context.call.getCallType() == Call.CallType.INVOKE) return;
396            if (context.checkArguments == CheckValueArgumentsMode.DISABLED) return;
397    
398            for (ValueArgument argument : arguments) {
399                JetExpression expression = argument.getArgumentExpression();
400    
401                JetExpression keyExpression = getDeferredComputationKeyExpression(expression);
402                markResultingCallAsCompleted(context, keyExpression);
403    
404                CallCandidateResolutionContext<? extends CallableDescriptor> storedContextForArgument =
405                        context.resolutionResultsCache.getDeferredComputation(keyExpression);
406                if (storedContextForArgument != null) {
407                    completeNestedCallsForNotResolvedInvocation(storedContextForArgument);
408                    CallCandidateResolutionContext<? extends CallableDescriptor> newContext =
409                            storedContextForArgument.replaceBindingTrace(context.trace);
410                    completeUnmappedArguments(newContext, storedContextForArgument.candidateCall.getUnmappedArguments());
411                    argumentTypeResolver.checkTypesForFunctionArgumentsWithNoCallee(newContext.replaceContextDependency(INDEPENDENT));
412                }
413            }
414        }
415    
416        private static void markResultingCallAsCompleted(
417                @NotNull CallResolutionContext<?> context,
418                @Nullable JetExpression keyExpression
419        ) {
420            if (keyExpression == null) return;
421    
422            CallCandidateResolutionContext<? extends CallableDescriptor> storedContextForArgument =
423                    context.resolutionResultsCache.getDeferredComputation(keyExpression);
424            if (storedContextForArgument == null) return;
425    
426            storedContextForArgument.candidateCall.markCallAsCompleted();
427    
428            // clean data for "invoke" calls
429            ResolvedCallWithTrace<? extends CallableDescriptor> resolvedCall = context.resolutionResultsCache.getCallForArgument(keyExpression);
430            assert resolvedCall != null : "Resolved call for '" + keyExpression + "' is not stored, but CallCandidateResolutionContext is.";
431            resolvedCall.markCallAsCompleted();
432        }
433    
434        @Nullable
435        private JetExpression getDeferredComputationKeyExpression(@Nullable JetExpression expression) {
436            if (expression == null) return null;
437            return expression.accept(new JetVisitor<JetExpression, Void>() {
438                @Nullable
439                private JetExpression visitInnerExpression(@Nullable JetElement expression) {
440                    if (expression == null) return null;
441                    return expression.accept(this, null);
442                }
443    
444                @Override
445                public JetExpression visitQualifiedExpression(@NotNull JetQualifiedExpression expression, Void data) {
446                    return visitInnerExpression(expression.getSelectorExpression());
447                }
448    
449                @Override
450                public JetExpression visitExpression(@NotNull JetExpression expression, Void data) {
451                    return expression;
452                }
453    
454                @Override
455                public JetExpression visitParenthesizedExpression(@NotNull JetParenthesizedExpression expression, Void data) {
456                    return visitInnerExpression(expression.getExpression());
457                }
458    
459                @Override
460                public JetExpression visitUnaryExpression(@NotNull JetUnaryExpression expression, Void data) {
461                    return ExpressionTypingUtils.isUnaryExpressionDependentOnExpectedType(expression) ? expression : null;
462                }
463    
464                @Override
465                public JetExpression visitPrefixExpression(@NotNull JetPrefixExpression expression, Void data) {
466                    return visitInnerExpression(JetPsiUtil.getBaseExpressionIfLabeledExpression(expression));
467                }
468    
469                @Override
470                public JetExpression visitBlockExpression(@NotNull JetBlockExpression expression, Void data) {
471                    JetElement lastStatement = JetPsiUtil.getLastStatementInABlock(expression);
472                    if (lastStatement != null) {
473                        return visitInnerExpression(lastStatement);
474                    }
475                    return expression;
476                }
477    
478                @Override
479                public JetExpression visitBinaryExpression(@NotNull JetBinaryExpression expression, Void data) {
480                    return ExpressionTypingUtils.isBinaryExpressionDependentOnExpectedType(expression) ? expression : null;
481                }
482            }, null);
483        }
484    
485        private static boolean isFairSafeCallExpression(@NotNull JetExpression expression, @NotNull BindingTrace trace) {
486            // We are interested in type of the last call:
487            // 'a.b?.foo()' is safe call, but 'a?.b.foo()' is not.
488            // Since receiver is 'a.b' and selector is 'foo()',
489            // we can only check if an expression is safe call.
490            if (!(expression instanceof JetSafeQualifiedExpression)) return false;
491    
492            JetSafeQualifiedExpression safeQualifiedExpression = (JetSafeQualifiedExpression) expression;
493            //If a receiver type is not null, then this safe expression is useless, and we don't need to make the result type nullable.
494            JetType type = trace.get(BindingContext.EXPRESSION_TYPE, safeQualifiedExpression.getReceiverExpression());
495            return type != null && type.isNullable();
496        }
497    
498        private static <D extends CallableDescriptor> void checkResultArgumentType(
499                @Nullable JetType type,
500                @NotNull ValueArgument argument,
501                @NotNull CallCandidateResolutionContext<D> context
502        ) {
503            JetExpression expression = argument.getArgumentExpression();
504            if (expression == null) return;
505    
506            DataFlowInfo dataFlowInfoForValueArgument = context.candidateCall.getDataFlowInfoForArguments().getInfo(argument);
507            ResolutionContext<?> newContext = context.replaceExpectedType(context.expectedType).replaceDataFlowInfo(
508                    dataFlowInfoForValueArgument);
509            DataFlowUtils.checkType(type, expression, newContext);
510        }
511    
512        private static <D extends CallableDescriptor> void recordReferenceForInvokeFunction(CallCandidateResolutionContext<D> context) {
513            PsiElement callElement = context.call.getCallElement();
514            if (!(callElement instanceof JetCallExpression)) return;
515    
516            JetCallExpression callExpression = (JetCallExpression) callElement;
517            CallableDescriptor resultingDescriptor = context.candidateCall.getResultingDescriptor();
518            if (BindingContextUtils.isCallExpressionWithValidReference(callExpression, context.trace.getBindingContext())) {
519                context.trace.record(BindingContext.EXPRESSION_TYPE, callExpression, resultingDescriptor.getReturnType());
520                context.trace.record(BindingContext.REFERENCE_TARGET, callExpression, resultingDescriptor);
521            }
522        }
523    
524        private <D extends CallableDescriptor> void addConstraintForFunctionLiteral(
525                @NotNull ValueArgument valueArgument,
526                @NotNull ValueParameterDescriptor valueParameterDescriptor,
527                @NotNull ConstraintSystem constraintSystem,
528                @NotNull CallCandidateResolutionContext<D> context
529        ) {
530            JetExpression argumentExpression = valueArgument.getArgumentExpression();
531            if (argumentExpression == null) return;
532            if (!ArgumentTypeResolver.isFunctionLiteralArgument(argumentExpression)) return;
533    
534            JetFunctionLiteralExpression functionLiteralExpression = ArgumentTypeResolver.getFunctionLiteralArgument(argumentExpression);
535    
536            JetType effectiveExpectedType = getEffectiveExpectedType(valueParameterDescriptor, valueArgument);
537            JetType expectedType = constraintSystem.getCurrentSubstitutor().substitute(effectiveExpectedType, Variance.INVARIANT);
538            if (expectedType == null || expectedType == DONT_CARE) {
539                expectedType = argumentTypeResolver.getShapeTypeOfFunctionLiteral(functionLiteralExpression, context.scope, context.trace, false);
540            }
541            if (expectedType == null || !KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(expectedType)
542                    || CallResolverUtil.hasUnknownFunctionParameter(expectedType)) {
543                return;
544            }
545            MutableDataFlowInfoForArguments dataFlowInfoForArguments = context.candidateCall.getDataFlowInfoForArguments();
546            DataFlowInfo dataFlowInfoForArgument = dataFlowInfoForArguments.getInfo(valueArgument);
547    
548            //todo analyze function literal body once in 'dependent' mode, then complete it with respect to expected type
549            boolean hasExpectedReturnType = !CallResolverUtil.hasUnknownReturnType(expectedType);
550            if (hasExpectedReturnType) {
551                TemporaryTraceAndCache temporaryToResolveFunctionLiteral = TemporaryTraceAndCache.create(
552                        context, "trace to resolve function literal with expected return type", argumentExpression);
553    
554                JetElement statementExpression = JetPsiUtil.getLastStatementInABlock(functionLiteralExpression.getBodyExpression());
555                if (statementExpression == null) return;
556                boolean[] mismatch = new boolean[1];
557                ObservableBindingTrace errorInterceptingTrace = ExpressionTypingUtils.makeTraceInterceptingTypeMismatch(
558                        temporaryToResolveFunctionLiteral.trace, statementExpression, mismatch);
559                CallCandidateResolutionContext<D> newContext = context
560                        .replaceBindingTrace(errorInterceptingTrace).replaceExpectedType(expectedType)
561                        .replaceDataFlowInfo(dataFlowInfoForArgument).replaceResolutionResultsCache(temporaryToResolveFunctionLiteral.cache)
562                        .replaceContextDependency(INDEPENDENT);
563                JetType type = argumentTypeResolver.getFunctionLiteralTypeInfo(
564                        argumentExpression, functionLiteralExpression, newContext, RESOLVE_FUNCTION_ARGUMENTS).getType();
565                if (!mismatch[0]) {
566                    constraintSystem.addSubtypeConstraint(
567                            type, effectiveExpectedType, ConstraintPosition.getValueParameterPosition(valueParameterDescriptor.getIndex()));
568                    temporaryToResolveFunctionLiteral.commit();
569                    return;
570                }
571            }
572            JetType expectedTypeWithoutReturnType = hasExpectedReturnType ? CallResolverUtil.replaceReturnTypeByUnknown(expectedType) : expectedType;
573            CallCandidateResolutionContext<D> newContext = context
574                    .replaceExpectedType(expectedTypeWithoutReturnType).replaceDataFlowInfo(dataFlowInfoForArgument)
575                    .replaceContextDependency(INDEPENDENT);
576            JetType type = argumentTypeResolver.getFunctionLiteralTypeInfo(argumentExpression, functionLiteralExpression, newContext,
577                                                                           RESOLVE_FUNCTION_ARGUMENTS).getType();
578            constraintSystem.addSubtypeConstraint(
579                    type, effectiveExpectedType, ConstraintPosition.getValueParameterPosition(valueParameterDescriptor.getIndex()));
580        }
581    
582        private <D extends CallableDescriptor> ResolutionStatus inferTypeArguments(CallCandidateResolutionContext<D> context) {
583            ResolvedCallImpl<D> candidateCall = context.candidateCall;
584            final D candidate = candidateCall.getCandidateDescriptor();
585    
586            context.trace.get(ResolutionDebugInfo.RESOLUTION_DEBUG_INFO, context.call.getCallElement());
587    
588            ConstraintSystemImpl constraintSystem = new ConstraintSystemImpl();
589    
590            // If the call is recursive, e.g.
591            //   fun foo<T>(t : T) : T = foo(t)
592            // we can't use same descriptor objects for T's as actual type values and same T's as unknowns,
593            // because constraints become trivial (T :< T), and inference fails
594            //
595            // Thus, we replace the parameters of our descriptor with fresh objects (perform alpha-conversion)
596            CallableDescriptor candidateWithFreshVariables = FunctionDescriptorUtil.alphaConvertTypeParameters(candidate);
597    
598            Map<TypeParameterDescriptor, Variance> typeVariables = Maps.newLinkedHashMap();
599            for (TypeParameterDescriptor typeParameterDescriptor : candidateWithFreshVariables.getTypeParameters()) {
600                typeVariables.put(typeParameterDescriptor, Variance.INVARIANT); // TODO: variance of the occurrences
601            }
602            constraintSystem.registerTypeVariables(typeVariables);
603    
604            TypeSubstitutor substituteDontCare =
605                    makeConstantSubstitutor(candidateWithFreshVariables.getTypeParameters(), DONT_CARE);
606    
607            // Value parameters
608            for (Map.Entry<ValueParameterDescriptor, ResolvedValueArgument> entry : candidateCall.getValueArguments().entrySet()) {
609                ResolvedValueArgument resolvedValueArgument = entry.getValue();
610                ValueParameterDescriptor valueParameterDescriptor = candidateWithFreshVariables.getValueParameters().get(entry.getKey().getIndex());
611    
612    
613                for (ValueArgument valueArgument : resolvedValueArgument.getArguments()) {
614                    // TODO : more attempts, with different expected types
615    
616                    // Here we type check expecting an error type (DONT_CARE, substitution with substituteDontCare)
617                    // and throw the results away
618                    // We'll type check the arguments later, with the inferred types expected
619                    boolean[] isErrorType = new boolean[1];
620                    addConstraintForValueArgument(valueArgument, valueParameterDescriptor, substituteDontCare, constraintSystem,
621                                                  context, isErrorType, SHAPE_FUNCTION_ARGUMENTS);
622                    if (isErrorType[0]) {
623                        candidateCall.argumentHasNoType();
624                    }
625                }
626            }
627    
628            // Receiver
629            // Error is already reported if something is missing
630            ReceiverValue receiverArgument = candidateCall.getReceiverArgument();
631            ReceiverParameterDescriptor receiverParameter = candidateWithFreshVariables.getReceiverParameter();
632            if (receiverArgument.exists() && receiverParameter != null) {
633                JetType receiverType =
634                        context.candidateCall.isSafeCall()
635                        ? TypeUtils.makeNotNullable(receiverArgument.getType())
636                        : receiverArgument.getType();
637                constraintSystem.addSubtypeConstraint(receiverType, receiverParameter.getType(), ConstraintPosition.RECEIVER_POSITION);
638            }
639    
640            // Restore type variables before alpha-conversion
641            ConstraintSystem constraintSystemWithRightTypeParameters = constraintSystem.substituteTypeVariables(
642                    new Function<TypeParameterDescriptor, TypeParameterDescriptor>() {
643                        @Override
644                        public TypeParameterDescriptor apply(@Nullable TypeParameterDescriptor typeParameterDescriptor) {
645                            assert typeParameterDescriptor != null;
646                            return candidate.getTypeParameters().get(typeParameterDescriptor.getIndex());
647                        }
648                    });
649            candidateCall.setConstraintSystem(constraintSystemWithRightTypeParameters);
650    
651    
652            // Solution
653            boolean hasContradiction = constraintSystem.getStatus().hasContradiction();
654            candidateCall.setHasUnknownTypeParameters(true);
655            if (!hasContradiction) {
656                return INCOMPLETE_TYPE_INFERENCE;
657            }
658            ValueArgumentsCheckingResult checkingResult = checkAllValueArguments(context, SHAPE_FUNCTION_ARGUMENTS);
659            ResolutionStatus argumentsStatus = checkingResult.status;
660            return OTHER_ERROR.combine(argumentsStatus);
661        }
662    
663        private void addConstraintForValueArgument(
664                @NotNull ValueArgument valueArgument,
665                @NotNull ValueParameterDescriptor valueParameterDescriptor,
666                @NotNull TypeSubstitutor substitutor,
667                @NotNull ConstraintSystem constraintSystem,
668                @NotNull CallCandidateResolutionContext<?> context,
669                @Nullable boolean[] isErrorType,
670                @NotNull CallResolverUtil.ResolveArgumentsMode resolveFunctionArgumentBodies) {
671    
672            JetType effectiveExpectedType = getEffectiveExpectedType(valueParameterDescriptor, valueArgument);
673            JetExpression argumentExpression = valueArgument.getArgumentExpression();
674    
675            JetType expectedType = substitutor.substitute(effectiveExpectedType, Variance.INVARIANT);
676            DataFlowInfo dataFlowInfoForArgument = context.candidateCall.getDataFlowInfoForArguments().getInfo(valueArgument);
677            CallResolutionContext<?> newContext = context.replaceExpectedType(expectedType).replaceDataFlowInfo(dataFlowInfoForArgument);
678    
679            JetTypeInfo typeInfoForCall = argumentTypeResolver.getArgumentTypeInfo(
680                    argumentExpression, newContext, resolveFunctionArgumentBodies);
681            context.candidateCall.getDataFlowInfoForArguments().updateInfo(valueArgument, typeInfoForCall.getDataFlowInfo());
682    
683            JetType type = updateResultTypeForSmartCasts(typeInfoForCall.getType(), argumentExpression, dataFlowInfoForArgument, context.trace);
684            constraintSystem.addSubtypeConstraint(type, effectiveExpectedType, ConstraintPosition.getValueParameterPosition(
685                    valueParameterDescriptor.getIndex()));
686            if (isErrorType != null) {
687                isErrorType[0] = type == null || type.isError();
688            }
689        }
690    
691        @Nullable
692        private static JetType updateResultTypeForSmartCasts(
693                @Nullable JetType type,
694                @Nullable JetExpression argumentExpression,
695                @NotNull DataFlowInfo dataFlowInfoForArgument,
696                @NotNull BindingTrace trace
697        ) {
698            if (argumentExpression == null || type == null) return type;
699    
700            DataFlowValue dataFlowValue = DataFlowValueFactory.createDataFlowValue(
701                    argumentExpression, type, trace.getBindingContext());
702            if (!dataFlowValue.isStableIdentifier()) return type;
703    
704            Set<JetType> possibleTypes = dataFlowInfoForArgument.getPossibleTypes(dataFlowValue);
705            if (possibleTypes.isEmpty()) return type;
706    
707            return TypeUtils.intersect(JetTypeChecker.INSTANCE, possibleTypes);
708        }
709    
710        private <D extends CallableDescriptor> ValueArgumentsCheckingResult checkAllValueArguments(
711                @NotNull CallCandidateResolutionContext<D> context,
712                @NotNull CallResolverUtil.ResolveArgumentsMode resolveFunctionArgumentBodies) {
713            return checkAllValueArguments(context, context.candidateCall.getTrace(), resolveFunctionArgumentBodies);
714        }
715    
716        private <D extends CallableDescriptor> ValueArgumentsCheckingResult checkAllValueArguments(
717                @NotNull CallCandidateResolutionContext<D> context,
718                @NotNull BindingTrace trace,
719                @NotNull CallResolverUtil.ResolveArgumentsMode resolveFunctionArgumentBodies
720        ) {
721            ValueArgumentsCheckingResult checkingResult = checkValueArgumentTypes(
722                    context, context.candidateCall, trace, resolveFunctionArgumentBodies);
723            ResolutionStatus resultStatus = checkingResult.status;
724            resultStatus = resultStatus.combine(checkReceiver(context, trace));
725    
726            return new ValueArgumentsCheckingResult(resultStatus, checkingResult.argumentTypes);
727        }
728    
729        private static <D extends CallableDescriptor> ResolutionStatus checkReceiver(
730                @NotNull CallCandidateResolutionContext<D> context,
731                @NotNull BindingTrace trace
732        ) {
733            ResolutionStatus resultStatus = SUCCESS;
734            ResolvedCall<D> candidateCall = context.candidateCall;
735    
736            resultStatus = resultStatus.combine(checkReceiverTypeError(candidateCall));
737    
738            // Comment about a very special case.
739            // Call 'b.foo(1)' where class 'Foo' has an extension member 'fun B.invoke(Int)' should be checked two times for safe call (in 'checkReceiver'), because
740            // both 'b' (receiver) and 'foo' (this object) might be nullable. In the first case we mark dot, in the second 'foo'.
741            // Class 'CallForImplicitInvoke' helps up to recognise this case, and parameter 'implicitInvokeCheck' helps us to distinguish whether we check receiver or this object.
742    
743            resultStatus = resultStatus.combine(checkReceiver(
744                    context, candidateCall, trace,
745                    candidateCall.getResultingDescriptor().getReceiverParameter(),
746                    candidateCall.getReceiverArgument(), candidateCall.getExplicitReceiverKind().isReceiver(), false));
747    
748            resultStatus = resultStatus.combine(checkReceiver(
749                    context, candidateCall, trace,
750                    candidateCall.getResultingDescriptor().getExpectedThisObject(), candidateCall.getThisObject(),
751                    candidateCall.getExplicitReceiverKind().isThisObject(),
752                    // for the invocation 'foo(1)' where foo is a variable of function type we should mark 'foo' if there is unsafe call error
753                    context.call instanceof CallForImplicitInvoke));
754            return resultStatus;
755        }
756    
757        public <D extends CallableDescriptor> ValueArgumentsCheckingResult checkValueArgumentTypes(
758                @NotNull CallCandidateResolutionContext<D> context
759        ) {
760            return checkValueArgumentTypes(context, context.candidateCall, context.trace, RESOLVE_FUNCTION_ARGUMENTS);
761        }
762    
763        private <D extends CallableDescriptor, C extends CallResolutionContext<C>> ValueArgumentsCheckingResult checkValueArgumentTypes(
764                @NotNull CallResolutionContext<C> context,
765                @NotNull ResolvedCallImpl<D> candidateCall,
766                @NotNull BindingTrace trace,
767                @NotNull CallResolverUtil.ResolveArgumentsMode resolveFunctionArgumentBodies) {
768            ResolutionStatus resultStatus = SUCCESS;
769            List<JetType> argumentTypes = Lists.newArrayList();
770            MutableDataFlowInfoForArguments infoForArguments = candidateCall.getDataFlowInfoForArguments();
771            for (Map.Entry<ValueParameterDescriptor, ResolvedValueArgument> entry : candidateCall.getValueArguments().entrySet()) {
772                ValueParameterDescriptor parameterDescriptor = entry.getKey();
773                ResolvedValueArgument resolvedArgument = entry.getValue();
774    
775    
776                for (ValueArgument argument : resolvedArgument.getArguments()) {
777                    JetExpression expression = argument.getArgumentExpression();
778                    if (expression == null) continue;
779    
780                    JetType expectedType = getEffectiveExpectedType(parameterDescriptor, argument);
781                    if (TypeUtils.dependsOnTypeParameters(expectedType, candidateCall.getCandidateDescriptor().getTypeParameters())) {
782                        expectedType = NO_EXPECTED_TYPE;
783                    }
784    
785                    CallResolutionContext<?> newContext = context.replaceDataFlowInfo(infoForArguments.getInfo(argument))
786                            .replaceBindingTrace(trace).replaceExpectedType(expectedType);
787                    JetTypeInfo typeInfoForCall = argumentTypeResolver.getArgumentTypeInfo(
788                            expression, newContext, resolveFunctionArgumentBodies);
789                    JetType type = typeInfoForCall.getType();
790                    infoForArguments.updateInfo(argument, typeInfoForCall.getDataFlowInfo());
791    
792                    if (type == null || (type.isError() && type != PLACEHOLDER_FUNCTION_TYPE)) {
793                        candidateCall.argumentHasNoType();
794                        argumentTypes.add(type);
795                    }
796                    else {
797                        JetType resultingType;
798                        if (noExpectedType(expectedType) || ArgumentTypeResolver.isSubtypeOfForArgumentType(type, expectedType)) {
799                            resultingType = type;
800                        }
801                        else {
802                            resultingType = autocastValueArgumentTypeIfPossible(expression, expectedType, type, newContext);
803                            if (resultingType == null) {
804                                resultingType = type;
805                                resultStatus = OTHER_ERROR;
806                            }
807                        }
808    
809                        argumentTypes.add(resultingType);
810                    }
811                }
812            }
813            return new ValueArgumentsCheckingResult(resultStatus, argumentTypes);
814        }
815    
816        @Nullable
817        private static JetType autocastValueArgumentTypeIfPossible(
818                @NotNull JetExpression expression,
819                @NotNull JetType expectedType,
820                @NotNull JetType actualType,
821                @NotNull ResolutionContext<?> context
822        ) {
823            ExpressionReceiver receiverToCast = new ExpressionReceiver(JetPsiUtil.safeDeparenthesize(expression, false), actualType);
824            List<ReceiverValue> variants =
825                    AutoCastUtils.getAutoCastVariants(context.trace.getBindingContext(), context.dataFlowInfo, receiverToCast);
826            for (ReceiverValue receiverValue : variants) {
827                JetType possibleType = receiverValue.getType();
828                if (JetTypeChecker.INSTANCE.isSubtypeOf(possibleType, expectedType)) {
829                    return possibleType;
830                }
831            }
832            return null;
833        }
834    
835        private static <D extends CallableDescriptor> ResolutionStatus checkReceiverTypeError(
836                @NotNull ResolvedCall<D> candidateCall
837        ) {
838            D candidateDescriptor = candidateCall.getCandidateDescriptor();
839            if (candidateDescriptor instanceof ExpressionAsFunctionDescriptor) return SUCCESS;
840    
841            ReceiverParameterDescriptor receiverDescriptor = candidateDescriptor.getReceiverParameter();
842            ReceiverParameterDescriptor expectedThisObjectDescriptor = candidateDescriptor.getExpectedThisObject();
843            ReceiverParameterDescriptor receiverParameterDescriptor;
844            JetType receiverArgumentType;
845            if (receiverDescriptor != null && candidateCall.getReceiverArgument().exists()) {
846                receiverParameterDescriptor = receiverDescriptor;
847                receiverArgumentType = candidateCall.getReceiverArgument().getType();
848            }
849            else if (expectedThisObjectDescriptor != null && candidateCall.getThisObject().exists()) {
850                receiverParameterDescriptor = expectedThisObjectDescriptor;
851                receiverArgumentType = candidateCall.getThisObject().getType();
852            }
853            else {
854                return SUCCESS;
855            }
856    
857            JetType effectiveReceiverArgumentType = TypeUtils.makeNotNullable(receiverArgumentType);
858            JetType erasedReceiverType = CallResolverUtil.getErasedReceiverType(receiverParameterDescriptor, candidateDescriptor);
859    
860            if (!JetTypeChecker.INSTANCE.isSubtypeOf(effectiveReceiverArgumentType, erasedReceiverType)) {
861                return RECEIVER_TYPE_ERROR;
862            }
863            return SUCCESS;
864        }
865    
866        private static <D extends CallableDescriptor> ResolutionStatus checkReceiver(
867                @NotNull CallCandidateResolutionContext<D> context,
868                @NotNull ResolvedCall<D> candidateCall,
869                @NotNull BindingTrace trace,
870                @Nullable ReceiverParameterDescriptor receiverParameter,
871                @NotNull ReceiverValue receiverArgument,
872                boolean isExplicitReceiver,
873                boolean implicitInvokeCheck
874        ) {
875            if (receiverParameter == null || !receiverArgument.exists()) return SUCCESS;
876    
877            JetType receiverArgumentType = receiverArgument.getType();
878            JetType effectiveReceiverArgumentType = TypeUtils.makeNotNullable(receiverArgumentType);
879            D candidateDescriptor = candidateCall.getCandidateDescriptor();
880            if (!ArgumentTypeResolver.isSubtypeOfForArgumentType(effectiveReceiverArgumentType, receiverParameter.getType())
881                    && !TypeUtils.dependsOnTypeParameters(receiverParameter.getType(), candidateDescriptor.getTypeParameters())) {
882                context.tracing.wrongReceiverType(trace, receiverParameter, receiverArgument);
883                return OTHER_ERROR;
884            }
885    
886            BindingContext bindingContext = trace.getBindingContext();
887            boolean safeAccess = isExplicitReceiver && !implicitInvokeCheck && candidateCall.isSafeCall();
888            AutoCastServiceImpl autoCastService = new AutoCastServiceImpl(context.dataFlowInfo, bindingContext);
889            if (!safeAccess && !receiverParameter.getType().isNullable() && !autoCastService.isNotNull(receiverArgument)) {
890    
891                context.tracing.unsafeCall(trace, receiverArgumentType, implicitInvokeCheck);
892                return UNSAFE_CALL_ERROR;
893            }
894            DataFlowValue receiverValue = DataFlowValueFactory.createDataFlowValue(receiverArgument, bindingContext);
895            if (safeAccess && !context.dataFlowInfo.getNullability(receiverValue).canBeNull()) {
896                context.tracing.unnecessarySafeCall(trace, receiverArgumentType);
897            }
898            return SUCCESS;
899        }
900    
901        private static class ValueArgumentsCheckingResult {
902    
903            public final List<JetType> argumentTypes;
904            public final ResolutionStatus status;
905    
906            private ValueArgumentsCheckingResult(@NotNull ResolutionStatus status, @NotNull List<JetType> argumentTypes) {
907                this.status = status;
908                this.argumentTypes = argumentTypes;
909            }
910        }
911    
912        @NotNull
913        private static JetType getEffectiveExpectedType(ValueParameterDescriptor parameterDescriptor, ValueArgument argument) {
914            if (argument.getSpreadElement() != null) {
915                if (parameterDescriptor.getVarargElementType() == null) {
916                    // Spread argument passed to a non-vararg parameter, an error is already reported by ValueArgumentsToParametersMapper
917                    return DONT_CARE;
918                }
919                else {
920                    return parameterDescriptor.getType();
921                }
922            }
923            else {
924                if (argument.isNamed()) {
925                    return parameterDescriptor.getType();
926                }
927                else {
928                    JetType varargElementType = parameterDescriptor.getVarargElementType();
929                    if (varargElementType == null) {
930                        return parameterDescriptor.getType();
931                    }
932                    return varargElementType;
933                }
934            }
935        }
936    
937        private static void checkGenericBoundsInAFunctionCall(
938                @NotNull List<JetTypeProjection> jetTypeArguments,
939                @NotNull List<JetType> typeArguments,
940                @NotNull CallableDescriptor functionDescriptor,
941                @NotNull BindingTrace trace) {
942            Map<TypeConstructor, TypeProjection> context = Maps.newHashMap();
943    
944            List<TypeParameterDescriptor> typeParameters = functionDescriptor.getOriginal().getTypeParameters();
945            for (int i = 0, typeParametersSize = typeParameters.size(); i < typeParametersSize; i++) {
946                TypeParameterDescriptor typeParameter = typeParameters.get(i);
947                JetType typeArgument = typeArguments.get(i);
948                context.put(typeParameter.getTypeConstructor(), new TypeProjectionImpl(typeArgument));
949            }
950            TypeSubstitutor substitutor = TypeSubstitutor.create(context);
951            for (int i = 0, typeParametersSize = typeParameters.size(); i < typeParametersSize; i++) {
952                TypeParameterDescriptor typeParameterDescriptor = typeParameters.get(i);
953                JetType typeArgument = typeArguments.get(i);
954                JetTypeReference typeReference = jetTypeArguments.get(i).getTypeReference();
955                if (typeReference != null) {
956                    DescriptorResolver.checkBounds(typeReference, typeArgument, typeParameterDescriptor, substitutor, trace);
957                }
958            }
959        }
960    }