001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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.coding;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026
027/**
028 * <p>
029 * Check that the {@code default} is after all the cases in a {@code switch} statement.
030 * </p>
031 * <p>
032 * Rationale: Java allows {@code default} anywhere within the
033 * {@code switch} statement. But it is more readable if it comes after the last {@code case}.
034 * </p>
035 * <ul>
036 * <li>
037 * Property {@code skipIfLastAndSharedWithCase} - Control whether to allow {@code default}
038 * along with {@code case} if they are not last.
039 * Type is {@code boolean}.
040 * Default value is {@code false}.
041 * </li>
042 * </ul>
043 * <p>
044 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
045 * </p>
046 * <p>
047 * Violation Message Keys:
048 * </p>
049 * <ul>
050 * <li>
051 * {@code default.comes.last}
052 * </li>
053 * <li>
054 * {@code default.comes.last.in.casegroup}
055 * </li>
056 * </ul>
057 *
058 * @since 3.4
059 */
060@StatelessCheck
061public class DefaultComesLastCheck extends AbstractCheck {
062
063    /**
064     * A key is pointing to the warning message text in "messages.properties"
065     * file.
066     */
067    public static final String MSG_KEY = "default.comes.last";
068
069    /**
070     * A key is pointing to the warning message text in "messages.properties"
071     * file.
072     */
073    public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE =
074            "default.comes.last.in.casegroup";
075
076    /** Control whether to allow {@code default} along with {@code case} if they are not last. */
077    private boolean skipIfLastAndSharedWithCase;
078
079    @Override
080    public int[] getAcceptableTokens() {
081        return getRequiredTokens();
082    }
083
084    @Override
085    public int[] getDefaultTokens() {
086        return getRequiredTokens();
087    }
088
089    @Override
090    public int[] getRequiredTokens() {
091        return new int[] {
092            TokenTypes.LITERAL_DEFAULT,
093        };
094    }
095
096    /**
097     * Setter to control whether to allow {@code default} along with
098     * {@code case} if they are not last.
099     *
100     * @param newValue whether to ignore checking.
101     * @since 7.7
102     */
103    public void setSkipIfLastAndSharedWithCase(boolean newValue) {
104        skipIfLastAndSharedWithCase = newValue;
105    }
106
107    @Override
108    public void visitToken(DetailAST ast) {
109        final DetailAST defaultGroupAST = ast.getParent();
110
111        // Switch rules are not subject to fall through.
112        final boolean isSwitchRule = defaultGroupAST.getType() == TokenTypes.SWITCH_RULE;
113
114        if (skipIfLastAndSharedWithCase && !isSwitchRule) {
115            if (isNextSiblingOf(ast, TokenTypes.LITERAL_CASE)) {
116                log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE);
117            }
118            else if (ast.getPreviousSibling() == null
119                && isNextSiblingOf(defaultGroupAST,
120                                                   TokenTypes.CASE_GROUP)) {
121                log(ast, MSG_KEY);
122            }
123        }
124        else if (isNextSiblingOf(defaultGroupAST,
125                                            TokenTypes.CASE_GROUP)
126                    || isNextSiblingOf(defaultGroupAST,
127                                            TokenTypes.SWITCH_RULE)) {
128            log(ast, MSG_KEY);
129        }
130    }
131
132    /**
133     * Return true only if passed tokenType in argument is found or returns false.
134     *
135     * @param ast root node.
136     * @param tokenType tokentype to be processed.
137     * @return true if desired token is found or else false.
138     */
139    private static boolean isNextSiblingOf(DetailAST ast, int tokenType) {
140        return ast.getNextSibling() != null && ast.getNextSibling().getType() == tokenType;
141    }
142
143}