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.types.expressions;
018    
019    import com.intellij.openapi.util.Ref;
020    import com.intellij.psi.tree.IElementType;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.jet.lang.evaluate.ConstantExpressionEvaluator;
024    import org.jetbrains.jet.lang.evaluate.EvaluatePackage;
025    import org.jetbrains.jet.lang.psi.*;
026    import org.jetbrains.jet.lang.resolve.BindingContext;
027    import org.jetbrains.jet.lang.resolve.BindingTrace;
028    import org.jetbrains.jet.lang.resolve.calls.autocasts.AutoCastUtils;
029    import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo;
030    import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowValue;
031    import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowValueFactory;
032    import org.jetbrains.jet.lang.resolve.calls.context.ResolutionContext;
033    import org.jetbrains.jet.lang.resolve.constants.CompileTimeConstant;
034    import org.jetbrains.jet.lang.resolve.constants.CompileTimeConstantChecker;
035    import org.jetbrains.jet.lang.resolve.constants.IntegerValueTypeConstant;
036    import org.jetbrains.jet.lang.types.JetType;
037    import org.jetbrains.jet.lang.types.JetTypeInfo;
038    import org.jetbrains.jet.lang.types.TypeUtils;
039    import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
040    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
041    import org.jetbrains.jet.lexer.JetTokens;
042    
043    import static org.jetbrains.jet.lang.diagnostics.Errors.*;
044    import static org.jetbrains.jet.lang.resolve.calls.context.ContextDependency.DEPENDENT;
045    import static org.jetbrains.jet.lang.resolve.calls.context.ContextDependency.INDEPENDENT;
046    import static org.jetbrains.jet.lang.types.TypeUtils.*;
047    
048    public class DataFlowUtils {
049        private DataFlowUtils() {
050        }
051    
052        @NotNull
053        public static DataFlowInfo extractDataFlowInfoFromCondition(@Nullable JetExpression condition, final boolean conditionValue, final ExpressionTypingContext context) {
054            if (condition == null) return context.dataFlowInfo;
055            final Ref<DataFlowInfo> result = new Ref<DataFlowInfo>(null);
056            condition.accept(new JetVisitorVoid() {
057                @Override
058                public void visitIsExpression(@NotNull JetIsExpression expression) {
059                    if (conditionValue && !expression.isNegated() || !conditionValue && expression.isNegated()) {
060                        result.set(context.trace.get(BindingContext.DATAFLOW_INFO_AFTER_CONDITION, expression));
061                    }
062                }
063    
064                @Override
065                public void visitBinaryExpression(@NotNull JetBinaryExpression expression) {
066                    IElementType operationToken = expression.getOperationToken();
067                    if (OperatorConventions.BOOLEAN_OPERATIONS.containsKey(operationToken)) {
068                        DataFlowInfo dataFlowInfo = extractDataFlowInfoFromCondition(expression.getLeft(), conditionValue, context);
069                        JetExpression expressionRight = expression.getRight();
070                        if (expressionRight != null) {
071                            DataFlowInfo rightInfo = extractDataFlowInfoFromCondition(expressionRight, conditionValue, context);
072                            boolean and = operationToken == JetTokens.ANDAND;
073                            if (and == conditionValue) { // this means: and && conditionValue || !and && !conditionValue
074                                dataFlowInfo = dataFlowInfo.and(rightInfo);
075                            }
076                            else {
077                                dataFlowInfo = dataFlowInfo.or(rightInfo);
078                            }
079                        }
080                        result.set(dataFlowInfo);
081                    }
082                    else  {
083                        JetExpression left = expression.getLeft();
084                        if (left == null) return;
085                        JetExpression right = expression.getRight();
086                        if (right == null) return;
087    
088                        JetType lhsType = context.trace.getBindingContext().get(BindingContext.EXPRESSION_TYPE, left);
089                        if (lhsType == null) return;
090                        JetType rhsType = context.trace.getBindingContext().get(BindingContext.EXPRESSION_TYPE, right);
091                        if (rhsType == null) return;
092    
093                        BindingContext bindingContext = context.trace.getBindingContext();
094                        DataFlowValue leftValue = DataFlowValueFactory.createDataFlowValue(left, lhsType, bindingContext);
095                        DataFlowValue rightValue = DataFlowValueFactory.createDataFlowValue(right, rhsType, bindingContext);
096    
097                        Boolean equals = null;
098                        if (operationToken == JetTokens.EQEQ || operationToken == JetTokens.EQEQEQ) {
099                            equals = true;
100                        }
101                        else if (operationToken == JetTokens.EXCLEQ || operationToken == JetTokens.EXCLEQEQEQ) {
102                            equals = false;
103                        }
104                        if (equals != null) {
105                            if (equals == conditionValue) { // this means: equals && conditionValue || !equals && !conditionValue
106                                result.set(context.dataFlowInfo.equate(leftValue, rightValue));
107                            }
108                            else {
109                                result.set(context.dataFlowInfo.disequate(leftValue, rightValue));
110                            }
111    
112                        }
113                    }
114                }
115    
116                @Override
117                public void visitUnaryExpression(@NotNull JetUnaryExpression expression) {
118                    IElementType operationTokenType = expression.getOperationReference().getReferencedNameElementType();
119                    if (operationTokenType == JetTokens.EXCL) {
120                        JetExpression baseExpression = expression.getBaseExpression();
121                        if (baseExpression != null) {
122                            result.set(extractDataFlowInfoFromCondition(baseExpression, !conditionValue, context));
123                        }
124                    }
125                }
126    
127                @Override
128                public void visitParenthesizedExpression(@NotNull JetParenthesizedExpression expression) {
129                    JetExpression body = expression.getExpression();
130                    if (body != null) {
131                        body.accept(this);
132                    }
133                }
134            });
135            if (result.get() == null) {
136                return context.dataFlowInfo;
137            }
138            return context.dataFlowInfo.and(result.get());
139        }
140    
141        @NotNull
142        public static JetTypeInfo checkType(@Nullable JetType expressionType, @NotNull JetExpression expression, @NotNull ResolutionContext context, @NotNull DataFlowInfo dataFlowInfo) {
143            return JetTypeInfo.create(checkType(expressionType, expression, context), dataFlowInfo);
144        }
145    
146        @NotNull
147        public static JetTypeInfo checkType(@NotNull JetTypeInfo typeInfo, @NotNull JetExpression expression, @NotNull ResolutionContext context) {
148            JetType type = checkType(typeInfo.getType(), expression, context);
149            if (type == typeInfo.getType()) {
150                return typeInfo;
151            }
152            return JetTypeInfo.create(type, typeInfo.getDataFlowInfo());
153        }
154    
155        @Nullable
156        public static JetType checkType(@Nullable JetType expressionType, @NotNull JetExpression expression, @NotNull ResolutionContext context) {
157            return checkType(expressionType, expression, context.expectedType, context.dataFlowInfo, context.trace);
158        }
159    
160        @Nullable
161        public static JetType checkType(@Nullable JetType expressionType, @NotNull JetExpression expressionToCheck,
162                @NotNull JetType expectedType, @NotNull DataFlowInfo dataFlowInfo, @NotNull BindingTrace trace
163        ) {
164            JetExpression expression = JetPsiUtil.safeDeparenthesize(expressionToCheck, false);
165            recordExpectedType(trace, expression, expectedType);
166    
167            if (expressionType == null || noExpectedType(expectedType) || !expectedType.getConstructor().isDenotable() ||
168                JetTypeChecker.DEFAULT.isSubtypeOf(expressionType, expectedType)) {
169                return expressionType;
170            }
171    
172            if (expression instanceof JetConstantExpression) {
173                CompileTimeConstant<?> value = ConstantExpressionEvaluator.OBJECT$.evaluate(expression, trace, expectedType);
174                if (value instanceof IntegerValueTypeConstant) {
175                    value = EvaluatePackage.createCompileTimeConstantWithType((IntegerValueTypeConstant) value, expectedType);
176                }
177                new CompileTimeConstantChecker(trace, true).checkConstantExpressionType(value, (JetConstantExpression) expression, expectedType);
178                return expressionType;
179            }
180    
181            DataFlowValue dataFlowValue = DataFlowValueFactory.createDataFlowValue(expression, expressionType, trace.getBindingContext());
182            for (JetType possibleType : dataFlowInfo.getPossibleTypes(dataFlowValue)) {
183                if (JetTypeChecker.DEFAULT.isSubtypeOf(possibleType, expectedType)) {
184                    AutoCastUtils.recordCastOrError(expression, possibleType, trace, dataFlowValue.isStableIdentifier(), false);
185                    return possibleType;
186                }
187            }
188            trace.report(TYPE_MISMATCH.on(expression, expectedType, expressionType));
189            return expressionType;
190        }
191    
192        public static void recordExpectedType(@NotNull BindingTrace trace, @NotNull JetExpression expression, @NotNull JetType expectedType) {
193            if (expectedType != NO_EXPECTED_TYPE) {
194                JetType normalizeExpectedType = expectedType == UNIT_EXPECTED_TYPE ? KotlinBuiltIns.getInstance().getUnitType() : expectedType;
195                trace.record(BindingContext.EXPECTED_EXPRESSION_TYPE, expression, normalizeExpectedType);
196            }
197        }
198    
199        @NotNull
200        public static JetTypeInfo checkStatementType(@NotNull JetExpression expression, @NotNull ResolutionContext context, @NotNull DataFlowInfo dataFlowInfo) {
201            return JetTypeInfo.create(checkStatementType(expression, context), dataFlowInfo);
202        }
203    
204        @Nullable
205        public static JetType checkStatementType(@NotNull JetExpression expression, @NotNull ResolutionContext context) {
206            if (!noExpectedType(context.expectedType) && !KotlinBuiltIns.getInstance().isUnit(context.expectedType) && !context.expectedType.isError()) {
207                context.trace.report(EXPECTED_TYPE_MISMATCH.on(expression, context.expectedType));
208                return null;
209            }
210            return KotlinBuiltIns.getInstance().getUnitType();
211        }
212    
213        @NotNull
214        public static JetTypeInfo checkImplicitCast(@Nullable JetType expressionType, @NotNull JetExpression expression, @NotNull ExpressionTypingContext context, boolean isStatement, DataFlowInfo dataFlowInfo) {
215            return JetTypeInfo.create(checkImplicitCast(expressionType, expression, context, isStatement), dataFlowInfo);
216        }
217    
218        @Nullable
219        public static JetType checkImplicitCast(@Nullable JetType expressionType, @NotNull JetExpression expression, @NotNull ExpressionTypingContext context, boolean isStatement) {
220            if (expressionType != null && context.expectedType == NO_EXPECTED_TYPE && context.contextDependency == INDEPENDENT && !isStatement
221                    && (KotlinBuiltIns.getInstance().isUnit(expressionType) || KotlinBuiltIns.getInstance().isAnyOrNullableAny(expressionType))) {
222                context.trace.report(IMPLICIT_CAST_TO_UNIT_OR_ANY.on(expression, expressionType));
223            }
224            return expressionType;
225        }
226    
227        @NotNull
228        public static JetTypeInfo illegalStatementType(@NotNull JetExpression expression, @NotNull ExpressionTypingContext context, @NotNull ExpressionTypingInternals facade) {
229            facade.checkStatementType(
230                    expression, context.replaceExpectedType(TypeUtils.NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT));
231            context.trace.report(EXPRESSION_EXPECTED.on(expression, expression));
232            return JetTypeInfo.create(null, context.dataFlowInfo);
233        }
234    }