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.coding; 021 022import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 023import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.api.TokenTypes; 026 027/** 028 * <div> 029 * Restricts nested {@code for} blocks to a specified depth. 030 * </div> 031 * 032 * @since 5.3 033 */ 034@FileStatefulCheck 035public final class NestedForDepthCheck extends AbstractCheck { 036 037 /** 038 * A key is pointing to the warning message text in "messages.properties" file. 039 */ 040 public static final String MSG_KEY = "nested.for.depth"; 041 042 /** Specify maximum allowed nesting depth. */ 043 private int max = 1; 044 /** Current nesting depth. */ 045 private int depth; 046 047 /** 048 * Creates a new {@code NestedForDepthCheck} instance. 049 */ 050 public NestedForDepthCheck() { 051 // no code by default 052 } 053 054 /** 055 * Setter to specify maximum allowed nesting depth. 056 * 057 * @param max maximum allowed nesting depth. 058 * @since 5.3 059 */ 060 public void setMax(int max) { 061 this.max = max; 062 } 063 064 @Override 065 public int[] getDefaultTokens() { 066 return getRequiredTokens(); 067 } 068 069 @Override 070 public int[] getAcceptableTokens() { 071 return getRequiredTokens(); 072 } 073 074 @Override 075 public int[] getRequiredTokens() { 076 return new int[] {TokenTypes.LITERAL_FOR}; 077 } 078 079 @Override 080 public void beginTree(DetailAST rootAST) { 081 depth = 0; 082 } 083 084 @Override 085 public void visitToken(DetailAST ast) { 086 if (depth > max) { 087 log(ast, MSG_KEY, depth, max); 088 } 089 ++depth; 090 } 091 092 @Override 093 public void leaveToken(DetailAST ast) { 094 --depth; 095 } 096 097}