001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2014 Oliver Burn 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//////////////////////////////////////////////////////////////////////////////// 019package com.puppycrawl.tools.checkstyle.checks.coding; 020 021import com.puppycrawl.tools.checkstyle.api.Check; 022import com.puppycrawl.tools.checkstyle.api.DetailAST; 023 024/** 025 * Abstract class which provides helpers functionality for nested checks. 026 * 027 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 028 */ 029public abstract class AbstractNestedDepthCheck extends Check 030{ 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 public AbstractNestedDepthCheck(int max) 041 { 042 setMax(max); 043 } 044 045 @Override 046 public final int[] getRequiredTokens() 047 { 048 return getDefaultTokens(); 049 } 050 051 @Override 052 public void beginTree(DetailAST rootAST) 053 { 054 depth = 0; 055 } 056 057 /** 058 * Getter for maximum allowed nesting depth. 059 * @return maximum allowed nesting depth. 060 */ 061 public final int getMax() 062 { 063 return max; 064 } 065 066 /** 067 * Setter for maximum allowed nesting depth. 068 * @param max maximum allowed nesting depth. 069 */ 070 public final void setMax(int max) 071 { 072 this.max = max; 073 } 074 075 /** 076 * Increasing current nesting depth. 077 * @param ast note which increases nesting. 078 * @param messageId message id for logging error. 079 */ 080 protected final void nestIn(DetailAST ast, String messageId) 081 { 082 if (depth > max) { 083 log(ast, messageId, depth, max); 084 } 085 ++depth; 086 } 087 088 /** Decreasing current nesting depth */ 089 protected final void nestOut() 090 { 091 --depth; 092 } 093}