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.Collections2;
021    import com.google.common.collect.Lists;
022    import com.intellij.psi.PsiElement;
023    import org.jetbrains.annotations.NotNull;
024    import org.jetbrains.annotations.Nullable;
025    import org.jetbrains.jet.lang.descriptors.CallableDescriptor;
026    import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
027    import org.jetbrains.jet.lang.descriptors.VariableDescriptor;
028    import org.jetbrains.jet.lang.psi.*;
029    import org.jetbrains.jet.lang.resolve.ChainedTemporaryBindingTrace;
030    import org.jetbrains.jet.lang.resolve.DelegatingBindingTrace;
031    import org.jetbrains.jet.lang.resolve.TemporaryBindingTrace;
032    import org.jetbrains.jet.lang.resolve.calls.context.BasicCallResolutionContext;
033    import org.jetbrains.jet.lang.resolve.calls.context.CallCandidateResolutionContext;
034    import org.jetbrains.jet.lang.resolve.calls.context.ContextDependency;
035    import org.jetbrains.jet.lang.resolve.calls.model.ResolvedCallImpl;
036    import org.jetbrains.jet.lang.resolve.calls.model.ResolvedCallWithTrace;
037    import org.jetbrains.jet.lang.resolve.calls.model.VariableAsFunctionResolvedCall;
038    import org.jetbrains.jet.lang.resolve.calls.results.OverloadResolutionResults;
039    import org.jetbrains.jet.lang.resolve.calls.results.OverloadResolutionResultsImpl;
040    import org.jetbrains.jet.lang.resolve.calls.tasks.ExplicitReceiverKind;
041    import org.jetbrains.jet.lang.resolve.calls.tasks.ResolutionCandidate;
042    import org.jetbrains.jet.lang.resolve.calls.tasks.ResolutionTask;
043    import org.jetbrains.jet.lang.resolve.calls.tasks.TracingStrategyForInvoke;
044    import org.jetbrains.jet.lang.resolve.calls.util.DelegatingCall;
045    import org.jetbrains.jet.lang.resolve.scopes.receivers.ExpressionReceiver;
046    import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue;
047    import org.jetbrains.jet.lang.types.JetType;
048    
049    import java.util.Collection;
050    import java.util.Collections;
051    import java.util.List;
052    
053    /**
054     * CallTransformer treats specially 'variable as function' call case, other cases keeps unchanged (base realization).
055     *
056     * For the call 'b.foo(1)' where foo is a variable that has method 'invoke' (for example of function type)
057     * CallTransformer creates two contexts, two calls in each, and performs second ('invoke') call resolution:
058     *
059     *   context#1. calls: 'b.foo' 'invoke(1)'
060     *   context#2. calls: 'foo'   'b.invoke(1)'
061     *
062     * If success VariableAsFunctionResolvedCall is created.
063     */
064    public class CallTransformer<D extends CallableDescriptor, F extends D> {
065        private CallTransformer() {}
066    
067        /**
068         * Returns two contexts for 'variable as function' case (in FUNCTION_CALL_TRANSFORMER), one context otherwise
069         */
070        @NotNull
071        public Collection<CallCandidateResolutionContext<D>> createCallContexts(@NotNull ResolutionCandidate<D> candidate,
072                @NotNull ResolutionTask<D, F> task,
073                @NotNull TemporaryBindingTrace candidateTrace
074        ) {
075            ResolvedCallImpl<D> candidateCall = ResolvedCallImpl.create(candidate, candidateTrace, task.tracing, task.dataFlowInfoForArguments);
076            return Collections.singleton(CallCandidateResolutionContext.create(candidateCall, task, candidateTrace, task.tracing));
077        }
078    
079        /**
080         * Returns collection of resolved calls for 'invoke' for 'variable as function' case (in FUNCTION_CALL_TRANSFORMER),
081         * the resolved call from callCandidateResolutionContext otherwise
082         */
083        @NotNull
084        public Collection<ResolvedCallWithTrace<F>> transformCall(@NotNull CallCandidateResolutionContext<D> callCandidateResolutionContext,
085                @NotNull CallResolver callResolver,
086                @NotNull ResolutionTask<D, F> task
087        ) {
088            return Collections.singleton((ResolvedCallWithTrace<F>) callCandidateResolutionContext.candidateCall);
089        }
090    
091    
092        public static CallTransformer<VariableDescriptor, VariableDescriptor> PROPERTY_CALL_TRANSFORMER = new CallTransformer<VariableDescriptor, VariableDescriptor>();
093    
094        public static CallTransformer<CallableDescriptor, FunctionDescriptor> FUNCTION_CALL_TRANSFORMER = new CallTransformer<CallableDescriptor, FunctionDescriptor>() {
095            @NotNull
096            @Override
097            public Collection<CallCandidateResolutionContext<CallableDescriptor>> createCallContexts(@NotNull ResolutionCandidate<CallableDescriptor> candidate,
098                    @NotNull ResolutionTask<CallableDescriptor, FunctionDescriptor> task, @NotNull TemporaryBindingTrace candidateTrace) {
099    
100                if (candidate.getDescriptor() instanceof FunctionDescriptor) {
101                    return super.createCallContexts(candidate, task, candidateTrace);
102                }
103    
104                assert candidate.getDescriptor() instanceof VariableDescriptor;
105    
106                boolean hasReceiver = candidate.getReceiverArgument().exists();
107                Call variableCall = stripCallArguments(task);
108                if (!hasReceiver) {
109                    CallCandidateResolutionContext<CallableDescriptor> context = CallCandidateResolutionContext.create(
110                            ResolvedCallImpl.create(candidate, candidateTrace, task.tracing, task.dataFlowInfoForArguments), task, candidateTrace, task.tracing, variableCall);
111                    return Collections.singleton(context);
112                }
113                CallCandidateResolutionContext<CallableDescriptor> contextWithReceiver = createContextWithChainedTrace(
114                        candidate, variableCall, candidateTrace, task, ReceiverValue.NO_RECEIVER);
115    
116                Call variableCallWithoutReceiver = stripReceiver(variableCall);
117                ResolutionCandidate<CallableDescriptor> candidateWithoutReceiver = ResolutionCandidate.create(
118                        candidate.getCall(), candidate.getDescriptor(), candidate.getThisObject(), ReceiverValue.NO_RECEIVER,
119                        ExplicitReceiverKind.NO_EXPLICIT_RECEIVER, false);
120    
121                CallCandidateResolutionContext<CallableDescriptor> contextWithoutReceiver = createContextWithChainedTrace(
122                        candidateWithoutReceiver, variableCallWithoutReceiver, candidateTrace, task, variableCall.getExplicitReceiver());
123    
124                return Lists.newArrayList(contextWithReceiver, contextWithoutReceiver);
125            }
126    
127            private CallCandidateResolutionContext<CallableDescriptor> createContextWithChainedTrace(
128                    @NotNull ResolutionCandidate<CallableDescriptor> candidate, @NotNull Call call, @NotNull TemporaryBindingTrace temporaryTrace,
129                    @NotNull ResolutionTask<CallableDescriptor, FunctionDescriptor> task, @NotNull ReceiverValue receiverValue
130            ) {
131                ChainedTemporaryBindingTrace chainedTrace = ChainedTemporaryBindingTrace.create(temporaryTrace, "chained trace to resolve candidate", candidate);
132                ResolvedCallImpl<CallableDescriptor> resolvedCall = ResolvedCallImpl.create(candidate, chainedTrace, task.tracing, task.dataFlowInfoForArguments);
133                return CallCandidateResolutionContext.create(resolvedCall, task, chainedTrace, task.tracing, call, receiverValue);
134            }
135    
136            private Call stripCallArguments(@NotNull ResolutionTask<CallableDescriptor, FunctionDescriptor> task) {
137                return new DelegatingCall(task.call) {
138                    @Override
139                    public JetValueArgumentList getValueArgumentList() {
140                        return null;
141                    }
142    
143                    @NotNull
144                    @Override
145                    public List<? extends ValueArgument> getValueArguments() {
146                        return Collections.emptyList();
147                    }
148    
149                    @NotNull
150                    @Override
151                    public List<JetExpression> getFunctionLiteralArguments() {
152                        return Collections.emptyList();
153                    }
154    
155                    @NotNull
156                    @Override
157                    public List<JetTypeProjection> getTypeArguments() {
158                        return Collections.emptyList();
159                    }
160    
161                    @Override
162                    public JetTypeArgumentList getTypeArgumentList() {
163                        return null;
164                    }
165                };
166            }
167    
168            private Call stripReceiver(@NotNull Call variableCall) {
169                return new DelegatingCall(variableCall) {
170                    @NotNull
171                    @Override
172                    public ReceiverValue getExplicitReceiver() {
173                        return ReceiverValue.NO_RECEIVER;
174                    }
175                };
176            }
177    
178            @NotNull
179            @Override
180            public Collection<ResolvedCallWithTrace<FunctionDescriptor>> transformCall(
181                    @NotNull CallCandidateResolutionContext<CallableDescriptor> context,
182                    @NotNull CallResolver callResolver,
183                    @NotNull ResolutionTask<CallableDescriptor, FunctionDescriptor> task
184            ) {
185                CallableDescriptor descriptor = context.candidateCall.getCandidateDescriptor();
186                if (descriptor instanceof FunctionDescriptor) {
187                    return super.transformCall(context, callResolver, task);
188                }
189    
190                assert descriptor instanceof VariableDescriptor;
191                JetType returnType = descriptor.getReturnType();
192                if (returnType == null) {
193                    return Collections.emptyList();
194                }
195    
196                final ResolvedCallWithTrace<VariableDescriptor> variableResolvedCall = (ResolvedCallWithTrace)context.candidateCall;
197    
198                JetExpression calleeExpression = task.call.getCalleeExpression();
199                if (calleeExpression == null) return Collections.emptyList();
200    
201                ExpressionReceiver variableReceiver = new ExpressionReceiver(calleeExpression, variableResolvedCall.getResultingDescriptor().getType());
202                Call functionCall = new CallForImplicitInvoke(context.explicitExtensionReceiverForInvoke, variableReceiver, task.call);
203    
204                DelegatingBindingTrace variableCallTrace = context.candidateCall.getTrace();
205                BasicCallResolutionContext basicCallResolutionContext = BasicCallResolutionContext.create(
206                        context.replaceBindingTrace(variableCallTrace).replaceContextDependency(ContextDependency.DEPENDENT),
207                        functionCall, context.checkArguments, context.dataFlowInfoForArguments);
208    
209                // 'invoke' call resolve
210                TracingStrategyForInvoke tracingForInvoke = new TracingStrategyForInvoke(
211                        calleeExpression, functionCall, variableReceiver.getType());
212                OverloadResolutionResults<FunctionDescriptor> results = callResolver.resolveCallForInvoke(
213                        basicCallResolutionContext, tracingForInvoke);
214                Collection<ResolvedCallWithTrace<FunctionDescriptor>> calls = ((OverloadResolutionResultsImpl<FunctionDescriptor>)results).getResultingCalls();
215    
216                return Collections2.transform(calls, new Function<ResolvedCallWithTrace<FunctionDescriptor>, ResolvedCallWithTrace<FunctionDescriptor>>() {
217                    @Override
218                    public ResolvedCallWithTrace<FunctionDescriptor> apply(ResolvedCallWithTrace<FunctionDescriptor> functionResolvedCall) {
219                        return new VariableAsFunctionResolvedCall(functionResolvedCall, variableResolvedCall);
220                    }
221                });
222            }
223        };
224    
225        public static class CallForImplicitInvoke extends DelegatingCall {
226            final Call outerCall;
227            final ReceiverValue explicitExtensionReceiver;
228            final ExpressionReceiver calleeExpressionAsThisObject;
229            final JetSimpleNameExpression fakeInvokeExpression;
230    
231            public CallForImplicitInvoke(
232                    @NotNull ReceiverValue explicitExtensionReceiver,
233                    @NotNull ExpressionReceiver calleeExpressionAsThisObject,
234                    @NotNull Call call
235            ) {
236                super(call);
237                this.outerCall = call;
238                this.explicitExtensionReceiver = explicitExtensionReceiver;
239                this.calleeExpressionAsThisObject = calleeExpressionAsThisObject;
240                this.fakeInvokeExpression = (JetSimpleNameExpression) JetPsiFactory.createExpression(call.getCallElement().getProject(), "invoke");
241            }
242    
243            @NotNull
244            @Override
245            public ReceiverValue getExplicitReceiver() {
246                return explicitExtensionReceiver;
247            }
248    
249            @NotNull
250            @Override
251            public ReceiverValue getThisObject() {
252                return calleeExpressionAsThisObject;
253            }
254    
255            @Override
256            public JetExpression getCalleeExpression() {
257                return fakeInvokeExpression;
258            }
259    
260            @NotNull
261            @Override
262            public PsiElement getCallElement() {
263                return outerCall.getCallElement();
264            }
265    
266            @NotNull
267            @Override
268            public CallType getCallType() {
269                return CallType.INVOKE;
270            }
271    
272            @NotNull
273            public Call getOuterCall() {
274                return outerCall;
275            }
276        }
277    }