001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2025 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018/////////////////////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.metrics; 021 022import java.math.BigInteger; 023import java.util.ArrayDeque; 024import java.util.Deque; 025 026import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 027import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 028import com.puppycrawl.tools.checkstyle.api.DetailAST; 029import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 031 032/** 033 * <div> 034 * Checks the NPATH complexity against a specified limit. 035 * </div> 036 * 037 * <p> 038 * The NPATH metric computes the number of possible execution paths through a 039 * function(method). It takes into account the nesting of conditional statements 040 * and multipart boolean expressions (A && B, C || D, E ? F :G and 041 * their combinations). 042 * </p> 043 * 044 * <p> 045 * The NPATH metric was designed base on Cyclomatic complexity to avoid problem 046 * of Cyclomatic complexity metric like nesting level within a function(method). 047 * </p> 048 * 049 * <p> 050 * Metric was described at <a href="http://dl.acm.org/citation.cfm?id=42379"> 051 * "NPATH: a measure of execution pathcomplexity and its applications"</a>. 052 * If you need detailed description of algorithm, please read that article, 053 * it is well written and have number of examples and details. 054 * </p> 055 * 056 * <p> 057 * Here is some quotes: 058 * </p> 059 * <blockquote> 060 * An NPATH threshold value of 200 has been established for a function. 061 * The value 200 is based on studies done at AT&T Bell Laboratories [1988 year]. 062 * </blockquote> 063 * <blockquote> 064 * Some of the most effective methods of reducing the NPATH value include: 065 * <ul> 066 * <li> 067 * distributing functionality; 068 * </li> 069 * <li> 070 * implementing multiple if statements as a switch statement; 071 * </li> 072 * <li> 073 * creating a separate function for logical expressions with a high count of 074 * variables and (&&) and or (||) operators. 075 * </li> 076 * </ul> 077 * </blockquote> 078 * <blockquote> 079 * Although strategies to reduce the NPATH complexity of functions are important, 080 * care must be taken not to distort the logical clarity of the software by 081 * applying a strategy to reduce the complexity of functions. That is, there is 082 * a point of diminishing return beyond which a further attempt at reduction of 083 * complexity distorts the logical clarity of the system structure. 084 * </blockquote> 085 * <div class="wrapper"> 086 * <table> 087 * <caption>Examples</caption> 088 * <thead><tr><th>Structure</th><th>Complexity expression</th></tr></thead> 089 * <tr><td>if ([expr]) { [if-range] }</td><td>NP(if-range) + 1 + NP(expr)</td></tr> 090 * <tr><td>if ([expr]) { [if-range] } else { [else-range] }</td> 091 * <td>NP(if-range)+ NP(else-range) + NP(expr)</td></tr> 092 * <tr><td>while ([expr]) { [while-range] }</td><td>NP(while-range) + NP(expr) + 1</td></tr> 093 * <tr><td>do { [do-range] } while ([expr])</td><td>NP(do-range) + NP(expr) + 1</td></tr> 094 * <tr><td>for([expr1]; [expr2]; [expr3]) { [for-range] }</td> 095 * <td>NP(for-range) + NP(expr1)+ NP(expr2) + NP(expr3) + 1</td></tr> 096 * <tr><td>switch ([expr]) { case : [case-range] default: [default-range] }</td> 097 * <td>S(i=1:i=n)NP(case-range[i]) + NP(default-range) + NP(expr)</td></tr> 098 * <tr><td>when[expr]</td><td>NP(expr) + 1</td></tr> 099 * <tr><td>[expr1] ? [expr2] : [expr3]</td><td>NP(expr1) + NP(expr2) + NP(expr3) + 2</td></tr> 100 * <tr><td>goto label</td><td>1</td></tr><tr><td>break</td><td>1</td></tr> 101 * <tr><td>Expressions</td> 102 * <td>Number of && and || operators in expression. No operators - 0</td></tr> 103 * <tr><td>continue</td><td>1</td></tr><tr><td>return</td><td>1</td></tr> 104 * <tr><td>Statement (even sequential statements)</td><td>1</td></tr> 105 * <tr><td>Empty block {}</td><td>1</td></tr><tr><td>Function call</td><td>1</td> 106 * </tr><tr><td>Function(Method) declaration or Block</td><td>P(i=1:i=N)NP(Statement[i])</td></tr> 107 * </table> 108 * </div> 109 * 110 * <p> 111 * <b>Rationale:</b> Nejmeh says that his group had an informal NPATH limit of 112 * 200 on individual routines; functions(methods) that exceeded this value were 113 * candidates for further decomposition - or at least a closer look. 114 * <b>Please do not be fanatic with limit 200</b> - choose number that suites 115 * your project style. Limit 200 is empirical number base on some sources of at 116 * AT&T Bell Laboratories of 1988 year. 117 * </p> 118 * <ul> 119 * <li> 120 * Property {@code max} - Specify the maximum threshold allowed. 121 * Type is {@code int}. 122 * Default value is {@code 200}. 123 * </li> 124 * </ul> 125 * 126 * <p> 127 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 128 * </p> 129 * 130 * <p> 131 * Violation Message Keys: 132 * </p> 133 * <ul> 134 * <li> 135 * {@code npathComplexity} 136 * </li> 137 * </ul> 138 * 139 * @since 3.4 140 */ 141// -@cs[AbbreviationAsWordInName] Can't change check name 142@FileStatefulCheck 143public final class NPathComplexityCheck extends AbstractCheck { 144 145 /** 146 * A key is pointing to the warning message text in "messages.properties" 147 * file. 148 */ 149 public static final String MSG_KEY = "npathComplexity"; 150 151 /** Tokens that are considered as case labels. */ 152 private static final int[] CASE_LABEL_TOKENS = { 153 TokenTypes.EXPR, 154 TokenTypes.PATTERN_DEF, 155 TokenTypes.PATTERN_VARIABLE_DEF, 156 TokenTypes.RECORD_PATTERN_DEF, 157 }; 158 159 /** Default allowed complexity. */ 160 private static final int DEFAULT_MAX = 200; 161 162 /** The initial current value. */ 163 private static final BigInteger INITIAL_VALUE = BigInteger.ZERO; 164 165 /** 166 * Stack of NP values for ranges. 167 */ 168 private final Deque<BigInteger> rangeValues = new ArrayDeque<>(); 169 170 /** Stack of NP values for expressions. */ 171 private final Deque<Integer> expressionValues = new ArrayDeque<>(); 172 173 /** Stack of belongs to range values for question operator. */ 174 private final Deque<Boolean> afterValues = new ArrayDeque<>(); 175 176 /** 177 * Range of the last processed expression. Used for checking that ternary operation 178 * which is a part of expression won't be processed for second time. 179 */ 180 private final TokenEnd processingTokenEnd = new TokenEnd(); 181 182 /** NP value for current range. */ 183 private BigInteger currentRangeValue; 184 185 /** Specify the maximum threshold allowed. */ 186 private int max = DEFAULT_MAX; 187 188 /** True, when branch is visited, but not leaved. */ 189 private boolean branchVisited; 190 191 /** 192 * Setter to specify the maximum threshold allowed. 193 * 194 * @param max the maximum threshold 195 * @since 3.4 196 */ 197 public void setMax(int max) { 198 this.max = max; 199 } 200 201 @Override 202 public int[] getDefaultTokens() { 203 return getRequiredTokens(); 204 } 205 206 @Override 207 public int[] getAcceptableTokens() { 208 return getRequiredTokens(); 209 } 210 211 @Override 212 public int[] getRequiredTokens() { 213 return new int[] { 214 TokenTypes.CTOR_DEF, 215 TokenTypes.METHOD_DEF, 216 TokenTypes.STATIC_INIT, 217 TokenTypes.INSTANCE_INIT, 218 TokenTypes.LITERAL_WHILE, 219 TokenTypes.LITERAL_DO, 220 TokenTypes.LITERAL_FOR, 221 TokenTypes.LITERAL_IF, 222 TokenTypes.LITERAL_ELSE, 223 TokenTypes.LITERAL_SWITCH, 224 TokenTypes.CASE_GROUP, 225 TokenTypes.LITERAL_TRY, 226 TokenTypes.LITERAL_CATCH, 227 TokenTypes.QUESTION, 228 TokenTypes.LITERAL_RETURN, 229 TokenTypes.LITERAL_DEFAULT, 230 TokenTypes.COMPACT_CTOR_DEF, 231 TokenTypes.SWITCH_RULE, 232 TokenTypes.LITERAL_WHEN, 233 }; 234 } 235 236 @Override 237 public void beginTree(DetailAST rootAST) { 238 rangeValues.clear(); 239 expressionValues.clear(); 240 afterValues.clear(); 241 processingTokenEnd.reset(); 242 currentRangeValue = INITIAL_VALUE; 243 branchVisited = false; 244 } 245 246 @Override 247 public void visitToken(DetailAST ast) { 248 switch (ast.getType()) { 249 case TokenTypes.LITERAL_IF, TokenTypes.LITERAL_SWITCH, 250 TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_DO, 251 TokenTypes.LITERAL_FOR -> visitConditional(ast, 1); 252 253 case TokenTypes.QUESTION -> visitUnitaryOperator(ast, 2); 254 255 case TokenTypes.LITERAL_RETURN -> visitUnitaryOperator(ast, 0); 256 257 case TokenTypes.LITERAL_WHEN -> visitWhenExpression(ast, 1); 258 259 case TokenTypes.CASE_GROUP -> { 260 final int caseNumber = countCaseTokens(ast); 261 branchVisited = true; 262 pushValue(caseNumber); 263 } 264 265 case TokenTypes.SWITCH_RULE -> { 266 final int caseConstantNumber = countCaseConstants(ast); 267 branchVisited = true; 268 pushValue(caseConstantNumber); 269 } 270 271 case TokenTypes.LITERAL_ELSE -> { 272 branchVisited = true; 273 if (currentRangeValue.equals(BigInteger.ZERO)) { 274 currentRangeValue = BigInteger.ONE; 275 } 276 pushValue(0); 277 } 278 279 case TokenTypes.LITERAL_TRY, 280 TokenTypes.LITERAL_CATCH, 281 TokenTypes.LITERAL_DEFAULT -> pushValue(1); 282 283 case TokenTypes.CTOR_DEF, 284 TokenTypes.METHOD_DEF, 285 TokenTypes.INSTANCE_INIT, 286 TokenTypes.STATIC_INIT, 287 TokenTypes.COMPACT_CTOR_DEF -> pushValue(0); 288 289 default -> { 290 // do nothing 291 } 292 } 293 } 294 295 @Override 296 public void leaveToken(DetailAST ast) { 297 switch (ast.getType()) { 298 case TokenTypes.LITERAL_WHILE, 299 TokenTypes.LITERAL_DO, 300 TokenTypes.LITERAL_FOR, 301 TokenTypes.LITERAL_IF, 302 TokenTypes.LITERAL_SWITCH, 303 TokenTypes.LITERAL_WHEN -> leaveConditional(); 304 305 case TokenTypes.LITERAL_TRY -> leaveMultiplyingConditional(); 306 307 case TokenTypes.LITERAL_RETURN, 308 TokenTypes.QUESTION -> leaveUnitaryOperator(); 309 310 case TokenTypes.LITERAL_CATCH -> leaveAddingConditional(); 311 312 case TokenTypes.LITERAL_DEFAULT -> leaveBranch(); 313 314 case TokenTypes.LITERAL_ELSE, 315 TokenTypes.CASE_GROUP, 316 TokenTypes.SWITCH_RULE -> { 317 leaveBranch(); 318 branchVisited = false; 319 } 320 321 case TokenTypes.CTOR_DEF, 322 TokenTypes.METHOD_DEF, 323 TokenTypes.INSTANCE_INIT, 324 TokenTypes.STATIC_INIT, 325 TokenTypes.COMPACT_CTOR_DEF -> leaveMethodDef(ast); 326 327 default -> { 328 // do nothing 329 } 330 } 331 } 332 333 /** 334 * Visits if, while, do-while, for and switch tokens - all of them have expression in 335 * parentheses which is used for calculation. 336 * 337 * @param ast visited token. 338 * @param basicBranchingFactor default number of branches added. 339 */ 340 private void visitConditional(DetailAST ast, int basicBranchingFactor) { 341 int expressionValue = basicBranchingFactor; 342 DetailAST bracketed; 343 for (bracketed = ast.findFirstToken(TokenTypes.LPAREN); 344 bracketed.getType() != TokenTypes.RPAREN; 345 bracketed = bracketed.getNextSibling()) { 346 expressionValue += countConditionalOperators(bracketed); 347 } 348 processingTokenEnd.setToken(bracketed); 349 pushValue(expressionValue); 350 } 351 352 /** 353 * Visits when expression token. There is no guarantee that when expression will be 354 * bracketed, so we don't use visitConditional method. 355 * 356 * @param ast visited token. 357 * @param basicBranchingFactor default number of branches added. 358 */ 359 private void visitWhenExpression(DetailAST ast, int basicBranchingFactor) { 360 final int expressionValue = basicBranchingFactor + countConditionalOperators(ast); 361 processingTokenEnd.setToken(getLastToken(ast)); 362 pushValue(expressionValue); 363 } 364 365 /** 366 * Visits ternary operator (?:) and return tokens. They differ from those processed by 367 * visitConditional method in that their expression isn't bracketed. 368 * 369 * @param ast visited token. 370 * @param basicBranchingFactor number of branches inherently added by this token. 371 */ 372 private void visitUnitaryOperator(DetailAST ast, int basicBranchingFactor) { 373 final boolean isAfter = processingTokenEnd.isAfter(ast); 374 afterValues.push(isAfter); 375 if (!isAfter) { 376 processingTokenEnd.setToken(getLastToken(ast)); 377 final int expressionValue = basicBranchingFactor + countConditionalOperators(ast); 378 pushValue(expressionValue); 379 } 380 } 381 382 /** 383 * Leaves ternary operator (?:) and return tokens. 384 */ 385 private void leaveUnitaryOperator() { 386 if (Boolean.FALSE.equals(afterValues.pop())) { 387 final Values valuePair = popValue(); 388 BigInteger basicRangeValue = valuePair.getRangeValue(); 389 BigInteger expressionValue = valuePair.getExpressionValue(); 390 if (expressionValue.equals(BigInteger.ZERO)) { 391 expressionValue = BigInteger.ONE; 392 } 393 if (basicRangeValue.equals(BigInteger.ZERO)) { 394 basicRangeValue = BigInteger.ONE; 395 } 396 currentRangeValue = currentRangeValue.add(expressionValue).multiply(basicRangeValue); 397 } 398 } 399 400 /** Leaves while, do, for, if, ternary (?::), return or switch. */ 401 private void leaveConditional() { 402 final Values valuePair = popValue(); 403 final BigInteger expressionValue = valuePair.getExpressionValue(); 404 BigInteger basicRangeValue = valuePair.getRangeValue(); 405 if (currentRangeValue.equals(BigInteger.ZERO)) { 406 currentRangeValue = BigInteger.ONE; 407 } 408 if (basicRangeValue.equals(BigInteger.ZERO)) { 409 basicRangeValue = BigInteger.ONE; 410 } 411 currentRangeValue = currentRangeValue.add(expressionValue).multiply(basicRangeValue); 412 } 413 414 /** Leaves else, default or case group tokens. */ 415 private void leaveBranch() { 416 final Values valuePair = popValue(); 417 final BigInteger basicRangeValue = valuePair.getRangeValue(); 418 final BigInteger expressionValue = valuePair.getExpressionValue(); 419 if (branchVisited && currentRangeValue.equals(BigInteger.ZERO)) { 420 currentRangeValue = BigInteger.ONE; 421 } 422 currentRangeValue = currentRangeValue.subtract(BigInteger.ONE) 423 .add(basicRangeValue) 424 .add(expressionValue); 425 } 426 427 /** 428 * Process the end of a method definition. 429 * 430 * @param ast the token type representing the method definition 431 */ 432 private void leaveMethodDef(DetailAST ast) { 433 final BigInteger bigIntegerMax = BigInteger.valueOf(max); 434 if (currentRangeValue.compareTo(bigIntegerMax) > 0) { 435 log(ast, MSG_KEY, currentRangeValue, bigIntegerMax); 436 } 437 popValue(); 438 currentRangeValue = INITIAL_VALUE; 439 } 440 441 /** Leaves catch. */ 442 private void leaveAddingConditional() { 443 currentRangeValue = currentRangeValue.add(popValue().getRangeValue().add(BigInteger.ONE)); 444 } 445 446 /** 447 * Pushes the current range value on the range value stack. Pushes this token expression value 448 * on the expression value stack. 449 * 450 * @param expressionValue value of expression calculated for current token. 451 */ 452 private void pushValue(Integer expressionValue) { 453 rangeValues.push(currentRangeValue); 454 expressionValues.push(expressionValue); 455 currentRangeValue = INITIAL_VALUE; 456 } 457 458 /** 459 * Pops values from both stack of expression values and stack of range values. 460 * 461 * @return pair of head values from both of the stacks. 462 */ 463 private Values popValue() { 464 final int expressionValue = expressionValues.pop(); 465 return new Values(rangeValues.pop(), BigInteger.valueOf(expressionValue)); 466 } 467 468 /** Leaves try. */ 469 private void leaveMultiplyingConditional() { 470 currentRangeValue = currentRangeValue.add(BigInteger.ONE) 471 .multiply(popValue().getRangeValue().add(BigInteger.ONE)); 472 } 473 474 /** 475 * Calculates number of conditional operators, including inline ternary operator, for a token. 476 * 477 * @param ast inspected token. 478 * @return number of conditional operators. 479 * @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.23"> 480 * Java Language Specification, §15.23</a> 481 * @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24"> 482 * Java Language Specification, §15.24</a> 483 * @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25"> 484 * Java Language Specification, §15.25</a> 485 */ 486 private static int countConditionalOperators(DetailAST ast) { 487 int number = 0; 488 for (DetailAST child = ast.getFirstChild(); child != null; 489 child = child.getNextSibling()) { 490 final int type = child.getType(); 491 if (type == TokenTypes.LOR || type == TokenTypes.LAND) { 492 number++; 493 } 494 else if (type == TokenTypes.QUESTION) { 495 number += 2; 496 } 497 number += countConditionalOperators(child); 498 } 499 return number; 500 } 501 502 /** 503 * Finds a leaf, which is the most distant from the root. 504 * 505 * @param ast the root of tree. 506 * @return the leaf. 507 */ 508 private static DetailAST getLastToken(DetailAST ast) { 509 final DetailAST lastChild = ast.getLastChild(); 510 final DetailAST result; 511 if (lastChild.getFirstChild() == null) { 512 result = lastChild; 513 } 514 else { 515 result = getLastToken(lastChild); 516 } 517 return result; 518 } 519 520 /** 521 * Counts number of case tokens subject to a case group token. 522 * 523 * @param ast case group token. 524 * @return number of case tokens. 525 */ 526 private static int countCaseTokens(DetailAST ast) { 527 int counter = 0; 528 for (DetailAST iterator = ast.getFirstChild(); iterator != null; 529 iterator = iterator.getNextSibling()) { 530 if (iterator.getType() == TokenTypes.LITERAL_CASE) { 531 counter++; 532 } 533 } 534 return counter; 535 } 536 537 /** 538 * Counts number of case constants tokens in a switch labeled rule. 539 * 540 * @param ast switch rule token. 541 * @return number of case constant tokens. 542 */ 543 private static int countCaseConstants(DetailAST ast) { 544 int counter = 0; 545 final DetailAST literalCase = ast.getFirstChild(); 546 547 for (DetailAST node = literalCase.getFirstChild(); node != null; 548 node = node.getNextSibling()) { 549 if (TokenUtil.isOfType(node, CASE_LABEL_TOKENS)) { 550 counter++; 551 } 552 } 553 554 return counter; 555 } 556 557 /** 558 * Coordinates of token end. Used to prevent inline ternary 559 * operator from being processed twice. 560 */ 561 private static final class TokenEnd { 562 563 /** End line of token. */ 564 private int endLineNo; 565 566 /** End column of token. */ 567 private int endColumnNo; 568 569 /** 570 * Sets end coordinates from given token. 571 * 572 * @param endToken token. 573 */ 574 public void setToken(DetailAST endToken) { 575 if (!isAfter(endToken)) { 576 endLineNo = endToken.getLineNo(); 577 endColumnNo = endToken.getColumnNo(); 578 } 579 } 580 581 /** Sets end token coordinates to the start of the file. */ 582 public void reset() { 583 endLineNo = 0; 584 endColumnNo = 0; 585 } 586 587 /** 588 * Checks if saved coordinates located after given token. 589 * 590 * @param ast given token. 591 * @return true, if saved coordinates located after given token. 592 */ 593 public boolean isAfter(DetailAST ast) { 594 final int lineNo = ast.getLineNo(); 595 final int columnNo = ast.getColumnNo(); 596 return lineNo <= endLineNo 597 && (lineNo != endLineNo 598 || columnNo <= endColumnNo); 599 } 600 601 } 602 603 /** 604 * Class that store range value and expression value. 605 */ 606 private static final class Values { 607 608 /** NP value for range. */ 609 private final BigInteger rangeValue; 610 611 /** NP value for expression. */ 612 private final BigInteger expressionValue; 613 614 /** 615 * Constructor that assigns all of class fields. 616 * 617 * @param valueOfRange NP value for range 618 * @param valueOfExpression NP value for expression 619 */ 620 private Values(BigInteger valueOfRange, BigInteger valueOfExpression) { 621 rangeValue = valueOfRange; 622 expressionValue = valueOfExpression; 623 } 624 625 /** 626 * Returns NP value for range. 627 * 628 * @return NP value for range 629 */ 630 public BigInteger getRangeValue() { 631 return rangeValue; 632 } 633 634 /** 635 * Returns NP value for expression. 636 * 637 * @return NP value for expression 638 */ 639 public BigInteger getExpressionValue() { 640 return expressionValue; 641 } 642 643 } 644 645}