001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2015 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.api.Check; 023import com.puppycrawl.tools.checkstyle.api.DetailAST; 024 025/** 026 * Abstract class which provides helpers functionality for nested checks. 027 * 028 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 029 */ 030public abstract class AbstractNestedDepthCheck extends Check { 031 /** Maximum allowed nesting depth. */ 032 private int max; 033 /** Current nesting depth. */ 034 private int depth; 035 036 /** 037 * Creates new instance of checks. 038 * @param max default allowed nesting depth. 039 */ 040 protected AbstractNestedDepthCheck(int max) { 041 this.max = max; 042 } 043 044 @Override 045 public final int[] getRequiredTokens() { 046 return getDefaultTokens(); 047 } 048 049 @Override 050 public void beginTree(DetailAST rootAST) { 051 depth = 0; 052 } 053 054 /** 055 * Setter for maximum allowed nesting depth. 056 * @param max maximum allowed nesting depth. 057 */ 058 public final void setMax(int max) { 059 this.max = max; 060 } 061 062 /** 063 * Increasing current nesting depth. 064 * @param ast note which increases nesting. 065 * @param messageId message id for logging error. 066 */ 067 protected final void nestIn(DetailAST ast, String messageId) { 068 if (depth > max) { 069 log(ast, messageId, depth, max); 070 } 071 ++depth; 072 } 073 074 /** Decreasing current nesting depth. */ 075 protected final void nestOut() { 076 --depth; 077 } 078}