001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 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.indentation; 021 022import java.util.Arrays; 023 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.api.TokenTypes; 026import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; 027import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 028import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 029 030/** 031 * Abstract base class for all handlers. 032 * 033 */ 034public abstract class AbstractExpressionHandler { 035 036 /** 037 * The indentation context providing config values, source lines, and 038 * violation reporting without a direct reference to the check. 039 */ 040 private final IndentationContext context; 041 042 /** The AST which is handled by this handler. */ 043 private final DetailAST mainAst; 044 045 /** Name used during output to user. */ 046 private final String typeName; 047 048 /** Containing AST handler. */ 049 private final AbstractExpressionHandler parent; 050 051 /** Indentation amount for this handler. */ 052 private IndentLevel indent; 053 054 /** 055 * Construct an instance of this handler with the given indentation context, 056 * name, abstract syntax tree, and parent handler. 057 * 058 * @param context the indentation context 059 * @param typeName the name of the handler 060 * @param expr the abstract syntax tree 061 * @param parent the parent handler 062 */ 063 protected AbstractExpressionHandler(IndentationContext context, String typeName, 064 DetailAST expr, AbstractExpressionHandler parent) { 065 this.context = context; 066 this.typeName = typeName; 067 mainAst = expr; 068 this.parent = parent; 069 } 070 071 /** 072 * Check the indentation of the expression we are handling. 073 */ 074 public abstract void checkIndentation(); 075 076 /** 077 * Get the indentation amount for this handler. For performance reasons, 078 * this value is cached. The first time this method is called, the 079 * indentation amount is computed and stored. On further calls, the stored value is returned. 080 * 081 * @return the expected indentation amount 082 * @noinspection WeakerAccess 083 * @noinspectionreason WeakerAccess - we avoid 'protected' when possible 084 */ 085 public final IndentLevel getIndent() { 086 if (indent == null) { 087 indent = getIndentImpl(); 088 } 089 return indent; 090 } 091 092 /** 093 * Compute the indentation amount for this handler. 094 * 095 * @return the expected indentation amount 096 */ 097 protected IndentLevel getIndentImpl() { 098 return parent.getSuggestedChildIndent(this); 099 } 100 101 /** 102 * Indentation level suggested for a child element. Children don't have 103 * to respect this, but most do. 104 * 105 * @param child child AST (so suggestion level can differ based on child type) 106 * 107 * @return suggested indentation for child 108 * @noinspection WeakerAccess 109 * @noinspectionreason WeakerAccess - we avoid 'protected' when possible 110 */ 111 public IndentLevel getSuggestedChildIndent(AbstractExpressionHandler child) { 112 return new IndentLevel(getIndent(), getBasicOffset()); 113 } 114 115 /** 116 * Log an indentation error. 117 * 118 * @param ast the expression that caused the error 119 * @param subtypeName the type of the expression 120 * @param actualIndent the actual indent level of the expression 121 */ 122 protected final void logError(DetailAST ast, String subtypeName, 123 int actualIndent) { 124 logError(ast, subtypeName, actualIndent, getIndent()); 125 } 126 127 /** 128 * Log an indentation error. 129 * 130 * @param ast the expression that caused the error 131 * @param subtypeName the type of the expression 132 * @param actualIndent the actual indent level of the expression 133 * @param expectedIndent the expected indent level of the expression 134 */ 135 protected final void logError(DetailAST ast, String subtypeName, 136 int actualIndent, IndentLevel expectedIndent) { 137 final String typeStr; 138 139 if (subtypeName.isEmpty()) { 140 typeStr = ""; 141 } 142 else { 143 typeStr = " " + subtypeName; 144 } 145 String messageKey = IndentationContext.MSG_ERROR; 146 if (expectedIndent.isMultiLevel()) { 147 messageKey = IndentationContext.MSG_ERROR_MULTI; 148 } 149 context.indentationLog(ast, messageKey, 150 typeName + typeStr, actualIndent, expectedIndent); 151 } 152 153 /** 154 * Log child indentation error. 155 * 156 * @param ast the abstract syntax tree that causes the error 157 * @param actualIndent the actual indent level of the expression 158 * @param expectedIndent the expected indent level of the expression 159 */ 160 protected final void logChildError(DetailAST ast, 161 int actualIndent, 162 IndentLevel expectedIndent) { 163 String messageKey = IndentationContext.MSG_CHILD_ERROR; 164 if (expectedIndent.isMultiLevel()) { 165 messageKey = IndentationContext.MSG_CHILD_ERROR_MULTI; 166 } 167 context.indentationLog(ast, messageKey, 168 typeName, actualIndent, expectedIndent); 169 } 170 171 /** 172 * Determines if the given expression is at the start of a line. 173 * 174 * @param ast the expression to check 175 * 176 * @return true if it is, false otherwise 177 */ 178 protected final boolean isOnStartOfLine(DetailAST ast) { 179 return getLineStart(ast) == expandedTabsColumnNo(ast); 180 } 181 182 /** 183 * Searches in given subtree (including given node) for the token 184 * which represents first symbol for this subtree in file. 185 * 186 * @param ast a root of subtree in which the search should be performed. 187 * @return a token which occurs first in the file. 188 */ 189 /* package */ static DetailAST getFirstToken(DetailAST ast) { 190 DetailAST first = ast; 191 DetailAST child = ast.getFirstChild(); 192 193 while (child != null) { 194 final DetailAST toTest = getFirstToken(child); 195 if (toTest.getColumnNo() < first.getColumnNo()) { 196 first = toTest; 197 } 198 child = child.getNextSibling(); 199 } 200 201 return first; 202 } 203 204 /** 205 * Get the start of the line for the given expression. 206 * 207 * @param ast the expression to find the start of the line for 208 * 209 * @return the start of the line for the given expression 210 */ 211 protected final int getLineStart(DetailAST ast) { 212 return getLineStart(ast.getLineNo()); 213 } 214 215 /** 216 * Get the start of the line for the given line number. 217 * 218 * @param lineNo the line number to find the start for 219 * 220 * @return the start of the line for the given expression 221 */ 222 protected final int getLineStart(int lineNo) { 223 return getLineStart(context.getLine(lineNo - 1)); 224 } 225 226 /** 227 * Get the start of the specified line. 228 * 229 * @param line the specified line number 230 * 231 * @return the start of the specified line 232 */ 233 private int getLineStart(String line) { 234 int index = 0; 235 while (Character.isWhitespace(line.charAt(index))) { 236 index++; 237 } 238 return CommonUtil.lengthExpandedTabs( 239 line, index, context.getIndentationTabWidth()); 240 } 241 242 /** 243 * Checks that indentation should be increased after first line in checkLinesIndent(). 244 * 245 * @return true if indentation should be increased after first line in checkLinesIndent() 246 * false otherwise 247 */ 248 protected boolean shouldIncreaseIndent() { 249 boolean result = true; 250 if (TokenUtil.isOfType(mainAst, TokenTypes.LITERAL_CATCH)) { 251 final DetailAST parameterAst = mainAst.findFirstToken(TokenTypes.PARAMETER_DEF); 252 result = !AnnotationUtil.containsAnnotation(parameterAst); 253 } 254 return result; 255 } 256 257 /** 258 * Check the indentation for a set of lines. 259 * 260 * @param astSet the set of abstract syntax tree to check 261 * @param indentLevel the indentation level 262 * @param firstLineMatches whether or not the first line has to match 263 * @param firstLine first line of whole expression 264 * @param allowNesting whether or not subtree nesting is allowed 265 */ 266 private void checkLinesIndent(DetailAstSet astSet, 267 IndentLevel indentLevel, 268 boolean firstLineMatches, 269 int firstLine, 270 boolean allowNesting) { 271 if (!astSet.isEmpty()) { 272 // check first line 273 final DetailAST startLineAst = astSet.firstLine(); 274 int startCol = expandedTabsColumnNo(startLineAst); 275 276 final int realStartCol = 277 getLineStart(context.getLine(startLineAst.getLineNo() - 1)); 278 279 if (firstLineMatches && !allowNesting) { 280 startCol = realStartCol; 281 } 282 283 if (realStartCol == startCol) { 284 checkLineIndent(startLineAst, indentLevel, 285 firstLineMatches); 286 } 287 288 checkRemainingLines(firstLineMatches, indentLevel, firstLine, astSet); 289 290 } 291 } 292 293 /** 294 * Check the indentation of remaining lines present in the astSet. 295 * 296 * @param firstLineMatches whether or not the first line has to match 297 * @param indentLevel the indentation level 298 * @param firstLine first line of whole expression 299 * @param astSet the set of abstract syntax tree to check 300 */ 301 private void checkRemainingLines(boolean firstLineMatches, 302 IndentLevel indentLevel, 303 int firstLine, 304 DetailAstSet astSet) { 305 // if first line starts the line, following lines are indented 306 // one level; but if the first line of this expression is 307 // nested with the previous expression (which is assumed if it 308 // doesn't start the line) then don't indent more, the first 309 // indentation is absorbed by the nesting 310 final DetailAST startLineAst = astSet.firstLine(); 311 final int endLine = astSet.lastLine(); 312 IndentLevel level = indentLevel; 313 314 if (shouldIncreaseIndent() 315 && startLineAst.getType() != TokenTypes.ANNOTATION 316 && (firstLineMatches || firstLine > mainAst.getLineNo())) { 317 level = new IndentLevel(indentLevel, 318 context.getLineWrappingIndentation()); 319 } 320 321 // check following lines 322 for (int index = startLineAst.getLineNo() + 1; index <= endLine; index++) { 323 final Integer col = astSet.getStartColumn(index); 324 // startCol could be null if this line didn't have an 325 // expression that was required to be checked (it could be 326 // checked by a child expression) 327 328 if (col != null) { 329 final DetailAST ast = astSet.getAst(index); 330 final boolean textBlockEndAligned = 331 ast.getType() == TokenTypes.TEXT_BLOCK_LITERAL_END 332 && isOnStartOfLine(ast.getParent()) 333 && indentLevel.isAcceptable(expandedTabsColumnNo(ast)); 334 if (!textBlockEndAligned) { 335 checkLineIndent(ast, level, false); 336 } 337 } 338 } 339 } 340 341 /** 342 * Check the indentation for a single-line. 343 * 344 * @param ast the abstract syntax tree to check 345 * @param indentLevel the indentation level 346 * @param mustMatch whether or not the indentation level must match 347 */ 348 private void checkLineIndent(DetailAST ast, 349 IndentLevel indentLevel, boolean mustMatch) { 350 final String line = context.getLine(ast.getLineNo() - 1); 351 final int start = getLineStart(line); 352 final int columnNumber = expandedTabsColumnNo(ast); 353 // if must match is set, it is a violation if the line start is not 354 // at the correct indention level; otherwise, it is an only a 355 // violation if this statement starts the line and it is less than 356 // the correct indentation level 357 if (mustMatch && !indentLevel.isAcceptable(start) 358 || !mustMatch && columnNumber == start && indentLevel.isGreaterThan(start)) { 359 logChildError(ast, start, indentLevel); 360 } 361 } 362 363 /** 364 * Checks indentation on wrapped lines between and including 365 * {@code firstNode} and {@code lastNode}. 366 * 367 * @param firstNode First node to start examining. 368 * @param lastNode Last node to examine inclusively. 369 */ 370 protected void checkWrappingIndentation(DetailAST firstNode, DetailAST lastNode) { 371 context.getLineWrappingHandler().checkIndentation(firstNode, lastNode); 372 } 373 374 /** 375 * Checks indentation on wrapped lines between and including 376 * {@code firstNode} and {@code lastNode}. 377 * 378 * @param firstNode First node to start examining. 379 * @param lastNode Last node to examine inclusively. 380 * @param wrappedIndentLevel Indentation all wrapped lines should use. 381 * @param startIndent Indentation first line before wrapped lines used. 382 * @param ignoreFirstLine Test if first line's indentation should be checked or not. 383 */ 384 protected void checkWrappingIndentation(DetailAST firstNode, DetailAST lastNode, 385 int wrappedIndentLevel, int startIndent, 386 LineWrappingHandler.LineWrappingOptions ignoreFirstLine) { 387 context.getLineWrappingHandler().checkIndentation(firstNode, lastNode, 388 wrappedIndentLevel, startIndent, ignoreFirstLine); 389 } 390 391 /** 392 * Check the indent level of the children of the specified parent expression. 393 * 394 * @param parentNode the parent whose children we are checking 395 * @param tokenTypes the token types to check 396 * @param startIndent the starting indent level 397 * @param firstLineMatches whether or not the first line needs to match 398 * @param allowNesting whether or not nested children are allowed 399 */ 400 protected final void checkChildren(DetailAST parentNode, 401 int[] tokenTypes, 402 IndentLevel startIndent, 403 boolean firstLineMatches, 404 boolean allowNesting) { 405 Arrays.sort(tokenTypes); 406 for (DetailAST child = parentNode.getFirstChild(); 407 child != null; 408 child = child.getNextSibling()) { 409 if (Arrays.binarySearch(tokenTypes, child.getType()) >= 0 410 && shouldCheckIndentationForChild(child)) { 411 checkExpressionSubtree(child, startIndent, 412 firstLineMatches, allowNesting); 413 } 414 } 415 } 416 417 /** 418 * Decide whether to check indentation for a specific child. 419 * 420 * @param child child AST node 421 * @return true if indentation should be checked 422 */ 423 protected boolean shouldCheckIndentationForChild(DetailAST child) { 424 return true; 425 } 426 427 /** 428 * Check the indentation level for an expression subtree. 429 * 430 * @param tree the expression subtree to check 431 * @param indentLevel the indentation level 432 * @param firstLineMatches whether or not the first line has to match 433 * @param allowNesting whether or not subtree nesting is allowed 434 */ 435 protected final void checkExpressionSubtree( 436 DetailAST tree, 437 IndentLevel indentLevel, 438 boolean firstLineMatches, 439 boolean allowNesting 440 ) { 441 final DetailAstSet subtreeAst = new DetailAstSet(context); 442 final int firstLine = getFirstLine(tree); 443 if (firstLineMatches && !allowNesting) { 444 final DetailAST firstAst = getFirstAstNode(tree); 445 subtreeAst.addAst(firstAst); 446 } 447 findSubtreeAst(subtreeAst, tree, allowNesting); 448 449 checkLinesIndent(subtreeAst, indentLevel, firstLineMatches, firstLine, allowNesting); 450 } 451 452 /** 453 * Get the first line number for given expression. 454 * 455 * @param tree the expression to find the first line for 456 * @return the first line of expression 457 */ 458 protected static int getFirstLine(DetailAST tree) { 459 return getFirstAstNode(tree).getLineNo(); 460 } 461 462 /** 463 * Get the first ast for given expression. 464 * 465 * @param ast the abstract syntax tree for which the starting ast is to be found 466 * 467 * @return the first ast of the expression 468 */ 469 protected static DetailAST getFirstAstNode(DetailAST ast) { 470 471 DetailAST curNode = ast; 472 DetailAST realStart = ast; 473 while (curNode != null) { 474 if (curNode.getLineNo() < realStart.getLineNo() 475 || curNode.getLineNo() == realStart.getLineNo() 476 && Math.min(curNode.getColumnNo(), realStart.getColumnNo()) 477 == curNode.getColumnNo()) { 478 realStart = curNode; 479 } 480 DetailAST toVisit = curNode.getFirstChild(); 481 while (curNode != ast && toVisit == null) { 482 toVisit = curNode.getNextSibling(); 483 curNode = curNode.getParent(); 484 } 485 curNode = toVisit; 486 } 487 return realStart; 488 } 489 490 /** 491 * Get the column number for the start of a given expression, expanding 492 * tabs out into spaces in the process. 493 * 494 * @param ast the expression to find the start of 495 * 496 * @return the column number for the start of the expression 497 */ 498 protected final int expandedTabsColumnNo(DetailAST ast) { 499 final String line = 500 context.getLine(ast.getLineNo() - 1); 501 502 return CommonUtil.lengthExpandedTabs(line, ast.getColumnNo(), 503 context.getIndentationTabWidth()); 504 } 505 506 /** 507 * Find the set of abstract syntax tree for a given subtree. 508 * 509 * @param astSet the set of ast to add 510 * @param tree the subtree to examine 511 * @param allowNesting whether or not to allow nested subtrees 512 */ 513 protected final void findSubtreeAst(DetailAstSet astSet, DetailAST tree, 514 boolean allowNesting) { 515 if (!context.getHandlerFactory().isHandledType(tree.getType())) { 516 final boolean isRecordPatternDelimiter = 517 TokenUtil.isOfType(tree.getType(), TokenTypes.LPAREN, TokenTypes.RPAREN) 518 && tree.getParent().getType() == TokenTypes.RECORD_PATTERN_DEF; 519 if (!isRecordPatternDelimiter) { 520 final int lineNum = tree.getLineNo(); 521 final Integer colNum = astSet.getStartColumn(lineNum); 522 523 final int thisLineColumn = expandedTabsColumnNo(tree); 524 if (colNum == null || thisLineColumn < colNum) { 525 astSet.addAst(tree); 526 } 527 } 528 529 // check children 530 for (DetailAST node = tree.getFirstChild(); 531 node != null; 532 node = node.getNextSibling()) { 533 findSubtreeAst(astSet, node, allowNesting); 534 } 535 } 536 } 537 538 /** 539 * Accessor for the indentation context. 540 * 541 * @return the indentation context 542 */ 543 protected final IndentationContext getContext() { 544 return context; 545 } 546 547 /** 548 * Accessor for the MainAst attribute. 549 * 550 * @return the MainAst attribute 551 */ 552 protected final DetailAST getMainAst() { 553 return mainAst; 554 } 555 556 /** 557 * Accessor for the Parent attribute. 558 * 559 * @return the Parent attribute 560 */ 561 protected final AbstractExpressionHandler getParent() { 562 return parent; 563 } 564 565 /** 566 * A shortcut for {@code basicOffset} property. 567 * 568 * @return value of basicOffset property 569 */ 570 protected final int getBasicOffset() { 571 return context.getBasicOffset(); 572 } 573 574 /** 575 * A shortcut for {@code braceAdjustment} property. 576 * 577 * @return value of braceAdjustment property 578 */ 579 protected final int getBraceAdjustment() { 580 return context.getBraceAdjustment(); 581 } 582 583 /** 584 * Check the indentation of the right parenthesis. 585 * 586 * @param lparen left parenthesis associated with aRparen 587 * @param rparen parenthesis to check 588 */ 589 protected final void checkRightParen(DetailAST lparen, DetailAST rparen) { 590 if (rparen != null) { 591 // the rcurly can either be at the correct indentation, 592 // or not first on the line 593 final int rparenLevel = expandedTabsColumnNo(rparen); 594 // or has <lparen level> + 1 indentation 595 final int lparenLevel = expandedTabsColumnNo(lparen); 596 597 if (rparenLevel != lparenLevel + 1 598 && !getIndent().isAcceptable(rparenLevel) 599 && isOnStartOfLine(rparen)) { 600 logError(rparen, "rparen", rparenLevel); 601 } 602 } 603 } 604 605 /** 606 * Check the indentation of the left parenthesis. 607 * 608 * @param lparen parenthesis to check 609 */ 610 protected final void checkLeftParen(final DetailAST lparen) { 611 // the rcurly can either be at the correct indentation, or on the 612 // same line as the lcurly 613 if (lparen != null 614 && !getIndent().isAcceptable(expandedTabsColumnNo(lparen)) 615 && isOnStartOfLine(lparen)) { 616 logError(lparen, "lparen", expandedTabsColumnNo(lparen)); 617 } 618 } 619 620}