View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2017 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.design;
21  
22  import java.util.ArrayDeque;
23  import java.util.Deque;
24  import java.util.regex.Pattern;
25  
26  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
27  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
28  import com.puppycrawl.tools.checkstyle.api.DetailAST;
29  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30  
31  /**
32   * <p> Ensures that exceptions (classes with names conforming to some regular
33   * expression and explicitly extending classes with names conforming to other
34   * regular expression) are immutable. That is, they have only final fields.</p>
35   * <p> Rationale: Exception instances should represent an error
36   * condition. Having non final fields not only allows the state to be
37   * modified by accident and therefore mask the original condition but
38   * also allows developers to accidentally forget to initialise state
39   * thereby leading to code catching the exception to draw incorrect
40   * conclusions based on the state.</p>
41   *
42   * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
43   */
44  @FileStatefulCheck
45  public final class MutableExceptionCheck extends AbstractCheck {
46  
47      /**
48       * A key is pointing to the warning message text in "messages.properties"
49       * file.
50       */
51      public static final String MSG_KEY = "mutable.exception";
52  
53      /** Default value for format and extendedClassNameFormat properties. */
54      private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$|^.*Throwable$";
55      /** Stack of checking information for classes. */
56      private final Deque<Boolean> checkingStack = new ArrayDeque<>();
57      /** Pattern for class name that is being extended. */
58      private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT);
59      /** Should we check current class or not. */
60      private boolean checking;
61      /** The regexp to match against. */
62      private Pattern format = Pattern.compile(DEFAULT_FORMAT);
63  
64      /**
65       * Sets the format of extended class name to the specified regular expression.
66       * @param extendedClassNameFormat a {@code String} value
67       */
68      public void setExtendedClassNameFormat(Pattern extendedClassNameFormat) {
69          this.extendedClassNameFormat = extendedClassNameFormat;
70      }
71  
72      /**
73       * Set the format for the specified regular expression.
74       * @param pattern the new pattern
75       */
76      public void setFormat(Pattern pattern) {
77          format = pattern;
78      }
79  
80      @Override
81      public int[] getDefaultTokens() {
82          return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
83      }
84  
85      @Override
86      public int[] getRequiredTokens() {
87          return getDefaultTokens();
88      }
89  
90      @Override
91      public int[] getAcceptableTokens() {
92          return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
93      }
94  
95      @Override
96      public void visitToken(DetailAST ast) {
97          switch (ast.getType()) {
98              case TokenTypes.CLASS_DEF:
99                  visitClassDef(ast);
100                 break;
101             case TokenTypes.VARIABLE_DEF:
102                 visitVariableDef(ast);
103                 break;
104             default:
105                 throw new IllegalStateException(ast.toString());
106         }
107     }
108 
109     @Override
110     public void leaveToken(DetailAST ast) {
111         if (ast.getType() == TokenTypes.CLASS_DEF) {
112             leaveClassDef();
113         }
114     }
115 
116     /**
117      * Called when we start processing class definition.
118      * @param ast class definition node
119      */
120     private void visitClassDef(DetailAST ast) {
121         checkingStack.push(checking);
122         checking = isNamedAsException(ast) && isExtendedClassNamedAsException(ast);
123     }
124 
125     /** Called when we leave class definition. */
126     private void leaveClassDef() {
127         checking = checkingStack.pop();
128     }
129 
130     /**
131      * Checks variable definition.
132      * @param ast variable def node for check
133      */
134     private void visitVariableDef(DetailAST ast) {
135         if (checking && ast.getParent().getType() == TokenTypes.OBJBLOCK) {
136             final DetailAST modifiersAST =
137                 ast.findFirstToken(TokenTypes.MODIFIERS);
138 
139             if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) {
140                 log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY,
141                         ast.findFirstToken(TokenTypes.IDENT).getText());
142             }
143         }
144     }
145 
146     /**
147      * Checks that a class name conforms to specified format.
148      * @param ast class definition node
149      * @return true if a class name conforms to specified format
150      */
151     private boolean isNamedAsException(DetailAST ast) {
152         final String className = ast.findFirstToken(TokenTypes.IDENT).getText();
153         return format.matcher(className).find();
154     }
155 
156     /**
157      * Checks that if extended class name conforms to specified format.
158      * @param ast class definition node
159      * @return true if extended class name conforms to specified format
160      */
161     private boolean isExtendedClassNamedAsException(DetailAST ast) {
162         boolean result = false;
163         final DetailAST extendsClause = ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE);
164         if (extendsClause != null) {
165             DetailAST currentNode = extendsClause;
166             while (currentNode.getLastChild() != null) {
167                 currentNode = currentNode.getLastChild();
168             }
169             final String extendedClassName = currentNode.getText();
170             result = extendedClassNameFormat.matcher(extendedClassName).matches();
171         }
172         return result;
173     }
174 }