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.cfg;
018
019 import com.google.common.collect.Lists;
020 import com.google.common.collect.Maps;
021 import com.google.common.collect.Sets;
022 import com.intellij.psi.PsiElement;
023 import com.intellij.psi.tree.IElementType;
024 import com.intellij.psi.util.PsiTreeUtil;
025 import kotlin.Unit;
026 import kotlin.jvm.functions.Function1;
027 import kotlin.jvm.functions.Function3;
028 import org.jetbrains.annotations.NotNull;
029 import org.jetbrains.annotations.Nullable;
030 import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
031 import org.jetbrains.kotlin.cfg.PseudocodeVariablesData.VariableControlFlowState;
032 import org.jetbrains.kotlin.cfg.PseudocodeVariablesData.VariableUseState;
033 import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue;
034 import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode;
035 import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtil;
036 import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt;
037 import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction;
038 import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor;
039 import org.jetbrains.kotlin.cfg.pseudocode.instructions.JetElementInstruction;
040 import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.*;
041 import org.jetbrains.kotlin.cfg.pseudocode.instructions.jumps.*;
042 import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.LocalFunctionDeclarationInstruction;
043 import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.MarkInstruction;
044 import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.SubroutineExitInstruction;
045 import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.VariableDeclarationInstruction;
046 import org.jetbrains.kotlin.cfg.pseudocodeTraverser.Edges;
047 import org.jetbrains.kotlin.cfg.pseudocodeTraverser.PseudocodeTraverserKt;
048 import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder;
049 import org.jetbrains.kotlin.descriptors.*;
050 import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptorKt;
051 import org.jetbrains.kotlin.diagnostics.Diagnostic;
052 import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
053 import org.jetbrains.kotlin.diagnostics.Errors;
054 import org.jetbrains.kotlin.idea.MainFunctionDetector;
055 import org.jetbrains.kotlin.lexer.KtTokens;
056 import org.jetbrains.kotlin.psi.*;
057 import org.jetbrains.kotlin.resolve.*;
058 import org.jetbrains.kotlin.resolve.bindingContextUtil.BindingContextUtilsKt;
059 import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
060 import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
061 import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.ResolvedCallUtilKt;
062 import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
063 import org.jetbrains.kotlin.types.KotlinType;
064 import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
065
066 import java.util.*;
067
068 import static org.jetbrains.kotlin.cfg.PseudocodeVariablesData.VariableUseState.*;
069 import static org.jetbrains.kotlin.cfg.TailRecursionKind.*;
070 import static org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder.FORWARD;
071 import static org.jetbrains.kotlin.diagnostics.Errors.*;
072 import static org.jetbrains.kotlin.diagnostics.Errors.UNREACHABLE_CODE;
073 import static org.jetbrains.kotlin.resolve.BindingContext.*;
074 import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
075 import static org.jetbrains.kotlin.types.TypeUtils.noExpectedType;
076
077 public class JetFlowInformationProvider {
078
079 private final KtElement subroutine;
080 private final Pseudocode pseudocode;
081 private final BindingTrace trace;
082 private PseudocodeVariablesData pseudocodeVariablesData;
083
084 private JetFlowInformationProvider(
085 @NotNull KtElement declaration,
086 @NotNull BindingTrace trace,
087 @NotNull Pseudocode pseudocode
088 ) {
089 this.subroutine = declaration;
090 this.trace = trace;
091 this.pseudocode = pseudocode;
092 }
093
094 public JetFlowInformationProvider(
095 @NotNull KtElement declaration,
096 @NotNull BindingTrace trace
097 ) {
098 this(declaration, trace, new JetControlFlowProcessor(trace).generatePseudocode(declaration));
099 }
100
101 public PseudocodeVariablesData getPseudocodeVariablesData() {
102 if (pseudocodeVariablesData == null) {
103 pseudocodeVariablesData = new PseudocodeVariablesData(pseudocode, trace.getBindingContext());
104 }
105 return pseudocodeVariablesData;
106 }
107
108 public void checkForLocalClassOrObjectMode() {
109 // Local classes and objects are analyzed twice: when TopDownAnalyzer processes it and as a part of its container.
110 // Almost all checks can be done when the container is analyzed
111 // except recording initialized variables (this information is needed for DeclarationChecker).
112 recordInitializedVariables();
113 }
114
115 public void checkDeclaration() {
116
117 recordInitializedVariables();
118
119 checkLocalFunctions();
120
121 markUninitializedVariables();
122
123 markUnusedVariables();
124
125 markStatements();
126
127 markUnusedExpressions();
128
129 markWhenWithoutElse();
130 }
131
132 public void checkFunction(@Nullable KotlinType expectedReturnType) {
133 UnreachableCode unreachableCode = collectUnreachableCode();
134 reportUnreachableCode(unreachableCode);
135
136 if (subroutine instanceof KtFunctionLiteral) return;
137
138 checkDefiniteReturn(expectedReturnType != null ? expectedReturnType : NO_EXPECTED_TYPE, unreachableCode);
139
140 markTailCalls();
141 }
142
143 private void collectReturnExpressions(@NotNull final Collection<KtElement> returnedExpressions) {
144 final Set<Instruction> instructions = Sets.newHashSet(pseudocode.getInstructions());
145 SubroutineExitInstruction exitInstruction = pseudocode.getExitInstruction();
146 for (Instruction previousInstruction : exitInstruction.getPreviousInstructions()) {
147 previousInstruction.accept(new InstructionVisitor() {
148 @Override
149 public void visitReturnValue(@NotNull ReturnValueInstruction instruction) {
150 if (instructions.contains(instruction)) { //exclude non-local return expressions
151 returnedExpressions.add(instruction.getElement());
152 }
153 }
154
155 @Override
156 public void visitReturnNoValue(@NotNull ReturnNoValueInstruction instruction) {
157 if (instructions.contains(instruction)) {
158 returnedExpressions.add(instruction.getElement());
159 }
160 }
161
162
163 @Override
164 public void visitJump(@NotNull AbstractJumpInstruction instruction) {
165 // Nothing
166 }
167
168 @Override
169 public void visitUnconditionalJump(@NotNull UnconditionalJumpInstruction instruction) {
170 redirectToPrevInstructions(instruction);
171 }
172
173 private void redirectToPrevInstructions(Instruction instruction) {
174 for (Instruction previousInstruction : instruction.getPreviousInstructions()) {
175 previousInstruction.accept(this);
176 }
177 }
178
179 @Override
180 public void visitNondeterministicJump(@NotNull NondeterministicJumpInstruction instruction) {
181 redirectToPrevInstructions(instruction);
182 }
183
184 @Override
185 public void visitMarkInstruction(@NotNull MarkInstruction instruction) {
186 redirectToPrevInstructions(instruction);
187 }
188
189 @Override
190 public void visitInstruction(@NotNull Instruction instruction) {
191 if (instruction instanceof JetElementInstruction) {
192 JetElementInstruction elementInstruction = (JetElementInstruction) instruction;
193 returnedExpressions.add(elementInstruction.getElement());
194 }
195 else {
196 throw new IllegalStateException(instruction + " precedes the exit point");
197 }
198 }
199 });
200 }
201 }
202
203 private void checkLocalFunctions() {
204 for (LocalFunctionDeclarationInstruction localDeclarationInstruction : pseudocode.getLocalDeclarations()) {
205 KtElement element = localDeclarationInstruction.getElement();
206 if (element instanceof KtDeclarationWithBody) {
207 KtDeclarationWithBody localDeclaration = (KtDeclarationWithBody) element;
208
209 CallableDescriptor functionDescriptor =
210 (CallableDescriptor) trace.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, localDeclaration);
211 KotlinType expectedType = functionDescriptor != null ? functionDescriptor.getReturnType() : null;
212
213 JetFlowInformationProvider providerForLocalDeclaration =
214 new JetFlowInformationProvider(localDeclaration, trace, localDeclarationInstruction.getBody());
215
216 providerForLocalDeclaration.checkFunction(expectedType);
217 }
218 }
219 }
220
221 public void checkDefiniteReturn(final @NotNull KotlinType expectedReturnType, @NotNull final UnreachableCode unreachableCode) {
222 assert subroutine instanceof KtDeclarationWithBody;
223 KtDeclarationWithBody function = (KtDeclarationWithBody) subroutine;
224
225 if (!function.hasBody()) return;
226
227 List<KtElement> returnedExpressions = Lists.newArrayList();
228 collectReturnExpressions(returnedExpressions);
229
230 final boolean blockBody = function.hasBlockBody();
231
232 final boolean[] noReturnError = new boolean[] { false };
233 for (KtElement returnedExpression : returnedExpressions) {
234 returnedExpression.accept(new KtVisitorVoid() {
235 @Override
236 public void visitReturnExpression(@NotNull KtReturnExpression expression) {
237 if (!blockBody) {
238 trace.report(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY.on(expression));
239 }
240 }
241
242 @Override
243 public void visitJetElement(@NotNull KtElement element) {
244 if (!(element instanceof KtExpression || element instanceof KtWhenCondition)) return;
245
246 if (blockBody && !noExpectedType(expectedReturnType)
247 && !KotlinBuiltIns.isUnit(expectedReturnType)
248 && !unreachableCode.getElements().contains(element)) {
249 noReturnError[0] = true;
250 }
251 }
252 });
253 }
254 if (noReturnError[0]) {
255 trace.report(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY.on(function));
256 }
257 }
258
259 private void reportUnreachableCode(@NotNull UnreachableCode unreachableCode) {
260 for (KtElement element : unreachableCode.getElements()) {
261 trace.report(UNREACHABLE_CODE.on(element, unreachableCode.getUnreachableTextRanges(element)));
262 trace.record(BindingContext.UNREACHABLE_CODE, element, true);
263 }
264 }
265
266 @NotNull
267 private UnreachableCode collectUnreachableCode() {
268 Set<KtElement> reachableElements = Sets.newHashSet();
269 Set<KtElement> unreachableElements = Sets.newHashSet();
270 for (Instruction instruction : pseudocode.getInstructionsIncludingDeadCode()) {
271 if (!(instruction instanceof JetElementInstruction)
272 || instruction instanceof LoadUnitValueInstruction
273 || instruction instanceof MergeInstruction
274 || (instruction instanceof MagicInstruction && ((MagicInstruction) instruction).getSynthetic())) continue;
275
276 KtElement element = ((JetElementInstruction) instruction).getElement();
277
278 if (instruction instanceof JumpInstruction) {
279 boolean isJumpElement = element instanceof KtBreakExpression
280 || element instanceof KtContinueExpression
281 || element instanceof KtReturnExpression
282 || element instanceof KtThrowExpression;
283 if (!isJumpElement) continue;
284 }
285
286 if (instruction.getDead()) {
287 unreachableElements.add(element);
288 }
289 else {
290 reachableElements.add(element);
291 }
292 }
293 return new UnreachableCodeImpl(reachableElements, unreachableElements);
294 }
295
296 ////////////////////////////////////////////////////////////////////////////////
297 // Uninitialized variables analysis
298
299 public void markUninitializedVariables() {
300 final Collection<VariableDescriptor> varWithUninitializedErrorGenerated = Sets.newHashSet();
301 final Collection<VariableDescriptor> varWithValReassignErrorGenerated = Sets.newHashSet();
302 final boolean processClassOrObject = subroutine instanceof KtClassOrObject;
303
304 PseudocodeVariablesData pseudocodeVariablesData = getPseudocodeVariablesData();
305 Map<Instruction, Edges<Map<VariableDescriptor, VariableControlFlowState>>> initializers =
306 pseudocodeVariablesData.getVariableInitializers();
307 final Set<VariableDescriptor> declaredVariables = pseudocodeVariablesData.getDeclaredVariables(pseudocode, true);
308 final LexicalScopeVariableInfo lexicalScopeVariableInfo = pseudocodeVariablesData.getLexicalScopeVariableInfo();
309
310 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap = Maps.newHashMap();
311
312 PseudocodeTraverserKt.traverse(
313 pseudocode, FORWARD, initializers,
314 new InstructionDataAnalyzeStrategy<Map<VariableDescriptor, VariableControlFlowState>>() {
315 @Override
316 public void execute(
317 @NotNull Instruction instruction,
318 @Nullable Map<VariableDescriptor, VariableControlFlowState> in,
319 @Nullable Map<VariableDescriptor, VariableControlFlowState> out
320 ) {
321 assert in != null && out != null;
322 VariableInitContext ctxt =
323 new VariableInitContext(instruction, reportedDiagnosticMap, in, out, lexicalScopeVariableInfo);
324 if (ctxt.variableDescriptor == null) return;
325 if (instruction instanceof ReadValueInstruction) {
326 ReadValueInstruction readValueInstruction = (ReadValueInstruction) instruction;
327 KtElement element = readValueInstruction.getElement();
328 boolean error = checkBackingField(ctxt, element);
329 if (!error &&
330 PseudocodeUtil.isThisOrNoDispatchReceiver(readValueInstruction, trace.getBindingContext()) &&
331 declaredVariables.contains(ctxt.variableDescriptor)) {
332 checkIsInitialized(ctxt, element, varWithUninitializedErrorGenerated);
333 }
334 return;
335 }
336 if (!(instruction instanceof WriteValueInstruction)) return;
337 WriteValueInstruction writeValueInstruction = (WriteValueInstruction) instruction;
338 KtElement element = writeValueInstruction.getLValue();
339 boolean error = checkBackingField(ctxt, element);
340 if (!(element instanceof KtExpression)) return;
341 if (!error) {
342 error = checkValReassignment(ctxt, (KtExpression) element, writeValueInstruction,
343 varWithValReassignErrorGenerated);
344 }
345 if (!error && processClassOrObject) {
346 error = checkAssignmentBeforeDeclaration(ctxt, (KtExpression) element);
347 }
348 if (!error && processClassOrObject) {
349 checkInitializationUsingBackingField(ctxt, (KtExpression) element);
350 }
351 }
352 }
353 );
354 }
355
356 public void recordInitializedVariables() {
357 PseudocodeVariablesData pseudocodeVariablesData = getPseudocodeVariablesData();
358 Pseudocode pseudocode = pseudocodeVariablesData.getPseudocode();
359 Map<Instruction, Edges<Map<VariableDescriptor, VariableControlFlowState>>> initializers =
360 pseudocodeVariablesData.getVariableInitializers();
361 recordInitializedVariables(pseudocode, initializers);
362 for (LocalFunctionDeclarationInstruction instruction : pseudocode.getLocalDeclarations()) {
363 recordInitializedVariables(instruction.getBody(), initializers);
364 }
365 }
366
367 private void checkIsInitialized(
368 @NotNull VariableInitContext ctxt,
369 @NotNull KtElement element,
370 @NotNull Collection<VariableDescriptor> varWithUninitializedErrorGenerated
371 ) {
372 if (!(element instanceof KtSimpleNameExpression)) return;
373
374
375 boolean isDefinitelyInitialized = ctxt.exitInitState.definitelyInitialized();
376 VariableDescriptor variableDescriptor = ctxt.variableDescriptor;
377 if (variableDescriptor instanceof PropertyDescriptor) {
378 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) variableDescriptor;
379 if (propertyDescriptor.isLateInit() || !trace.get(BindingContext.BACKING_FIELD_REQUIRED, propertyDescriptor)) {
380 isDefinitelyInitialized = true;
381 }
382 }
383 if (!isDefinitelyInitialized && !varWithUninitializedErrorGenerated.contains(variableDescriptor)) {
384 if (!(variableDescriptor instanceof PropertyDescriptor)) {
385 varWithUninitializedErrorGenerated.add(variableDescriptor);
386 }
387 if (variableDescriptor instanceof ValueParameterDescriptor) {
388 report(Errors.UNINITIALIZED_PARAMETER.on((KtSimpleNameExpression) element,
389 (ValueParameterDescriptor) variableDescriptor), ctxt);
390 }
391 else {
392 report(Errors.UNINITIALIZED_VARIABLE.on((KtSimpleNameExpression) element, variableDescriptor), ctxt);
393 }
394 }
395 }
396
397 private boolean checkValReassignment(
398 @NotNull VariableInitContext ctxt,
399 @NotNull KtExpression expression,
400 @NotNull WriteValueInstruction writeValueInstruction,
401 @NotNull Collection<VariableDescriptor> varWithValReassignErrorGenerated
402 ) {
403 VariableDescriptor variableDescriptor = ctxt.variableDescriptor;
404 PropertyDescriptor propertyDescriptor = SyntheticFieldDescriptorKt.getReferencedProperty(variableDescriptor);
405 if (KtPsiUtil.isBackingFieldReference(expression, variableDescriptor) && propertyDescriptor != null) {
406 KtPropertyAccessor accessor = PsiTreeUtil.getParentOfType(expression, KtPropertyAccessor.class);
407 if (accessor != null) {
408 DeclarationDescriptor accessorDescriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, accessor);
409 if (propertyDescriptor.getGetter() == accessorDescriptor) {
410 //val can be reassigned through backing field inside its own getter
411 return false;
412 }
413 }
414 }
415
416 boolean mayBeInitializedNotHere = ctxt.enterInitState.mayBeInitialized();
417 boolean hasBackingField = true;
418 if (variableDescriptor instanceof PropertyDescriptor) {
419 hasBackingField = trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor);
420 }
421 if (variableDescriptor.isVar() && variableDescriptor instanceof PropertyDescriptor) {
422 DeclarationDescriptor descriptor = BindingContextUtils.getEnclosingDescriptor(trace.getBindingContext(), expression);
423 PropertySetterDescriptor setterDescriptor = ((PropertyDescriptor) variableDescriptor).getSetter();
424
425 ResolvedCall<? extends CallableDescriptor> resolvedCall = CallUtilKt.getResolvedCall(expression, trace.getBindingContext());
426 ReceiverValue receiverValue = ReceiverValue.IRRELEVANT_RECEIVER;
427 if (resolvedCall != null) {
428 receiverValue = ExpressionTypingUtils
429 .normalizeReceiverValueForVisibility(resolvedCall.getDispatchReceiver(), trace.getBindingContext());
430
431 }
432 if (Visibilities.isVisible(receiverValue, variableDescriptor, descriptor) && setterDescriptor != null
433 && !Visibilities.isVisible(receiverValue, setterDescriptor, descriptor)) {
434 report(Errors.INVISIBLE_SETTER.on(expression, variableDescriptor, setterDescriptor.getVisibility(),
435 setterDescriptor), ctxt);
436 return true;
437 }
438 }
439 boolean isThisOrNoDispatchReceiver =
440 PseudocodeUtil.isThisOrNoDispatchReceiver(writeValueInstruction, trace.getBindingContext());
441 if ((mayBeInitializedNotHere || !hasBackingField || !isThisOrNoDispatchReceiver) && !variableDescriptor.isVar()) {
442 boolean hasReassignMethodReturningUnit = false;
443 KtSimpleNameExpression operationReference = null;
444 PsiElement parent = expression.getParent();
445 if (parent instanceof KtBinaryExpression) {
446 operationReference = ((KtBinaryExpression) parent).getOperationReference();
447 }
448 else if (parent instanceof KtUnaryExpression) {
449 operationReference = ((KtUnaryExpression) parent).getOperationReference();
450 }
451 if (operationReference != null) {
452 DeclarationDescriptor descriptor = trace.get(BindingContext.REFERENCE_TARGET, operationReference);
453 if (descriptor instanceof FunctionDescriptor) {
454 if (KotlinBuiltIns.isUnit(((FunctionDescriptor) descriptor).getReturnType())) {
455 hasReassignMethodReturningUnit = true;
456 }
457 }
458 if (descriptor == null) {
459 Collection<? extends DeclarationDescriptor> descriptors =
460 trace.get(BindingContext.AMBIGUOUS_REFERENCE_TARGET, operationReference);
461 if (descriptors != null) {
462 for (DeclarationDescriptor referenceDescriptor : descriptors) {
463 if (KotlinBuiltIns.isUnit(((FunctionDescriptor) referenceDescriptor).getReturnType())) {
464 hasReassignMethodReturningUnit = true;
465 }
466 }
467 }
468 }
469 }
470 if (!hasReassignMethodReturningUnit) {
471 if (!isThisOrNoDispatchReceiver || !varWithValReassignErrorGenerated.contains(variableDescriptor)) {
472 report(Errors.VAL_REASSIGNMENT.on(expression, variableDescriptor), ctxt);
473 }
474 if (isThisOrNoDispatchReceiver) {
475 // try to get rid of repeating VAL_REASSIGNMENT diagnostic only for vars with no receiver
476 // or when receiver is this
477 varWithValReassignErrorGenerated.add(variableDescriptor);
478 }
479 return true;
480 }
481 }
482 return false;
483 }
484
485 private boolean checkAssignmentBeforeDeclaration(@NotNull VariableInitContext ctxt, @NotNull KtExpression expression) {
486 if (!ctxt.enterInitState.isDeclared && !ctxt.exitInitState.isDeclared
487 && !ctxt.enterInitState.mayBeInitialized() && ctxt.exitInitState.mayBeInitialized()) {
488 report(Errors.INITIALIZATION_BEFORE_DECLARATION.on(expression, ctxt.variableDescriptor), ctxt);
489 return true;
490 }
491 return false;
492 }
493
494 private boolean checkInitializationUsingBackingField(@NotNull VariableInitContext ctxt, @NotNull KtExpression expression) {
495 VariableDescriptor variableDescriptor = ctxt.variableDescriptor;
496 if (variableDescriptor instanceof PropertyDescriptor
497 && !ctxt.enterInitState.mayBeInitialized()
498 && ctxt.exitInitState.mayBeInitialized()) {
499 if (!variableDescriptor.isVar()) return false;
500 if (!trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor)) return false;
501 PsiElement property = DescriptorToSourceUtils.descriptorToDeclaration(variableDescriptor);
502 assert property instanceof KtProperty;
503 KtPropertyAccessor setter = ((KtProperty) property).getSetter();
504 if (((PropertyDescriptor) variableDescriptor).getModality() == Modality.FINAL && (setter == null || !setter.hasBody())) {
505 return false;
506 }
507 KtExpression variable = expression;
508 if (expression instanceof KtDotQualifiedExpression) {
509 if (((KtDotQualifiedExpression) expression).getReceiverExpression() instanceof KtThisExpression) {
510 variable = ((KtDotQualifiedExpression) expression).getSelectorExpression();
511 }
512 }
513 if (variable instanceof KtSimpleNameExpression) {
514 KtSimpleNameExpression simpleNameExpression = (KtSimpleNameExpression) variable;
515 if (simpleNameExpression.getReferencedNameElementType() != KtTokens.FIELD_IDENTIFIER) {
516 trace.record(IS_UNINITIALIZED, (PropertyDescriptor) variableDescriptor);
517 return true;
518 }
519 }
520 }
521 return false;
522 }
523
524 private boolean checkBackingField(@NotNull VariableContext cxtx, @NotNull KtElement element) {
525 VariableDescriptor variableDescriptor = cxtx.variableDescriptor;
526 boolean[] error = new boolean[1];
527 if (!isCorrectBackingFieldReference(element, cxtx, error, true)) return false;
528 if (error[0]) return true;
529 if (!(variableDescriptor instanceof PropertyDescriptor)) {
530 report(Errors.NOT_PROPERTY_BACKING_FIELD.on(element), cxtx);
531 return true;
532 }
533 PsiElement property = DescriptorToSourceUtils.descriptorToDeclaration(variableDescriptor);
534 boolean insideSelfAccessors = PsiTreeUtil.isAncestor(property, element, false);
535 if (!trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor) &&
536 // not to generate error in accessors of abstract properties, there is one: declared accessor of abstract property
537 !insideSelfAccessors) {
538
539 if (((PropertyDescriptor) variableDescriptor).getModality() == Modality.ABSTRACT) {
540 report(NO_BACKING_FIELD_ABSTRACT_PROPERTY.on(element), cxtx);
541 }
542 else {
543 report(NO_BACKING_FIELD_CUSTOM_ACCESSORS.on(element), cxtx);
544 }
545 return true;
546 }
547 if (insideSelfAccessors) return false;
548
549 DeclarationDescriptor declarationDescriptor = BindingContextUtils.getEnclosingDescriptor(trace.getBindingContext(), element);
550
551 DeclarationDescriptor containingDeclaration = variableDescriptor.getContainingDeclaration();
552 if ((containingDeclaration instanceof ClassDescriptor)
553 && DescriptorUtils.isAncestor(containingDeclaration, declarationDescriptor, false)) {
554 if (element instanceof KtSimpleNameExpression) {
555 report(Errors.BACKING_FIELD_USAGE_FORBIDDEN.on((KtSimpleNameExpression) element), cxtx);
556 }
557 return false;
558 }
559 report(Errors.INACCESSIBLE_BACKING_FIELD.on(element), cxtx);
560 return true;
561 }
562
563 private boolean isCorrectBackingFieldReference(
564 @Nullable KtElement element,
565 VariableContext ctxt,
566 boolean[] error,
567 boolean reportError
568 ) {
569 error[0] = false;
570 if (KtPsiUtil.isBackingFieldReference(element, null)) {
571 return true;
572 }
573 if (element instanceof KtDotQualifiedExpression && isCorrectBackingFieldReference(
574 ((KtDotQualifiedExpression) element).getSelectorExpression(), ctxt, error, false)) {
575 if (((KtDotQualifiedExpression) element).getReceiverExpression() instanceof KtThisExpression) {
576 return true;
577 }
578 error[0] = true;
579 if (reportError) {
580 report(Errors.INACCESSIBLE_BACKING_FIELD.on(element), ctxt);
581 }
582 }
583 return false;
584 }
585
586 private void recordInitializedVariables(
587 @NotNull Pseudocode pseudocode,
588 @NotNull Map<Instruction, Edges<Map<VariableDescriptor, VariableControlFlowState>>> initializersMap
589 ) {
590 Edges<Map<VariableDescriptor, VariableControlFlowState>> initializers = initializersMap.get(pseudocode.getExitInstruction());
591 if (initializers == null) return;
592 Set<VariableDescriptor> declaredVariables = getPseudocodeVariablesData().getDeclaredVariables(pseudocode, false);
593 for (VariableDescriptor variable : declaredVariables) {
594 if (variable instanceof PropertyDescriptor) {
595 VariableControlFlowState variableControlFlowState = initializers.getIncoming().get(variable);
596 if (variableControlFlowState != null && variableControlFlowState.definitelyInitialized()) continue;
597 trace.record(BindingContext.IS_UNINITIALIZED, (PropertyDescriptor) variable);
598 }
599 }
600 }
601
602 ////////////////////////////////////////////////////////////////////////////////
603 // "Unused variable" & "unused value" analyses
604
605 public void markUnusedVariables() {
606 final PseudocodeVariablesData pseudocodeVariablesData = getPseudocodeVariablesData();
607 Map<Instruction, Edges<Map<VariableDescriptor, VariableUseState>>> variableStatusData =
608 pseudocodeVariablesData.getVariableUseStatusData();
609 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap = Maps.newHashMap();
610 InstructionDataAnalyzeStrategy<Map<VariableDescriptor, VariableUseState>> variableStatusAnalyzeStrategy =
611 new InstructionDataAnalyzeStrategy<Map<VariableDescriptor, VariableUseState>>() {
612 @Override
613 public void execute(
614 @NotNull Instruction instruction,
615 @Nullable Map<VariableDescriptor, VariableUseState> in,
616 @Nullable Map<VariableDescriptor, VariableUseState> out
617 ) {
618
619 assert in != null && out != null;
620 VariableContext ctxt = new VariableUseContext(instruction, reportedDiagnosticMap, in, out);
621 Set<VariableDescriptor> declaredVariables =
622 pseudocodeVariablesData.getDeclaredVariables(instruction.getOwner(), false);
623 VariableDescriptor variableDescriptor = PseudocodeUtil.extractVariableDescriptorIfAny(
624 instruction, false, trace.getBindingContext());
625 if (variableDescriptor == null || !declaredVariables.contains(variableDescriptor)
626 || !ExpressionTypingUtils.isLocal(variableDescriptor.getContainingDeclaration(), variableDescriptor)) {
627 return;
628 }
629 PseudocodeVariablesData.VariableUseState variableUseState = in.get(variableDescriptor);
630 if (instruction instanceof WriteValueInstruction) {
631 if (trace.get(CAPTURED_IN_CLOSURE, variableDescriptor) != null) return;
632 KtElement element = ((WriteValueInstruction) instruction).getElement();
633 if (variableUseState != READ) {
634 if (element instanceof KtBinaryExpression &&
635 ((KtBinaryExpression) element).getOperationToken() == KtTokens.EQ) {
636 KtExpression right = ((KtBinaryExpression) element).getRight();
637 if (right != null) {
638 report(Errors.UNUSED_VALUE.on((KtBinaryExpression) element, right, variableDescriptor), ctxt);
639 }
640 }
641 else if (element instanceof KtPostfixExpression) {
642 IElementType operationToken =
643 ((KtPostfixExpression) element).getOperationReference().getReferencedNameElementType();
644 if (operationToken == KtTokens.PLUSPLUS || operationToken == KtTokens.MINUSMINUS) {
645 report(Errors.UNUSED_CHANGED_VALUE.on(element, element), ctxt);
646 }
647 }
648 }
649 }
650 else if (instruction instanceof VariableDeclarationInstruction) {
651 KtDeclaration element = ((VariableDeclarationInstruction) instruction).getVariableDeclarationElement();
652 if (!(element instanceof KtNamedDeclaration)) return;
653 PsiElement nameIdentifier = ((KtNamedDeclaration) element).getNameIdentifier();
654 if (nameIdentifier == null) return;
655 if (!VariableUseState.isUsed(variableUseState)) {
656 if (KtPsiUtil.isVariableNotParameterDeclaration(element)) {
657 report(Errors.UNUSED_VARIABLE.on((KtNamedDeclaration) element, variableDescriptor), ctxt);
658 }
659 else if (element instanceof KtParameter) {
660 PsiElement owner = element.getParent().getParent();
661 if (owner instanceof KtPrimaryConstructor) {
662 if (!((KtParameter) element).hasValOrVar()) {
663 KtClassOrObject containingClass = ((KtPrimaryConstructor) owner).getContainingClassOrObject();
664 DeclarationDescriptor containingClassDescriptor = trace.get(
665 BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass
666 );
667 if (!DescriptorUtils.isAnnotationClass(containingClassDescriptor)) {
668 report(Errors.UNUSED_PARAMETER.on((KtParameter) element, variableDescriptor), ctxt);
669 }
670 }
671 }
672 else if (owner instanceof KtFunction) {
673 MainFunctionDetector mainFunctionDetector = new MainFunctionDetector(trace.getBindingContext());
674 boolean isMain = (owner instanceof KtNamedFunction) && mainFunctionDetector.isMain((KtNamedFunction) owner);
675 if (owner instanceof KtFunctionLiteral) return;
676 DeclarationDescriptor descriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, owner);
677 assert descriptor instanceof FunctionDescriptor : owner.getText();
678 FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor;
679 String functionName = functionDescriptor.getName().asString();
680 if (isMain
681 || functionDescriptor.getModality().isOverridable()
682 || !functionDescriptor.getOverriddenDescriptors().isEmpty()
683 || "getValue".equals(functionName) || "setValue".equals(functionName)
684 || "propertyDelegated".equals(functionName)
685 ) {
686 return;
687 }
688 report(Errors.UNUSED_PARAMETER.on((KtParameter) element, variableDescriptor), ctxt);
689 }
690 }
691 }
692 else if (variableUseState == ONLY_WRITTEN_NEVER_READ && KtPsiUtil.isVariableNotParameterDeclaration(element)) {
693 report(Errors.ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE.on((KtNamedDeclaration) element, variableDescriptor), ctxt);
694 }
695 else if (variableUseState == WRITTEN_AFTER_READ && element instanceof KtVariableDeclaration) {
696 if (element instanceof KtProperty) {
697 KtExpression initializer = ((KtProperty) element).getInitializer();
698 if (initializer != null) {
699 report(Errors.VARIABLE_WITH_REDUNDANT_INITIALIZER.on(initializer, variableDescriptor), ctxt);
700 }
701 }
702 else if (element instanceof KtMultiDeclarationEntry) {
703 report(VARIABLE_WITH_REDUNDANT_INITIALIZER.on(element, variableDescriptor), ctxt);
704 }
705 }
706 }
707 }
708 };
709 PseudocodeTraverserKt.traverse(pseudocode, TraversalOrder.BACKWARD, variableStatusData, variableStatusAnalyzeStrategy);
710 }
711
712 ////////////////////////////////////////////////////////////////////////////////
713 // "Unused expressions" in block
714
715 public void markUnusedExpressions() {
716 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap = Maps.newHashMap();
717 PseudocodeTraverserKt.traverse(
718 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() {
719 @Override
720 public void execute(@NotNull Instruction instruction) {
721 if (!(instruction instanceof JetElementInstruction)) return;
722
723 KtElement element = ((JetElementInstruction)instruction).getElement();
724 if (!(element instanceof KtExpression)) return;
725
726 if (BindingContextUtilsKt.isUsedAsStatement((KtExpression) element, trace.getBindingContext())
727 && PseudocodeUtilsKt.getSideEffectFree(instruction)) {
728 VariableContext ctxt = new VariableContext(instruction, reportedDiagnosticMap);
729 report(
730 element instanceof KtFunctionLiteralExpression
731 ? Errors.UNUSED_FUNCTION_LITERAL.on((KtFunctionLiteralExpression) element)
732 : Errors.UNUSED_EXPRESSION.on(element),
733 ctxt
734 );
735 }
736 }
737 }
738 );
739 }
740
741 ////////////////////////////////////////////////////////////////////////////////
742 // Statements
743
744 public void markStatements() {
745 PseudocodeTraverserKt.traverse(
746 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() {
747 @Override
748 public void execute(@NotNull Instruction instruction) {
749 PseudoValue value = instruction instanceof InstructionWithValue
750 ? ((InstructionWithValue) instruction).getOutputValue()
751 : null;
752 Pseudocode pseudocode = instruction.getOwner();
753 boolean isUsedAsExpression = !pseudocode.getUsages(value).isEmpty();
754 for (KtElement element : pseudocode.getValueElements(value)) {
755 trace.record(BindingContext.USED_AS_EXPRESSION, element, isUsedAsExpression);
756 }
757 }
758 }
759 );
760 }
761
762 public void markWhenWithoutElse() {
763 PseudocodeTraverserKt.traverse(
764 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() {
765 @Override
766 public void execute(@NotNull Instruction instruction) {
767 PseudoValue value = instruction instanceof InstructionWithValue
768 ? ((InstructionWithValue) instruction).getOutputValue()
769 : null;
770 for (KtElement element : instruction.getOwner().getValueElements(value)) {
771 if (!(element instanceof KtWhenExpression)) continue;
772 KtWhenExpression whenExpression = (KtWhenExpression) element;
773 if (whenExpression.getElseExpression() != null) continue;
774
775 if (WhenChecker.mustHaveElse(whenExpression, trace)) {
776 trace.report(NO_ELSE_IN_WHEN.on(whenExpression));
777 }
778 else if (whenExpression.getSubjectExpression() != null) {
779 ClassDescriptor enumClassDescriptor = WhenChecker.getClassDescriptorOfTypeIfEnum(
780 trace.getType(whenExpression.getSubjectExpression()));
781 if (enumClassDescriptor != null
782 && !WhenChecker.isWhenOnEnumExhaustive(whenExpression, trace, enumClassDescriptor)) {
783 trace.report(NON_EXHAUSTIVE_WHEN.on(whenExpression));
784 }
785 }
786 }
787 }
788 }
789 );
790 }
791
792 ////////////////////////////////////////////////////////////////////////////////
793 // Tail calls
794
795 public void markTailCalls() {
796 final DeclarationDescriptor subroutineDescriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, subroutine);
797 if (!(subroutineDescriptor instanceof FunctionDescriptor)) return;
798 if (!((FunctionDescriptor) subroutineDescriptor).isTailrec()) return;
799
800 // finally blocks are copied which leads to multiple diagnostics reported on one instruction
801 class KindAndCall {
802 TailRecursionKind kind;
803 ResolvedCall<?> call;
804
805 KindAndCall(TailRecursionKind kind, ResolvedCall<?> call) {
806 this.kind = kind;
807 this.call = call;
808 }
809 }
810 final Map<KtElement, KindAndCall> calls = new HashMap<KtElement, KindAndCall>();
811 PseudocodeTraverserKt.traverse(
812 pseudocode,
813 FORWARD,
814 new FunctionVoid1<Instruction>() {
815 public void execute(@NotNull Instruction instruction) {
816 if (!(instruction instanceof CallInstruction)) return;
817 CallInstruction callInstruction = (CallInstruction) instruction;
818
819 ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCall(callInstruction.getElement(), trace.getBindingContext());
820 if (resolvedCall == null) return;
821
822 // is this a recursive call?
823 CallableDescriptor functionDescriptor = resolvedCall.getResultingDescriptor();
824 if (!functionDescriptor.getOriginal().equals(subroutineDescriptor)) return;
825
826 KtElement element = callInstruction.getElement();
827 //noinspection unchecked
828 KtExpression parent = PsiTreeUtil.getParentOfType(
829 element,
830 KtTryExpression.class, KtFunction.class, KtClassInitializer.class
831 );
832
833 if (parent instanceof KtTryExpression) {
834 // We do not support tail calls Collections.singletonMap() try-catch-finally, for simplicity of the mental model
835 // very few cases there would be real tail-calls, and it's often not so easy for the user to see why
836 calls.put(element, new KindAndCall(IN_TRY, resolvedCall));
837 return;
838 }
839
840 boolean isTail = PseudocodeTraverserKt.traverseFollowingInstructions(
841 callInstruction,
842 new HashSet<Instruction>(),
843 FORWARD,
844 new TailRecursionDetector(subroutine, callInstruction)
845 );
846
847 // A tail call is not allowed to change dispatch receiver
848 // class C {
849 // fun foo(other: C) {
850 // other.foo(this) // not a tail call
851 // }
852 // }
853 boolean sameDispatchReceiver =
854 ResolvedCallUtilKt.hasThisOrNoDispatchReceiver(resolvedCall, trace.getBindingContext());
855
856 TailRecursionKind kind = isTail && sameDispatchReceiver ? TAIL_CALL : NON_TAIL;
857
858 KindAndCall kindAndCall = calls.get(element);
859 calls.put(element,
860 new KindAndCall(
861 combineKinds(kind, kindAndCall == null ? null : kindAndCall.kind),
862 resolvedCall
863 )
864 );
865 }
866 }
867 );
868 boolean hasTailCalls = false;
869 for (Map.Entry<KtElement, KindAndCall> entry : calls.entrySet()) {
870 KtElement element = entry.getKey();
871 KindAndCall kindAndCall = entry.getValue();
872 switch (kindAndCall.kind) {
873 case TAIL_CALL:
874 trace.record(TAIL_RECURSION_CALL, kindAndCall.call, TailRecursionKind.TAIL_CALL);
875 hasTailCalls = true;
876 break;
877 case IN_TRY:
878 trace.report(Errors.TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED.on(element));
879 break;
880 case NON_TAIL:
881 trace.report(Errors.NON_TAIL_RECURSIVE_CALL.on(element));
882 break;
883 }
884 }
885
886 if (!hasTailCalls) {
887 trace.report(Errors.NO_TAIL_CALLS_FOUND.on((KtNamedFunction) subroutine));
888 }
889 }
890
891 private static TailRecursionKind combineKinds(TailRecursionKind kind, @Nullable TailRecursionKind existingKind) {
892 TailRecursionKind resultingKind;
893 if (existingKind == null || existingKind == kind) {
894 resultingKind = kind;
895 }
896 else {
897 if (check(kind, existingKind, IN_TRY, TAIL_CALL)) {
898 resultingKind = IN_TRY;
899 }
900 else if (check(kind, existingKind, IN_TRY, NON_TAIL)) {
901 resultingKind = IN_TRY;
902 }
903 else {
904 // TAIL_CALL, NON_TAIL
905 resultingKind = NON_TAIL;
906 }
907 }
908 return resultingKind;
909 }
910
911 private static boolean check(Object a, Object b, Object x, Object y) {
912 return (a == x && b == y) || (a == y && b == x);
913 }
914
915 ////////////////////////////////////////////////////////////////////////////////
916 // Utility classes and methods
917
918 /**
919 * The method provides reporting of the same diagnostic only once for copied instructions
920 * (depends on whether it should be reported for all or only for one of the copies)
921 */
922 private void report(
923 @NotNull Diagnostic diagnostic,
924 @NotNull VariableContext ctxt
925 ) {
926 Instruction instruction = ctxt.instruction;
927 if (instruction.getCopies().isEmpty()) {
928 trace.report(diagnostic);
929 return;
930 }
931 Map<Instruction, DiagnosticFactory<?>> previouslyReported = ctxt.reportedDiagnosticMap;
932 previouslyReported.put(instruction, diagnostic.getFactory());
933
934 boolean alreadyReported = false;
935 boolean sameErrorForAllCopies = true;
936 for (Instruction copy : instruction.getCopies()) {
937 DiagnosticFactory<?> previouslyReportedErrorFactory = previouslyReported.get(copy);
938 if (previouslyReportedErrorFactory != null) {
939 alreadyReported = true;
940 }
941
942 if (previouslyReportedErrorFactory != diagnostic.getFactory()) {
943 sameErrorForAllCopies = false;
944 }
945 }
946
947 if (mustBeReportedOnAllCopies(diagnostic.getFactory())) {
948 if (sameErrorForAllCopies) {
949 trace.report(diagnostic);
950 }
951 }
952 else {
953 //only one reporting required
954 if (!alreadyReported) {
955 trace.report(diagnostic);
956 }
957 }
958 }
959
960 private static boolean mustBeReportedOnAllCopies(@NotNull DiagnosticFactory<?> diagnosticFactory) {
961 return diagnosticFactory == UNUSED_VARIABLE
962 || diagnosticFactory == UNUSED_PARAMETER
963 || diagnosticFactory == UNUSED_CHANGED_VALUE;
964 }
965
966
967 private class VariableContext {
968 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap;
969 final Instruction instruction;
970 final VariableDescriptor variableDescriptor;
971
972 private VariableContext(
973 @NotNull Instruction instruction,
974 @NotNull Map<Instruction, DiagnosticFactory<?>> map
975 ) {
976 this.instruction = instruction;
977 reportedDiagnosticMap = map;
978 variableDescriptor = PseudocodeUtil.extractVariableDescriptorIfAny(instruction, true, trace.getBindingContext());
979 }
980 }
981
982 private class VariableInitContext extends VariableContext {
983 final VariableControlFlowState enterInitState;
984 final VariableControlFlowState exitInitState;
985
986 private VariableInitContext(
987 @NotNull Instruction instruction,
988 @NotNull Map<Instruction, DiagnosticFactory<?>> map,
989 @NotNull Map<VariableDescriptor, VariableControlFlowState> in,
990 @NotNull Map<VariableDescriptor, VariableControlFlowState> out,
991 @NotNull LexicalScopeVariableInfo lexicalScopeVariableInfo
992 ) {
993 super(instruction, map);
994 enterInitState = initialize(variableDescriptor, lexicalScopeVariableInfo, in);
995 exitInitState = initialize(variableDescriptor, lexicalScopeVariableInfo, out);
996 }
997
998 private VariableControlFlowState initialize(
999 VariableDescriptor variableDescriptor,
1000 LexicalScopeVariableInfo lexicalScopeVariableInfo,
1001 Map<VariableDescriptor, VariableControlFlowState> map
1002 ) {
1003 if (variableDescriptor == null) return null;
1004 VariableControlFlowState state = map.get(variableDescriptor);
1005 if (state != null) return state;
1006 return PseudocodeVariablesData.getDefaultValueForInitializers(variableDescriptor, instruction, lexicalScopeVariableInfo);
1007 }
1008 }
1009
1010 private class VariableUseContext extends VariableContext {
1011 final VariableUseState enterUseState;
1012 final VariableUseState exitUseState;
1013
1014
1015 private VariableUseContext(
1016 @NotNull Instruction instruction,
1017 @NotNull Map<Instruction, DiagnosticFactory<?>> map,
1018 @NotNull Map<VariableDescriptor, VariableUseState> in,
1019 @NotNull Map<VariableDescriptor, VariableUseState> out
1020 ) {
1021 super(instruction, map);
1022 enterUseState = variableDescriptor != null ? in.get(variableDescriptor) : null;
1023 exitUseState = variableDescriptor != null ? out.get(variableDescriptor) : null;
1024 }
1025 }
1026
1027 //TODO after KT-4621 rewrite to Kotlin
1028 public abstract static class InstructionDataAnalyzeStrategy<D> implements Function3<Instruction, D, D, Unit> {
1029 @Override
1030 public Unit invoke(Instruction instruction, D enterData, D exitData) {
1031 execute(instruction, enterData, exitData);
1032 return Unit.INSTANCE$;
1033 }
1034
1035 public abstract void execute(Instruction instruction, D enterData, D exitData);
1036 }
1037
1038 public abstract static class FunctionVoid1<P> implements Function1<P, Unit> {
1039 @Override
1040 public Unit invoke(P p) {
1041 execute(p);
1042 return Unit.INSTANCE$;
1043 }
1044
1045 public abstract void execute(P p);
1046 }
1047 }