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//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.blocks; 021 022 023import com.puppycrawl.tools.checkstyle.api.Check; 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.api.TokenTypes; 026 027/** 028 * <p> 029 * Checks for braces around code blocks. 030 * </p> 031 * <p> By default the check will check the following blocks: 032 * {@link TokenTypes#LITERAL_DO LITERAL_DO}, 033 * {@link TokenTypes#LITERAL_ELSE LITERAL_ELSE}, 034 * {@link TokenTypes#LITERAL_FOR LITERAL_FOR}, 035 * {@link TokenTypes#LITERAL_IF LITERAL_IF}, 036 * {@link TokenTypes#LITERAL_WHILE LITERAL_WHILE}. 037 * </p> 038 * <p> 039 * An example of how to configure the check is: 040 * </p> 041 * <pre> 042 * <module name="NeedBraces"/> 043 * </pre> 044 * <p> An example of how to configure the check for <code>if</code> and 045 * <code>else</code> blocks is: 046 * </p> 047 * <pre> 048 * <module name="NeedBraces"> 049 * <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/> 050 * </module> 051 * </pre> 052 * 053 * @author Rick Giles 054 * @version 1.0 055 */ 056public class NeedBracesCheck extends Check 057{ 058 @Override 059 public int[] getDefaultTokens() 060 { 061 return new int[] { 062 TokenTypes.LITERAL_DO, 063 TokenTypes.LITERAL_ELSE, 064 TokenTypes.LITERAL_FOR, 065 TokenTypes.LITERAL_IF, 066 TokenTypes.LITERAL_WHILE, 067 }; 068 } 069 070 @Override 071 public void visitToken(DetailAST aAST) 072 { 073 final DetailAST slistAST = aAST.findFirstToken(TokenTypes.SLIST); 074 boolean isElseIf = false; 075 if ((aAST.getType() == TokenTypes.LITERAL_ELSE) 076 && (aAST.findFirstToken(TokenTypes.LITERAL_IF) != null)) 077 { 078 isElseIf = true; 079 } 080 if ((slistAST == null) && !isElseIf) { 081 log(aAST.getLineNo(), "needBraces", aAST.getText()); 082 } 083 } 084}