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.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
099            if (skipIfLastAndSharedWithCase) {
100                if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) {
101                    log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE);
102                }
103                else if (ast.getPreviousSibling() == null
104                    && Objects.nonNull(findNextSibling(defaultGroupAST,
105                                                       TokenTypes.CASE_GROUP))) {
106                    log(ast, MSG_KEY);
107                }
108            }
109            else if (Objects.nonNull(findNextSibling(defaultGroupAST,
110                                                     TokenTypes.CASE_GROUP))) {
111                log(ast, MSG_KEY);
112            }
113        }
114    }
115
116    /**
117     * Return token type only if passed tokenType in argument is found or returns -1.
118     *
119     * @param ast root node.
120     * @param tokenType tokentype to be processed.
121     * @return token if desired token is found or else null.
122     */
123    private static DetailAST findNextSibling(DetailAST ast, int tokenType) {
124        DetailAST token = null;
125        DetailAST node = ast.getNextSibling();
126        while (node != null) {
127            if (node.getType() == tokenType) {
128                token = node;
129                break;
130            }
131            node = node.getNextSibling();
132        }
133        return token;
134    }
135}