001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2025 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
051 * conclusions based on the state.
052 * </p>
053 *
054 * @since 3.2
055 */
056@FileStatefulCheck
057public final class MutableExceptionCheck extends AbstractCheck {
058
059    /**
060     * A key is pointing to the warning message text in "messages.properties"
061     * file.
062     */
063    public static final String MSG_KEY = "mutable.exception";
064
065    /** Default value for format and extendedClassNameFormat properties. */
066    private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$|^.*Throwable$";
067    /** Stack of checking information for classes. */
068    private final Deque<Boolean> checkingStack = new ArrayDeque<>();
069    /** Specify pattern for extended class names. */
070    private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT);
071    /** Should we check current class or not. */
072    private boolean checking;
073    /** Specify pattern for exception class names. */
074    private Pattern format = extendedClassNameFormat;
075
076    /**
077     * Setter to specify pattern for extended class names.
078     *
079     * @param extendedClassNameFormat a {@code String} value
080     * @since 6.2
081     */
082    public void setExtendedClassNameFormat(Pattern extendedClassNameFormat) {
083        this.extendedClassNameFormat = extendedClassNameFormat;
084    }
085
086    /**
087     * Setter to specify pattern for exception class names.
088     *
089     * @param pattern the new pattern
090     * @since 3.2
091     */
092    public void setFormat(Pattern pattern) {
093        format = pattern;
094    }
095
096    @Override
097    public int[] getDefaultTokens() {
098        return getRequiredTokens();
099    }
100
101    @Override
102    public int[] getRequiredTokens() {
103        return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
104    }
105
106    @Override
107    public int[] getAcceptableTokens() {
108        return getRequiredTokens();
109    }
110
111    @Override
112    public void visitToken(DetailAST ast) {
113        switch (ast.getType()) {
114            case TokenTypes.CLASS_DEF -> visitClassDef(ast);
115            case TokenTypes.VARIABLE_DEF -> visitVariableDef(ast);
116            default -> throw new IllegalStateException(ast.toString());
117        }
118    }
119
120    @Override
121    public void leaveToken(DetailAST ast) {
122        if (ast.getType() == TokenTypes.CLASS_DEF) {
123            leaveClassDef();
124        }
125    }
126
127    /**
128     * Called when we start processing class definition.
129     *
130     * @param ast class definition node
131     */
132    private void visitClassDef(DetailAST ast) {
133        checkingStack.push(checking);
134        checking = isNamedAsException(ast) && isExtendedClassNamedAsException(ast);
135    }
136
137    /** Called when we leave class definition. */
138    private void leaveClassDef() {
139        checking = checkingStack.pop();
140    }
141
142    /**
143     * Checks variable definition.
144     *
145     * @param ast variable def node for check
146     */
147    private void visitVariableDef(DetailAST ast) {
148        if (checking && ast.getParent().getType() == TokenTypes.OBJBLOCK) {
149            final DetailAST modifiersAST =
150                ast.findFirstToken(TokenTypes.MODIFIERS);
151
152            if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) {
153                log(ast, MSG_KEY, ast.findFirstToken(TokenTypes.IDENT).getText());
154            }
155        }
156    }
157
158    /**
159     * Checks that a class name conforms to specified format.
160     *
161     * @param ast class definition node
162     * @return true if a class name conforms to specified format
163     */
164    private boolean isNamedAsException(DetailAST ast) {
165        final String className = ast.findFirstToken(TokenTypes.IDENT).getText();
166        return format.matcher(className).find();
167    }
168
169    /**
170     * Checks that if extended class name conforms to specified format.
171     *
172     * @param ast class definition node
173     * @return true if extended class name conforms to specified format
174     */
175    private boolean isExtendedClassNamedAsException(DetailAST ast) {
176        boolean result = false;
177        final DetailAST extendsClause = ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE);
178        if (extendsClause != null) {
179            DetailAST currentNode = extendsClause;
180            while (currentNode.getLastChild() != null) {
181                currentNode = currentNode.getLastChild();
182            }
183            final String extendedClassName = currentNode.getText();
184            result = extendedClassNameFormat.matcher(extendedClassName).matches();
185        }
186        return result;
187    }
188
189}