001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 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.design; 021 022import java.util.ArrayDeque; 023import java.util.Deque; 024import java.util.regex.Pattern; 025 026import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 027import com.puppycrawl.tools.checkstyle.api.DetailAST; 028import com.puppycrawl.tools.checkstyle.api.TokenTypes; 029 030/** 031 * <p> Ensures that exceptions (classes with names conforming to some regular 032 * expression and explicitly extending classes with names conforming to other 033 * regular expression) are immutable. That is, they have only final fields.</p> 034 * <p> Rationale: Exception instances should represent an error 035 * condition. Having non final fields not only allows the state to be 036 * modified by accident and therefore mask the original condition but 037 * also allows developers to accidentally forget to initialise state 038 * thereby leading to code catching the exception to draw incorrect 039 * conclusions based on the state.</p> 040 * 041 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 042 */ 043public final class MutableExceptionCheck extends AbstractCheck { 044 045 /** 046 * A key is pointing to the warning message text in "messages.properties" 047 * file. 048 */ 049 public static final String MSG_KEY = "mutable.exception"; 050 051 /** Default value for format and extendedClassNameFormat properties. */ 052 private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$|^.*Throwable$"; 053 /** Stack of checking information for classes. */ 054 private final Deque<Boolean> checkingStack = new ArrayDeque<>(); 055 /** Pattern for class name that is being extended. */ 056 private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT); 057 /** Should we check current class or not. */ 058 private boolean checking; 059 /** The regexp to match against. */ 060 private Pattern format = Pattern.compile(DEFAULT_FORMAT); 061 062 /** 063 * Sets the format of extended class name to the specified regular expression. 064 * @param extendedClassNameFormat a {@code String} value 065 */ 066 public void setExtendedClassNameFormat(Pattern extendedClassNameFormat) { 067 this.extendedClassNameFormat = extendedClassNameFormat; 068 } 069 070 /** 071 * Set the format for the specified regular expression. 072 * @param pattern the new pattern 073 */ 074 public void setFormat(Pattern pattern) { 075 format = pattern; 076 } 077 078 @Override 079 public int[] getDefaultTokens() { 080 return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF}; 081 } 082 083 @Override 084 public int[] getRequiredTokens() { 085 return getDefaultTokens(); 086 } 087 088 @Override 089 public int[] getAcceptableTokens() { 090 return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF}; 091 } 092 093 @Override 094 public void visitToken(DetailAST ast) { 095 switch (ast.getType()) { 096 case TokenTypes.CLASS_DEF: 097 visitClassDef(ast); 098 break; 099 case TokenTypes.VARIABLE_DEF: 100 visitVariableDef(ast); 101 break; 102 default: 103 throw new IllegalStateException(ast.toString()); 104 } 105 } 106 107 @Override 108 public void leaveToken(DetailAST ast) { 109 if (ast.getType() == TokenTypes.CLASS_DEF) { 110 leaveClassDef(); 111 } 112 } 113 114 /** 115 * Called when we start processing class definition. 116 * @param ast class definition node 117 */ 118 private void visitClassDef(DetailAST ast) { 119 checkingStack.push(checking); 120 checking = isNamedAsException(ast) && isExtendedClassNamedAsException(ast); 121 } 122 123 /** Called when we leave class definition. */ 124 private void leaveClassDef() { 125 checking = checkingStack.pop(); 126 } 127 128 /** 129 * Checks variable definition. 130 * @param ast variable def node for check 131 */ 132 private void visitVariableDef(DetailAST ast) { 133 if (checking && ast.getParent().getType() == TokenTypes.OBJBLOCK) { 134 final DetailAST modifiersAST = 135 ast.findFirstToken(TokenTypes.MODIFIERS); 136 137 if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) { 138 log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY, 139 ast.findFirstToken(TokenTypes.IDENT).getText()); 140 } 141 } 142 } 143 144 /** 145 * Checks that a class name conforms to specified format. 146 * @param ast class definition node 147 * @return true if a class name conforms to specified format 148 */ 149 private boolean isNamedAsException(DetailAST ast) { 150 final String className = ast.findFirstToken(TokenTypes.IDENT).getText(); 151 return format.matcher(className).find(); 152 } 153 154 /** 155 * Checks that if extended class name conforms to specified format. 156 * @param ast class definition node 157 * @return true if extended class name conforms to specified format 158 */ 159 private boolean isExtendedClassNamedAsException(DetailAST ast) { 160 boolean result = false; 161 final DetailAST extendsClause = ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE); 162 if (extendsClause != null) { 163 DetailAST currentNode = extendsClause; 164 while (currentNode.getLastChild() != null) { 165 currentNode = currentNode.getLastChild(); 166 } 167 final String extendedClassName = currentNode.getText(); 168 result = extendedClassNameFormat.matcher(extendedClassName).matches(); 169 } 170 return result; 171 } 172}