001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 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 java.util.Objects;
023
024import com.puppycrawl.tools.checkstyle.StatelessCheck;
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.TokenTypes;
028
029/**
030 * <p>
031 * Check that the {@code default} is after all the {@code case}s
032 * in a {@code switch} statement.
033 * </p>
034 * <p>
035 * Rationale: Java allows {@code default} anywhere within the
036 * {@code switch} statement. But if it comes after the last
037 * {@code case} then it is more readable.
038 * </p>
039 * <p>
040 * An example of how to configure the check is:
041 * </p>
042 * <pre>
043 * &lt;module name="DefaultComesLast"/&gt;
044 * </pre>
045 * @author o_sukhodolsky
046 */
047@StatelessCheck
048public class DefaultComesLastCheck extends AbstractCheck {
049
050    /**
051     * A key is pointing to the warning message text in "messages.properties"
052     * file.
053     */
054    public static final String MSG_KEY = "default.comes.last";
055
056    /**
057     * A key is pointing to the warning message text in "messages.properties"
058     * file.
059     */
060    public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE =
061            "default.comes.last.in.casegroup";
062
063    /** Whether to process skipIfLastAndSharedWithCaseInSwitch() invocations. */
064    private boolean skipIfLastAndSharedWithCase;
065
066    @Override
067    public int[] getAcceptableTokens() {
068        return getRequiredTokens();
069    }
070
071    @Override
072    public int[] getDefaultTokens() {
073        return getRequiredTokens();
074    }
075
076    @Override
077    public int[] getRequiredTokens() {
078        return new int[] {
079            TokenTypes.LITERAL_DEFAULT,
080        };
081    }
082
083    /**
084     * Whether to allow default keyword not in last but surrounded with case.
085     * @param newValue whether to ignore checking.
086     */
087    public void setSkipIfLastAndSharedWithCase(boolean newValue) {
088        skipIfLastAndSharedWithCase = newValue;
089    }
090
091    @Override
092    public void visitToken(DetailAST ast) {
093        final DetailAST defaultGroupAST = ast.getParent();
094        //default keywords used in annotations too - not what we're
095        //interested in
096        if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF
097                && defaultGroupAST.getType() != TokenTypes.MODIFIERS) {
098            if (skipIfLastAndSharedWithCase) {
099                if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) {
100                    log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE);
101                }
102                else if (ast.getPreviousSibling() == null
103                    && Objects.nonNull(findNextSibling(defaultGroupAST,
104                                                       TokenTypes.CASE_GROUP))) {
105                    log(ast, MSG_KEY);
106                }
107            }
108            else if (Objects.nonNull(findNextSibling(defaultGroupAST,
109                                                     TokenTypes.CASE_GROUP))) {
110                log(ast, MSG_KEY);
111            }
112        }
113    }
114
115    /**
116     * Return token type only if passed tokenType in argument is found or returns -1.
117     *
118     * @param ast root node.
119     * @param tokenType tokentype to be processed.
120     * @return token if desired token is found or else null.
121     */
122    private static DetailAST findNextSibling(DetailAST ast, int tokenType) {
123        DetailAST token = null;
124        DetailAST node = ast.getNextSibling();
125        while (node != null) {
126            if (node.getType() == tokenType) {
127                token = node;
128                break;
129            }
130            node = node.getNextSibling();
131        }
132        return token;
133    }
134
135}