001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.FileStatefulCheck;
027import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030
031/**
032 * <div>
033 * Ensures that exception classes (classes with names conforming to some pattern
034 * and explicitly extending classes with names conforming to other
035 * pattern) are immutable, that is, that they have only final fields.
036 * </div>
037 *
038 * <p>
039 * The current algorithm is very simple: it checks that all members of exception are final.
040 * The user can still mutate an exception's instance (e.g. Throwable has a method called
041 * {@code setStackTrace} which changes the exception's stack trace). But, at least, all
042 * information provided by this exception type is unchangeable.
043 * </p>
044 *
045 * <p>
046 * Rationale: Exception instances should represent an error
047 * condition. Having non-final fields not only allows the state to be
048 * modified by accident and therefore mask the original condition but
049 * also allows developers to accidentally forget to set the initial state.
050 * In both cases, code catching the exception could draw incorrect conclusions based on the state.
051 * </p>
052 *
053 * @since 3.2
054 */
055@FileStatefulCheck
056public final class MutableExceptionCheck extends AbstractCheck {
057
058    /**
059     * A key is pointing to the warning message text in "messages.properties" file.
060     */
061    public static final String MSG_KEY = "mutable.exception";
062
063    /** Default value for format and extendedClassNameFormat properties. */
064    private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$|^.*Throwable$";
065    /** Stack of checking information for classes. */
066    private final Deque<Boolean> checkingStack = new ArrayDeque<>();
067    /** Specify pattern for extended class names. */
068    private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT);
069    /** Should we check current class or not. */
070    private boolean checking;
071    /** Specify pattern for exception class names. */
072    private Pattern format = extendedClassNameFormat;
073
074    /**
075     * Creates a new {@code MutableExceptionCheck} instance.
076     */
077    public MutableExceptionCheck() {
078        // no code by default
079    }
080
081    /**
082     * Setter to specify pattern for extended class names.
083     *
084     * @param extendedClassNameFormat a {@code String} value
085     * @since 6.2
086     */
087    public void setExtendedClassNameFormat(Pattern extendedClassNameFormat) {
088        this.extendedClassNameFormat = extendedClassNameFormat;
089    }
090
091    /**
092     * Setter to specify pattern for exception class names.
093     *
094     * @param pattern the new pattern
095     * @since 3.2
096     */
097    public void setFormat(Pattern pattern) {
098        format = pattern;
099    }
100
101    @Override
102    public int[] getDefaultTokens() {
103        return getRequiredTokens();
104    }
105
106    @Override
107    public int[] getRequiredTokens() {
108        return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
109    }
110
111    @Override
112    public int[] getAcceptableTokens() {
113        return getRequiredTokens();
114    }
115
116    @Override
117    public void visitToken(DetailAST ast) {
118        switch (ast.getType()) {
119            case TokenTypes.CLASS_DEF -> visitClassDef(ast);
120            case TokenTypes.VARIABLE_DEF -> visitVariableDef(ast);
121            default -> throw new IllegalStateException(ast.toString());
122        }
123    }
124
125    @Override
126    public void leaveToken(DetailAST ast) {
127        if (ast.getType() == TokenTypes.CLASS_DEF) {
128            leaveClassDef();
129        }
130    }
131
132    /**
133     * Called when we start processing class definition.
134     *
135     * @param ast class definition node
136     */
137    private void visitClassDef(DetailAST ast) {
138        checkingStack.push(checking);
139        checking = isNamedAsException(ast) && isExtendedClassNamedAsException(ast);
140    }
141
142    /** Called when we leave class definition. */
143    private void leaveClassDef() {
144        checking = checkingStack.pop();
145    }
146
147    /**
148     * Checks variable definition.
149     *
150     * @param ast variable def node for check
151     */
152    private void visitVariableDef(DetailAST ast) {
153        if (checking && ast.getParent().getType() == TokenTypes.OBJBLOCK) {
154            final DetailAST modifiersAST =
155                ast.findFirstToken(TokenTypes.MODIFIERS);
156
157            if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) {
158                log(ast, MSG_KEY, ast.findFirstToken(TokenTypes.IDENT).getText());
159            }
160        }
161    }
162
163    /**
164     * Checks that a class name conforms to specified format.
165     *
166     * @param ast class definition node
167     * @return true if a class name conforms to specified format
168     */
169    private boolean isNamedAsException(DetailAST ast) {
170        final String className = ast.findFirstToken(TokenTypes.IDENT).getText();
171        return format.matcher(className).find();
172    }
173
174    /**
175     * Checks that if extended class name conforms to specified format.
176     *
177     * @param ast class definition node
178     * @return true if extended class name conforms to specified format
179     */
180    private boolean isExtendedClassNamedAsException(DetailAST ast) {
181        boolean result = false;
182        final DetailAST extendsClause = ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE);
183        if (extendsClause != null) {
184            DetailAST currentNode = extendsClause;
185            while (currentNode.getLastChild() != null) {
186                currentNode = currentNode.getLastChild();
187            }
188            final String extendedClassName = currentNode.getText();
189            result = extendedClassNameFormat.matcher(extendedClassName).matches();
190        }
191        return result;
192    }
193
194}