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.PseudocodePackage; 036 import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtil; 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.PseudocodeTraverserPackage; 048 import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder; 049 import org.jetbrains.kotlin.descriptors.*; 050 import org.jetbrains.kotlin.diagnostics.Diagnostic; 051 import org.jetbrains.kotlin.diagnostics.DiagnosticFactory; 052 import org.jetbrains.kotlin.diagnostics.Errors; 053 import org.jetbrains.kotlin.idea.MainFunctionDetector; 054 import org.jetbrains.kotlin.lexer.JetTokens; 055 import org.jetbrains.kotlin.psi.*; 056 import org.jetbrains.kotlin.resolve.*; 057 import org.jetbrains.kotlin.resolve.bindingContextUtil.BindingContextUtilPackage; 058 import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage; 059 import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall; 060 import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.ResolvedCallUtilPackage; 061 import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue; 062 import org.jetbrains.kotlin.types.JetType; 063 import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils; 064 065 import java.util.*; 066 067 import static org.jetbrains.kotlin.cfg.PseudocodeVariablesData.VariableUseState.*; 068 import static org.jetbrains.kotlin.cfg.TailRecursionKind.*; 069 import static org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder.FORWARD; 070 import static org.jetbrains.kotlin.diagnostics.Errors.*; 071 import static org.jetbrains.kotlin.resolve.BindingContext.CAPTURED_IN_CLOSURE; 072 import static org.jetbrains.kotlin.resolve.BindingContext.TAIL_RECURSION_CALL; 073 import static org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage.getResolvedCall; 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 JetElement subroutine; 080 private final Pseudocode pseudocode; 081 private final BindingTrace trace; 082 private PseudocodeVariablesData pseudocodeVariablesData; 083 084 private JetFlowInformationProvider( 085 @NotNull JetElement 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 JetElement 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 JetType expectedReturnType) { 133 UnreachableCode unreachableCode = collectUnreachableCode(); 134 reportUnreachableCode(unreachableCode); 135 136 if (subroutine instanceof JetFunctionLiteral) return; 137 138 checkDefiniteReturn(expectedReturnType != null ? expectedReturnType : NO_EXPECTED_TYPE, unreachableCode); 139 140 markTailCalls(); 141 } 142 143 private void collectReturnExpressions(@NotNull final Collection<JetElement> 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 JetElement element = localDeclarationInstruction.getElement(); 206 if (element instanceof JetDeclarationWithBody) { 207 JetDeclarationWithBody localDeclaration = (JetDeclarationWithBody) element; 208 209 CallableDescriptor functionDescriptor = 210 (CallableDescriptor) trace.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, localDeclaration); 211 JetType 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 JetType expectedReturnType, @NotNull final UnreachableCode unreachableCode) { 222 assert subroutine instanceof JetDeclarationWithBody; 223 JetDeclarationWithBody function = (JetDeclarationWithBody) subroutine; 224 225 if (!function.hasBody()) return; 226 227 List<JetElement> returnedExpressions = Lists.newArrayList(); 228 collectReturnExpressions(returnedExpressions); 229 230 final boolean blockBody = function.hasBlockBody(); 231 232 final boolean[] noReturnError = new boolean[] { false }; 233 for (JetElement returnedExpression : returnedExpressions) { 234 returnedExpression.accept(new JetVisitorVoid() { 235 @Override 236 public void visitReturnExpression(@NotNull JetReturnExpression 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 JetElement element) { 244 if (!(element instanceof JetExpression || element instanceof JetWhenCondition)) 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 (JetElement 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<JetElement> reachableElements = Sets.newHashSet(); 269 Set<JetElement> 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 JetElement element = ((JetElementInstruction) instruction).getElement(); 277 278 if (instruction instanceof JumpInstruction) { 279 boolean isJumpElement = element instanceof JetBreakExpression 280 || element instanceof JetContinueExpression 281 || element instanceof JetReturnExpression 282 || element instanceof JetThrowExpression; 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 JetClassOrObject; 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 PseudocodeTraverserPackage.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 JetElement 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 JetElement element = writeValueInstruction.getlValue(); 339 boolean error = checkBackingField(ctxt, element); 340 if (!(element instanceof JetExpression)) return; 341 if (!error) { 342 error = checkValReassignment(ctxt, (JetExpression) element, writeValueInstruction, 343 varWithValReassignErrorGenerated); 344 } 345 if (!error && processClassOrObject) { 346 error = checkAssignmentBeforeDeclaration(ctxt, (JetExpression) element); 347 } 348 if (!error && processClassOrObject) { 349 checkInitializationUsingBackingField(ctxt, (JetExpression) 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 JetElement element, 370 @NotNull Collection<VariableDescriptor> varWithUninitializedErrorGenerated 371 ) { 372 if (!(element instanceof JetSimpleNameExpression)) return; 373 374 375 boolean isDefinitelyInitialized = ctxt.exitInitState.definitelyInitialized(); 376 VariableDescriptor variableDescriptor = ctxt.variableDescriptor; 377 if (variableDescriptor instanceof PropertyDescriptor) { 378 if (!trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor)) { 379 isDefinitelyInitialized = true; 380 } 381 } 382 if (!isDefinitelyInitialized && !varWithUninitializedErrorGenerated.contains(variableDescriptor)) { 383 if (!(variableDescriptor instanceof PropertyDescriptor)) { 384 varWithUninitializedErrorGenerated.add(variableDescriptor); 385 } 386 if (variableDescriptor instanceof ValueParameterDescriptor) { 387 report(Errors.UNINITIALIZED_PARAMETER.on((JetSimpleNameExpression) element, 388 (ValueParameterDescriptor) variableDescriptor), ctxt); 389 } 390 else { 391 report(Errors.UNINITIALIZED_VARIABLE.on((JetSimpleNameExpression) element, variableDescriptor), ctxt); 392 } 393 } 394 } 395 396 private boolean checkValReassignment( 397 @NotNull VariableInitContext ctxt, 398 @NotNull JetExpression expression, 399 @NotNull WriteValueInstruction writeValueInstruction, 400 @NotNull Collection<VariableDescriptor> varWithValReassignErrorGenerated 401 ) { 402 VariableDescriptor variableDescriptor = ctxt.variableDescriptor; 403 if (JetPsiUtil.isBackingFieldReference(expression) && variableDescriptor instanceof PropertyDescriptor) { 404 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) variableDescriptor; 405 JetPropertyAccessor accessor = PsiTreeUtil.getParentOfType(expression, JetPropertyAccessor.class); 406 if (accessor != null) { 407 DeclarationDescriptor accessorDescriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, accessor); 408 if (propertyDescriptor.getGetter() == accessorDescriptor) { 409 //val can be reassigned through backing field inside its own getter 410 return false; 411 } 412 } 413 } 414 415 boolean mayBeInitializedNotHere = ctxt.enterInitState.mayBeInitialized(); 416 boolean hasBackingField = true; 417 if (variableDescriptor instanceof PropertyDescriptor) { 418 hasBackingField = trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor); 419 } 420 if (variableDescriptor.isVar() && variableDescriptor instanceof PropertyDescriptor) { 421 DeclarationDescriptor descriptor = BindingContextUtils.getEnclosingDescriptor(trace.getBindingContext(), expression); 422 PropertySetterDescriptor setterDescriptor = ((PropertyDescriptor) variableDescriptor).getSetter(); 423 424 ResolvedCall<? extends CallableDescriptor> resolvedCall = CallUtilPackage.getResolvedCall(expression, trace.getBindingContext()); 425 ReceiverValue receiverValue = ReceiverValue.IRRELEVANT_RECEIVER; 426 if (resolvedCall != null) { 427 receiverValue = ExpressionTypingUtils 428 .normalizeReceiverValueForVisibility(resolvedCall.getDispatchReceiver(), trace.getBindingContext()); 429 430 } 431 if (Visibilities.isVisible(receiverValue, variableDescriptor, descriptor) && setterDescriptor != null 432 && !Visibilities.isVisible(receiverValue, setterDescriptor, descriptor)) { 433 report(Errors.INVISIBLE_SETTER.on(expression, variableDescriptor, setterDescriptor.getVisibility(), 434 variableDescriptor.getContainingDeclaration()), ctxt); 435 return true; 436 } 437 } 438 boolean isThisOrNoDispatchReceiver = 439 PseudocodeUtil.isThisOrNoDispatchReceiver(writeValueInstruction, trace.getBindingContext()); 440 if ((mayBeInitializedNotHere || !hasBackingField || !isThisOrNoDispatchReceiver) && !variableDescriptor.isVar()) { 441 boolean hasReassignMethodReturningUnit = false; 442 JetSimpleNameExpression operationReference = null; 443 PsiElement parent = expression.getParent(); 444 if (parent instanceof JetBinaryExpression) { 445 operationReference = ((JetBinaryExpression) parent).getOperationReference(); 446 } 447 else if (parent instanceof JetUnaryExpression) { 448 operationReference = ((JetUnaryExpression) parent).getOperationReference(); 449 } 450 if (operationReference != null) { 451 DeclarationDescriptor descriptor = trace.get(BindingContext.REFERENCE_TARGET, operationReference); 452 if (descriptor instanceof FunctionDescriptor) { 453 if (KotlinBuiltIns.isUnit(((FunctionDescriptor) descriptor).getReturnType())) { 454 hasReassignMethodReturningUnit = true; 455 } 456 } 457 if (descriptor == null) { 458 Collection<? extends DeclarationDescriptor> descriptors = 459 trace.get(BindingContext.AMBIGUOUS_REFERENCE_TARGET, operationReference); 460 if (descriptors != null) { 461 for (DeclarationDescriptor referenceDescriptor : descriptors) { 462 if (KotlinBuiltIns.isUnit(((FunctionDescriptor) referenceDescriptor).getReturnType())) { 463 hasReassignMethodReturningUnit = true; 464 } 465 } 466 } 467 } 468 } 469 if (!hasReassignMethodReturningUnit) { 470 if (!isThisOrNoDispatchReceiver || !varWithValReassignErrorGenerated.contains(variableDescriptor)) { 471 report(Errors.VAL_REASSIGNMENT.on(expression, variableDescriptor), ctxt); 472 } 473 if (isThisOrNoDispatchReceiver) { 474 // try to get rid of repeating VAL_REASSIGNMENT diagnostic only for vars with no receiver 475 // or when receiver is this 476 varWithValReassignErrorGenerated.add(variableDescriptor); 477 } 478 return true; 479 } 480 } 481 return false; 482 } 483 484 private boolean checkAssignmentBeforeDeclaration(@NotNull VariableInitContext ctxt, @NotNull JetExpression expression) { 485 if (!ctxt.enterInitState.isDeclared && !ctxt.exitInitState.isDeclared 486 && !ctxt.enterInitState.mayBeInitialized() && ctxt.exitInitState.mayBeInitialized()) { 487 report(Errors.INITIALIZATION_BEFORE_DECLARATION.on(expression, ctxt.variableDescriptor), ctxt); 488 return true; 489 } 490 return false; 491 } 492 493 private boolean checkInitializationUsingBackingField(@NotNull VariableInitContext ctxt, @NotNull JetExpression expression) { 494 VariableDescriptor variableDescriptor = ctxt.variableDescriptor; 495 if (variableDescriptor instanceof PropertyDescriptor 496 && !ctxt.enterInitState.mayBeInitialized() && ctxt.exitInitState.mayBeInitialized()) { 497 if (!variableDescriptor.isVar()) return false; 498 if (!trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor)) return false; 499 PsiElement property = DescriptorToSourceUtils.descriptorToDeclaration(variableDescriptor); 500 assert property instanceof JetProperty; 501 if (((PropertyDescriptor) variableDescriptor).getModality() == Modality.FINAL && ((JetProperty) property).getSetter() == null) { 502 return false; 503 } 504 JetExpression variable = expression; 505 if (expression instanceof JetDotQualifiedExpression) { 506 if (((JetDotQualifiedExpression) expression).getReceiverExpression() instanceof JetThisExpression) { 507 variable = ((JetDotQualifiedExpression) expression).getSelectorExpression(); 508 } 509 } 510 if (variable instanceof JetSimpleNameExpression) { 511 JetSimpleNameExpression simpleNameExpression = (JetSimpleNameExpression) variable; 512 if (simpleNameExpression.getReferencedNameElementType() != JetTokens.FIELD_IDENTIFIER) { 513 if (((PropertyDescriptor) variableDescriptor).getModality() != Modality.FINAL) { 514 report(Errors.INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER.on(expression, variableDescriptor), ctxt); 515 } 516 else { 517 report(Errors.INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER.on(expression, variableDescriptor), ctxt); 518 } 519 return true; 520 } 521 } 522 } 523 return false; 524 } 525 526 private boolean checkBackingField(@NotNull VariableContext cxtx, @NotNull JetElement element) { 527 VariableDescriptor variableDescriptor = cxtx.variableDescriptor; 528 boolean[] error = new boolean[1]; 529 if (!isCorrectBackingFieldReference(element, cxtx, error, true)) return false; 530 if (error[0]) return true; 531 if (!(variableDescriptor instanceof PropertyDescriptor)) { 532 report(Errors.NOT_PROPERTY_BACKING_FIELD.on(element), cxtx); 533 return true; 534 } 535 PsiElement property = DescriptorToSourceUtils.descriptorToDeclaration(variableDescriptor); 536 boolean insideSelfAccessors = PsiTreeUtil.isAncestor(property, element, false); 537 if (!trace.get(BindingContext.BACKING_FIELD_REQUIRED, (PropertyDescriptor) variableDescriptor) && 538 // not to generate error in accessors of abstract properties, there is one: declared accessor of abstract property 539 !insideSelfAccessors) { 540 541 if (((PropertyDescriptor) variableDescriptor).getModality() == Modality.ABSTRACT) { 542 report(NO_BACKING_FIELD_ABSTRACT_PROPERTY.on(element), cxtx); 543 } 544 else { 545 report(NO_BACKING_FIELD_CUSTOM_ACCESSORS.on(element), cxtx); 546 } 547 return true; 548 } 549 if (insideSelfAccessors) return false; 550 551 DeclarationDescriptor declarationDescriptor = BindingContextUtils.getEnclosingDescriptor(trace.getBindingContext(), element); 552 553 DeclarationDescriptor containingDeclaration = variableDescriptor.getContainingDeclaration(); 554 if ((containingDeclaration instanceof ClassDescriptor) 555 && DescriptorUtils.isAncestor(containingDeclaration, declarationDescriptor, false)) { 556 return false; 557 } 558 report(Errors.INACCESSIBLE_BACKING_FIELD.on(element), cxtx); 559 return true; 560 } 561 562 private boolean isCorrectBackingFieldReference( 563 @Nullable JetElement element, 564 VariableContext ctxt, 565 boolean[] error, 566 boolean reportError 567 ) { 568 error[0] = false; 569 if (JetPsiUtil.isBackingFieldReference(element)) { 570 return true; 571 } 572 if (element instanceof JetDotQualifiedExpression && isCorrectBackingFieldReference( 573 ((JetDotQualifiedExpression) element).getSelectorExpression(), ctxt, error, false)) { 574 if (((JetDotQualifiedExpression) element).getReceiverExpression() instanceof JetThisExpression) { 575 return true; 576 } 577 error[0] = true; 578 if (reportError) { 579 report(Errors.INACCESSIBLE_BACKING_FIELD.on(element), ctxt); 580 } 581 } 582 return false; 583 } 584 585 private void recordInitializedVariables( 586 @NotNull Pseudocode pseudocode, 587 @NotNull Map<Instruction, Edges<Map<VariableDescriptor, VariableControlFlowState>>> initializersMap 588 ) { 589 Edges<Map<VariableDescriptor, VariableControlFlowState>> initializers = initializersMap.get(pseudocode.getExitInstruction()); 590 if (initializers == null) return; 591 Set<VariableDescriptor> declaredVariables = getPseudocodeVariablesData().getDeclaredVariables(pseudocode, false); 592 for (VariableDescriptor variable : declaredVariables) { 593 if (variable instanceof PropertyDescriptor) { 594 VariableControlFlowState variableControlFlowState = initializers.getIncoming().get(variable); 595 if (variableControlFlowState != null && variableControlFlowState.definitelyInitialized()) continue; 596 trace.record(BindingContext.IS_UNINITIALIZED, (PropertyDescriptor) variable); 597 } 598 } 599 } 600 601 //////////////////////////////////////////////////////////////////////////////// 602 // "Unused variable" & "unused value" analyses 603 604 public void markUnusedVariables() { 605 final PseudocodeVariablesData pseudocodeVariablesData = getPseudocodeVariablesData(); 606 Map<Instruction, Edges<Map<VariableDescriptor, VariableUseState>>> variableStatusData = 607 pseudocodeVariablesData.getVariableUseStatusData(); 608 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap = Maps.newHashMap(); 609 InstructionDataAnalyzeStrategy<Map<VariableDescriptor, VariableUseState>> variableStatusAnalyzeStrategy = 610 new InstructionDataAnalyzeStrategy<Map<VariableDescriptor, VariableUseState>>() { 611 @Override 612 public void execute( 613 @NotNull Instruction instruction, 614 @Nullable Map<VariableDescriptor, VariableUseState> in, 615 @Nullable Map<VariableDescriptor, VariableUseState> out 616 ) { 617 618 assert in != null && out != null; 619 VariableContext ctxt = new VariableUseContext(instruction, reportedDiagnosticMap, in, out); 620 Set<VariableDescriptor> declaredVariables = 621 pseudocodeVariablesData.getDeclaredVariables(instruction.getOwner(), false); 622 VariableDescriptor variableDescriptor = PseudocodeUtil.extractVariableDescriptorIfAny( 623 instruction, false, trace.getBindingContext()); 624 if (variableDescriptor == null || !declaredVariables.contains(variableDescriptor) 625 || !ExpressionTypingUtils.isLocal(variableDescriptor.getContainingDeclaration(), variableDescriptor)) { 626 return; 627 } 628 PseudocodeVariablesData.VariableUseState variableUseState = in.get(variableDescriptor); 629 if (instruction instanceof WriteValueInstruction) { 630 if (trace.get(CAPTURED_IN_CLOSURE, variableDescriptor) != null) return; 631 JetElement element = ((WriteValueInstruction) instruction).getElement(); 632 if (variableUseState != READ) { 633 if (element instanceof JetBinaryExpression && 634 ((JetBinaryExpression) element).getOperationToken() == JetTokens.EQ) { 635 JetExpression right = ((JetBinaryExpression) element).getRight(); 636 if (right != null) { 637 report(Errors.UNUSED_VALUE.on((JetBinaryExpression) element, right, variableDescriptor), ctxt); 638 } 639 } 640 else if (element instanceof JetPostfixExpression) { 641 IElementType operationToken = 642 ((JetPostfixExpression) element).getOperationReference().getReferencedNameElementType(); 643 if (operationToken == JetTokens.PLUSPLUS || operationToken == JetTokens.MINUSMINUS) { 644 report(Errors.UNUSED_CHANGED_VALUE.on(element, element), ctxt); 645 } 646 } 647 } 648 } 649 else if (instruction instanceof VariableDeclarationInstruction) { 650 JetDeclaration element = ((VariableDeclarationInstruction) instruction).getVariableDeclarationElement(); 651 if (!(element instanceof JetNamedDeclaration)) return; 652 PsiElement nameIdentifier = ((JetNamedDeclaration) element).getNameIdentifier(); 653 if (nameIdentifier == null) return; 654 if (!VariableUseState.isUsed(variableUseState)) { 655 if (JetPsiUtil.isVariableNotParameterDeclaration(element)) { 656 report(Errors.UNUSED_VARIABLE.on((JetNamedDeclaration) element, variableDescriptor), ctxt); 657 } 658 else if (element instanceof JetParameter) { 659 PsiElement owner = element.getParent().getParent(); 660 if (owner instanceof JetPrimaryConstructor) { 661 if (!((JetParameter) element).hasValOrVar()) { 662 JetClassOrObject containingClass = ((JetPrimaryConstructor) owner).getContainingClassOrObject(); 663 DeclarationDescriptor containingClassDescriptor = trace.get( 664 BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass 665 ); 666 if (!DescriptorUtils.isAnnotationClass(containingClassDescriptor)) { 667 report(Errors.UNUSED_PARAMETER.on((JetParameter) element, variableDescriptor), ctxt); 668 } 669 } 670 } 671 else if (owner instanceof JetFunction) { 672 MainFunctionDetector mainFunctionDetector = new MainFunctionDetector(trace.getBindingContext()); 673 boolean isMain = (owner instanceof JetNamedFunction) && mainFunctionDetector.isMain((JetNamedFunction) owner); 674 if (owner instanceof JetFunctionLiteral) return; 675 DeclarationDescriptor descriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, owner); 676 assert descriptor instanceof FunctionDescriptor : owner.getText(); 677 FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor; 678 String functionName = functionDescriptor.getName().asString(); 679 if (isMain 680 || functionDescriptor.getModality().isOverridable() 681 || !functionDescriptor.getOverriddenDescriptors().isEmpty() 682 || "get".equals(functionName) || "set".equals(functionName) || "propertyDelegated".equals(functionName) 683 ) { 684 return; 685 } 686 report(Errors.UNUSED_PARAMETER.on((JetParameter) element, variableDescriptor), ctxt); 687 } 688 } 689 } 690 else if (variableUseState == ONLY_WRITTEN_NEVER_READ && JetPsiUtil.isVariableNotParameterDeclaration(element)) { 691 report(Errors.ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE.on((JetNamedDeclaration) element, variableDescriptor), ctxt); 692 } 693 else if (variableUseState == WRITTEN_AFTER_READ && element instanceof JetVariableDeclaration) { 694 if (element instanceof JetProperty) { 695 JetExpression initializer = ((JetProperty) element).getInitializer(); 696 if (initializer != null) { 697 report(Errors.VARIABLE_WITH_REDUNDANT_INITIALIZER.on(initializer, variableDescriptor), ctxt); 698 } 699 } 700 else if (element instanceof JetMultiDeclarationEntry) { 701 report(VARIABLE_WITH_REDUNDANT_INITIALIZER.on(element, variableDescriptor), ctxt); 702 } 703 } 704 } 705 } 706 }; 707 PseudocodeTraverserPackage.traverse(pseudocode, TraversalOrder.BACKWARD, variableStatusData, variableStatusAnalyzeStrategy); 708 } 709 710 //////////////////////////////////////////////////////////////////////////////// 711 // "Unused expressions" in block 712 713 public void markUnusedExpressions() { 714 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap = Maps.newHashMap(); 715 PseudocodeTraverserPackage.traverse( 716 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() { 717 @Override 718 public void execute(@NotNull Instruction instruction) { 719 if (!(instruction instanceof JetElementInstruction)) return; 720 721 JetElement element = ((JetElementInstruction)instruction).getElement(); 722 if (!(element instanceof JetExpression)) return; 723 724 if (BindingContextUtilPackage.isUsedAsStatement((JetExpression) element, trace.getBindingContext()) 725 && PseudocodePackage.getSideEffectFree(instruction)) { 726 VariableContext ctxt = new VariableContext(instruction, reportedDiagnosticMap); 727 report( 728 element instanceof JetFunctionLiteralExpression 729 ? Errors.UNUSED_FUNCTION_LITERAL.on((JetFunctionLiteralExpression) element) 730 : Errors.UNUSED_EXPRESSION.on(element), 731 ctxt 732 ); 733 } 734 } 735 } 736 ); 737 } 738 739 //////////////////////////////////////////////////////////////////////////////// 740 // Statements 741 742 public void markStatements() { 743 PseudocodeTraverserPackage.traverse( 744 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() { 745 @Override 746 public void execute(@NotNull Instruction instruction) { 747 PseudoValue value = instruction instanceof InstructionWithValue 748 ? ((InstructionWithValue) instruction).getOutputValue() 749 : null; 750 Pseudocode pseudocode = instruction.getOwner(); 751 boolean isUsedAsExpression = !pseudocode.getUsages(value).isEmpty(); 752 for (JetElement element : pseudocode.getValueElements(value)) { 753 trace.record(BindingContext.USED_AS_EXPRESSION, element, isUsedAsExpression); 754 } 755 } 756 } 757 ); 758 } 759 760 public void markWhenWithoutElse() { 761 PseudocodeTraverserPackage.traverse( 762 pseudocode, FORWARD, new JetFlowInformationProvider.FunctionVoid1<Instruction>() { 763 @Override 764 public void execute(@NotNull Instruction instruction) { 765 PseudoValue value = instruction instanceof InstructionWithValue 766 ? ((InstructionWithValue) instruction).getOutputValue() 767 : null; 768 for (JetElement element : instruction.getOwner().getValueElements(value)) { 769 if (!(element instanceof JetWhenExpression)) continue; 770 JetWhenExpression whenExpression = (JetWhenExpression) element; 771 if (whenExpression.getElseExpression() != null) continue; 772 773 if (WhenChecker.mustHaveElse(whenExpression, trace)) { 774 trace.report(NO_ELSE_IN_WHEN.on(whenExpression)); 775 } 776 else if (whenExpression.getSubjectExpression() != null) { 777 ClassDescriptor enumClassDescriptor = WhenChecker.getClassDescriptorOfTypeIfEnum( 778 trace.getType(whenExpression.getSubjectExpression())); 779 if (enumClassDescriptor != null 780 && !WhenChecker.isWhenOnEnumExhaustive(whenExpression, trace, enumClassDescriptor)) { 781 trace.report(NON_EXHAUSTIVE_WHEN.on(whenExpression)); 782 } 783 } 784 } 785 } 786 } 787 ); 788 } 789 790 //////////////////////////////////////////////////////////////////////////////// 791 // Tail calls 792 793 public void markTailCalls() { 794 final DeclarationDescriptor subroutineDescriptor = trace.get(BindingContext.DECLARATION_TO_DESCRIPTOR, subroutine); 795 if (!(subroutineDescriptor instanceof FunctionDescriptor)) return; 796 if (!KotlinBuiltIns.isTailRecursive(subroutineDescriptor)) return; 797 798 // finally blocks are copied which leads to multiple diagnostics reported on one instruction 799 class KindAndCall { 800 TailRecursionKind kind; 801 ResolvedCall<?> call; 802 803 KindAndCall(TailRecursionKind kind, ResolvedCall<?> call) { 804 this.kind = kind; 805 this.call = call; 806 } 807 } 808 final Map<JetElement, KindAndCall> calls = new HashMap<JetElement, KindAndCall>(); 809 PseudocodeTraverserPackage.traverse( 810 pseudocode, 811 FORWARD, 812 new FunctionVoid1<Instruction>() { 813 public void execute(@NotNull Instruction instruction) { 814 if (!(instruction instanceof CallInstruction)) return; 815 CallInstruction callInstruction = (CallInstruction) instruction; 816 817 ResolvedCall<?> resolvedCall = getResolvedCall(callInstruction.getElement(), trace.getBindingContext()); 818 if (resolvedCall == null) return; 819 820 // is this a recursive call? 821 CallableDescriptor functionDescriptor = resolvedCall.getResultingDescriptor(); 822 if (!functionDescriptor.getOriginal().equals(subroutineDescriptor)) return; 823 824 JetElement element = callInstruction.getElement(); 825 //noinspection unchecked 826 JetExpression parent = PsiTreeUtil.getParentOfType( 827 element, 828 JetTryExpression.class, JetFunction.class, JetClassInitializer.class 829 ); 830 831 if (parent instanceof JetTryExpression) { 832 // We do not support tail calls Collections.singletonMap() try-catch-finally, for simplicity of the mental model 833 // very few cases there would be real tail-calls, and it's often not so easy for the user to see why 834 calls.put(element, new KindAndCall(IN_TRY, resolvedCall)); 835 return; 836 } 837 838 boolean isTail = PseudocodeTraverserPackage.traverseFollowingInstructions( 839 callInstruction, 840 new HashSet<Instruction>(), 841 FORWARD, 842 new TailRecursionDetector(subroutine, callInstruction) 843 ); 844 845 // A tail call is not allowed to change dispatch receiver 846 // class C { 847 // fun foo(other: C) { 848 // other.foo(this) // not a tail call 849 // } 850 // } 851 boolean sameDispatchReceiver = 852 ResolvedCallUtilPackage.hasThisOrNoDispatchReceiver(resolvedCall, trace.getBindingContext()); 853 854 TailRecursionKind kind = isTail && sameDispatchReceiver ? TAIL_CALL : NON_TAIL; 855 856 KindAndCall kindAndCall = calls.get(element); 857 calls.put(element, 858 new KindAndCall( 859 combineKinds(kind, kindAndCall == null ? null : kindAndCall.kind), 860 resolvedCall 861 ) 862 ); 863 } 864 } 865 ); 866 boolean hasTailCalls = false; 867 for (Map.Entry<JetElement, KindAndCall> entry : calls.entrySet()) { 868 JetElement element = entry.getKey(); 869 KindAndCall kindAndCall = entry.getValue(); 870 switch (kindAndCall.kind) { 871 case TAIL_CALL: 872 trace.record(TAIL_RECURSION_CALL, kindAndCall.call, TailRecursionKind.TAIL_CALL); 873 hasTailCalls = true; 874 break; 875 case IN_TRY: 876 trace.report(Errors.TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED.on(element)); 877 break; 878 case NON_TAIL: 879 trace.report(Errors.NON_TAIL_RECURSIVE_CALL.on(element)); 880 break; 881 } 882 } 883 884 if (!hasTailCalls) { 885 trace.report(Errors.NO_TAIL_CALLS_FOUND.on((JetNamedFunction) subroutine)); 886 } 887 } 888 889 private static TailRecursionKind combineKinds(TailRecursionKind kind, @Nullable TailRecursionKind existingKind) { 890 TailRecursionKind resultingKind; 891 if (existingKind == null || existingKind == kind) { 892 resultingKind = kind; 893 } 894 else { 895 if (check(kind, existingKind, IN_TRY, TAIL_CALL)) { 896 resultingKind = IN_TRY; 897 } 898 else if (check(kind, existingKind, IN_TRY, NON_TAIL)) { 899 resultingKind = IN_TRY; 900 } 901 else { 902 // TAIL_CALL, NON_TAIL 903 resultingKind = NON_TAIL; 904 } 905 } 906 return resultingKind; 907 } 908 909 private static boolean check(Object a, Object b, Object x, Object y) { 910 return (a == x && b == y) || (a == y && b == x); 911 } 912 913 //////////////////////////////////////////////////////////////////////////////// 914 // Utility classes and methods 915 916 /** 917 * The method provides reporting of the same diagnostic only once for copied instructions 918 * (depends on whether it should be reported for all or only for one of the copies) 919 */ 920 private void report( 921 @NotNull Diagnostic diagnostic, 922 @NotNull VariableContext ctxt 923 ) { 924 Instruction instruction = ctxt.instruction; 925 if (instruction.getCopies().isEmpty()) { 926 trace.report(diagnostic); 927 return; 928 } 929 Map<Instruction, DiagnosticFactory<?>> previouslyReported = ctxt.reportedDiagnosticMap; 930 previouslyReported.put(instruction, diagnostic.getFactory()); 931 932 boolean alreadyReported = false; 933 boolean sameErrorForAllCopies = true; 934 for (Instruction copy : instruction.getCopies()) { 935 DiagnosticFactory<?> previouslyReportedErrorFactory = previouslyReported.get(copy); 936 if (previouslyReportedErrorFactory != null) { 937 alreadyReported = true; 938 } 939 940 if (previouslyReportedErrorFactory != diagnostic.getFactory()) { 941 sameErrorForAllCopies = false; 942 } 943 } 944 945 if (mustBeReportedOnAllCopies(diagnostic.getFactory())) { 946 if (sameErrorForAllCopies) { 947 trace.report(diagnostic); 948 } 949 } 950 else { 951 //only one reporting required 952 if (!alreadyReported) { 953 trace.report(diagnostic); 954 } 955 } 956 } 957 958 private static boolean mustBeReportedOnAllCopies(@NotNull DiagnosticFactory<?> diagnosticFactory) { 959 return diagnosticFactory == UNUSED_VARIABLE 960 || diagnosticFactory == UNUSED_PARAMETER 961 || diagnosticFactory == UNUSED_CHANGED_VALUE; 962 } 963 964 965 private class VariableContext { 966 final Map<Instruction, DiagnosticFactory<?>> reportedDiagnosticMap; 967 final Instruction instruction; 968 final VariableDescriptor variableDescriptor; 969 970 private VariableContext( 971 @NotNull Instruction instruction, 972 @NotNull Map<Instruction, DiagnosticFactory<?>> map 973 ) { 974 this.instruction = instruction; 975 reportedDiagnosticMap = map; 976 variableDescriptor = PseudocodeUtil.extractVariableDescriptorIfAny(instruction, true, trace.getBindingContext()); 977 } 978 } 979 980 private class VariableInitContext extends VariableContext { 981 final VariableControlFlowState enterInitState; 982 final VariableControlFlowState exitInitState; 983 984 private VariableInitContext( 985 @NotNull Instruction instruction, 986 @NotNull Map<Instruction, DiagnosticFactory<?>> map, 987 @NotNull Map<VariableDescriptor, VariableControlFlowState> in, 988 @NotNull Map<VariableDescriptor, VariableControlFlowState> out, 989 @NotNull LexicalScopeVariableInfo lexicalScopeVariableInfo 990 ) { 991 super(instruction, map); 992 enterInitState = initialize(variableDescriptor, lexicalScopeVariableInfo, in); 993 exitInitState = initialize(variableDescriptor, lexicalScopeVariableInfo, out); 994 } 995 996 private VariableControlFlowState initialize( 997 VariableDescriptor variableDescriptor, 998 LexicalScopeVariableInfo lexicalScopeVariableInfo, 999 Map<VariableDescriptor, VariableControlFlowState> map 1000 ) { 1001 if (variableDescriptor == null) return null; 1002 VariableControlFlowState state = map.get(variableDescriptor); 1003 if (state != null) return state; 1004 return PseudocodeVariablesData.getDefaultValueForInitializers(variableDescriptor, instruction, lexicalScopeVariableInfo); 1005 } 1006 } 1007 1008 private class VariableUseContext extends VariableContext { 1009 final VariableUseState enterUseState; 1010 final VariableUseState exitUseState; 1011 1012 1013 private VariableUseContext( 1014 @NotNull Instruction instruction, 1015 @NotNull Map<Instruction, DiagnosticFactory<?>> map, 1016 @NotNull Map<VariableDescriptor, VariableUseState> in, 1017 @NotNull Map<VariableDescriptor, VariableUseState> out 1018 ) { 1019 super(instruction, map); 1020 enterUseState = variableDescriptor != null ? in.get(variableDescriptor) : null; 1021 exitUseState = variableDescriptor != null ? out.get(variableDescriptor) : null; 1022 } 1023 } 1024 1025 //TODO after KT-4621 rewrite to Kotlin 1026 public abstract static class InstructionDataAnalyzeStrategy<D> implements Function3<Instruction, D, D, Unit> { 1027 @Override 1028 public Unit invoke(Instruction instruction, D enterData, D exitData) { 1029 execute(instruction, enterData, exitData); 1030 return Unit.INSTANCE$; 1031 } 1032 1033 public abstract void execute(Instruction instruction, D enterData, D exitData); 1034 } 1035 1036 public abstract static class FunctionVoid1<P> implements Function1<P, Unit> { 1037 @Override 1038 public Unit invoke(P p) { 1039 execute(p); 1040 return Unit.INSTANCE$; 1041 } 1042 1043 public abstract void execute(P p); 1044 } 1045 }