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