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