001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.types.expressions;
018    
019    import kotlin.Pair;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.annotations.Nullable;
022    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
023    import org.jetbrains.kotlin.descriptors.FunctionDescriptor;
024    import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1;
025    import org.jetbrains.kotlin.name.Name;
026    import org.jetbrains.kotlin.psi.Call;
027    import org.jetbrains.kotlin.psi.JetExpression;
028    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
029    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults;
030    import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
031    import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
032    import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator;
033    import org.jetbrains.kotlin.types.JetType;
034    import org.jetbrains.kotlin.util.slicedMap.WritableSlice;
035    
036    import java.util.Collections;
037    
038    import static org.jetbrains.kotlin.diagnostics.Errors.*;
039    import static org.jetbrains.kotlin.resolve.BindingContext.*;
040    
041    public class ForLoopConventionsChecker {
042    
043        @NotNull private final KotlinBuiltIns builtIns;
044        @NotNull private final SymbolUsageValidator symbolUsageValidator;
045        @NotNull private final FakeCallResolver fakeCallResolver;
046    
047        public ForLoopConventionsChecker(
048                @NotNull KotlinBuiltIns builtIns,
049                @NotNull FakeCallResolver fakeCallResolver,
050                @NotNull SymbolUsageValidator symbolUsageValidator
051        ) {
052            this.builtIns = builtIns;
053            this.fakeCallResolver = fakeCallResolver;
054            this.symbolUsageValidator = symbolUsageValidator;
055        }
056    
057        @Nullable
058        public JetType checkIterableConvention(@NotNull ExpressionReceiver loopRange, ExpressionTypingContext context) {
059            JetExpression loopRangeExpression = loopRange.getExpression();
060    
061            // Make a fake call loopRange.iterator(), and try to resolve it
062            Name iterator = Name.identifier("iterator");
063            Pair<Call, OverloadResolutionResults<FunctionDescriptor>> calls =
064                    fakeCallResolver.makeAndResolveFakeCall(loopRange, context, Collections.<JetExpression>emptyList(), iterator,
065                                                                 loopRange.getExpression());
066            OverloadResolutionResults<FunctionDescriptor> iteratorResolutionResults = calls.getSecond();
067    
068            if (iteratorResolutionResults.isSuccess()) {
069                ResolvedCall<FunctionDescriptor> iteratorResolvedCall = iteratorResolutionResults.getResultingCall();
070                context.trace.record(LOOP_RANGE_ITERATOR_RESOLVED_CALL, loopRangeExpression, iteratorResolvedCall);
071                FunctionDescriptor iteratorFunction = iteratorResolvedCall.getResultingDescriptor();
072    
073                symbolUsageValidator.validateCall(iteratorFunction, context.trace, loopRangeExpression);
074    
075                JetType iteratorType = iteratorFunction.getReturnType();
076                JetType hasNextType = checkConventionForIterator(context, loopRangeExpression, iteratorType, "hasNext",
077                                                                 HAS_NEXT_FUNCTION_AMBIGUITY, HAS_NEXT_MISSING, HAS_NEXT_FUNCTION_NONE_APPLICABLE,
078                                                                 LOOP_RANGE_HAS_NEXT_RESOLVED_CALL);
079                if (hasNextType != null && !builtIns.isBooleanOrSubtype(hasNextType)) {
080                    context.trace.report(HAS_NEXT_FUNCTION_TYPE_MISMATCH.on(loopRangeExpression, hasNextType));
081                }
082                return checkConventionForIterator(context, loopRangeExpression, iteratorType, "next",
083                                                  NEXT_AMBIGUITY, NEXT_MISSING, NEXT_NONE_APPLICABLE,
084                                                  LOOP_RANGE_NEXT_RESOLVED_CALL);
085            }
086            else {
087                if (iteratorResolutionResults.isAmbiguity()) {
088                    context.trace.report(ITERATOR_AMBIGUITY.on(loopRangeExpression, iteratorResolutionResults.getResultingCalls()));
089                }
090                else {
091                    context.trace.report(ITERATOR_MISSING.on(loopRangeExpression));
092                }
093            }
094            return null;
095        }
096    
097        @Nullable
098        private JetType checkConventionForIterator(
099                @NotNull ExpressionTypingContext context,
100                @NotNull JetExpression loopRangeExpression,
101                @NotNull JetType iteratorType,
102                @NotNull String name,
103                @NotNull DiagnosticFactory1<JetExpression, JetType> ambiguity,
104                @NotNull DiagnosticFactory1<JetExpression, JetType> missing,
105                @NotNull DiagnosticFactory1<JetExpression, JetType> noneApplicable,
106                @NotNull WritableSlice<JetExpression, ResolvedCall<FunctionDescriptor>> resolvedCallKey
107        ) {
108            OverloadResolutionResults<FunctionDescriptor> nextResolutionResults = fakeCallResolver.resolveFakeCall(
109                    context, new TransientReceiver(iteratorType), Name.identifier(name), loopRangeExpression);
110            if (nextResolutionResults.isAmbiguity()) {
111                context.trace.report(ambiguity.on(loopRangeExpression, iteratorType));
112            }
113            else if (nextResolutionResults.isNothing()) {
114                context.trace.report(missing.on(loopRangeExpression, iteratorType));
115            }
116            else if (!nextResolutionResults.isSuccess()) {
117                context.trace.report(noneApplicable.on(loopRangeExpression, iteratorType));
118            }
119            else {
120                assert nextResolutionResults.isSuccess();
121                ResolvedCall<FunctionDescriptor> resolvedCall = nextResolutionResults.getResultingCall();
122                context.trace.record(resolvedCallKey, loopRangeExpression, resolvedCall);
123                FunctionDescriptor functionDescriptor = resolvedCall.getResultingDescriptor();
124                symbolUsageValidator.validateCall(functionDescriptor, context.trace, loopRangeExpression);
125                return functionDescriptor.getReturnType();
126            }
127            return null;
128        }
129    }