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 com.puppycrawl.tools.checkstyle.api.AbstractCheck;
023import com.puppycrawl.tools.checkstyle.api.DetailAST;
024import com.puppycrawl.tools.checkstyle.api.TokenTypes;
025import com.puppycrawl.tools.checkstyle.utils.CheckUtils;
026import com.puppycrawl.tools.checkstyle.utils.ScopeUtils;
027
028/**
029 * <p>
030 * Checks if any class or object member explicitly initialized
031 * to default for its type value ({@code null} for object
032 * references, zero for numeric types and {@code char}
033 * and {@code false} for {@code boolean}.
034 * </p>
035 * <p>
036 * Rationale: each instance variable gets
037 * initialized twice, to the same value.  Java
038 * initializes each instance variable to its default
039 * value (0 or null) before performing any
040 * initialization specified in the code.  So in this case,
041 * x gets initialized to 0 twice, and bar gets initialized
042 * to null twice.  So there is a minor inefficiency.  This style of
043 * coding is a hold-over from C/C++ style coding,
044 * and it shows that the developer isn't really confident that
045 * Java really initializes instance variables to default
046 * values.
047 * </p>
048 *
049 * @author o_sukhodolsky
050 */
051public class ExplicitInitializationCheck extends AbstractCheck {
052
053    /**
054     * A key is pointing to the warning message text in "messages.properties"
055     * file.
056     */
057    public static final String MSG_KEY = "explicit.init";
058
059    /** Whether only explicit initialization made to null should be checked.**/
060    private boolean onlyObjectReferences;
061
062    @Override
063    public final int[] getDefaultTokens() {
064        return new int[] {TokenTypes.VARIABLE_DEF};
065    }
066
067    @Override
068    public final int[] getRequiredTokens() {
069        return getDefaultTokens();
070    }
071
072    @Override
073    public final int[] getAcceptableTokens() {
074        return new int[] {TokenTypes.VARIABLE_DEF};
075    }
076
077    /**
078     * Sets whether only explicit initialization made to null should be checked.
079     * @param onlyObjectReferences whether only explicit initialization made to null
080     *                             should be checked
081     */
082    public void setOnlyObjectReferences(boolean onlyObjectReferences) {
083        this.onlyObjectReferences = onlyObjectReferences;
084    }
085
086    @Override
087    public void visitToken(DetailAST ast) {
088        if (!isSkipCase(ast)) {
089            final DetailAST assign = ast.findFirstToken(TokenTypes.ASSIGN);
090            final DetailAST exprStart =
091                assign.getFirstChild().getFirstChild();
092            final DetailAST type = ast.findFirstToken(TokenTypes.TYPE);
093            if (isObjectType(type)
094                && exprStart.getType() == TokenTypes.LITERAL_NULL) {
095                final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
096                log(ident, MSG_KEY, ident.getText(), "null");
097            }
098            if (!onlyObjectReferences) {
099                validateNonObjects(ast);
100            }
101        }
102    }
103
104    /**
105     * Checks for explicit initializations made to 'false', '0' and '\0'.
106     * @param ast token being checked for explicit initializations
107     */
108    private void validateNonObjects(DetailAST ast) {
109        final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
110        final DetailAST assign = ast.findFirstToken(TokenTypes.ASSIGN);
111        final DetailAST exprStart =
112                assign.getFirstChild().getFirstChild();
113        final DetailAST type = ast.findFirstToken(TokenTypes.TYPE);
114        final int primitiveType = type.getFirstChild().getType();
115        if (primitiveType == TokenTypes.LITERAL_BOOLEAN
116                && exprStart.getType() == TokenTypes.LITERAL_FALSE) {
117            log(ident, MSG_KEY, ident.getText(), "false");
118        }
119        if (isNumericType(primitiveType) && isZero(exprStart)) {
120            log(ident, MSG_KEY, ident.getText(), "0");
121        }
122        if (primitiveType == TokenTypes.LITERAL_CHAR
123                && isZeroChar(exprStart)) {
124            log(ident, MSG_KEY, ident.getText(), "\\0");
125        }
126    }
127
128    /**
129     * Examine char literal for initializing to default value.
130     * @param exprStart expression
131     * @return true is literal is initialized by zero symbol
132     */
133    private static boolean isZeroChar(DetailAST exprStart) {
134        return isZero(exprStart)
135            || exprStart.getType() == TokenTypes.CHAR_LITERAL
136            && "'\\0'".equals(exprStart.getText());
137    }
138
139    /**
140     * Checks for cases that should be skipped: no assignment, local variable, final variables.
141     * @param ast Variable def AST
142     * @return true is that is a case that need to be skipped.
143     */
144    private static boolean isSkipCase(DetailAST ast) {
145        boolean skipCase = true;
146
147        // do not check local variables and
148        // fields declared in interface/annotations
149        if (!ScopeUtils.isLocalVariableDef(ast)
150                && !ScopeUtils.isInInterfaceOrAnnotationBlock(ast)) {
151            final DetailAST assign = ast.findFirstToken(TokenTypes.ASSIGN);
152
153            if (assign != null) {
154                final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
155                skipCase = modifiers.branchContains(TokenTypes.FINAL);
156            }
157        }
158        return skipCase;
159    }
160
161    /**
162     * Determines if a given type is an object type.
163     * @param type type to check.
164     * @return true if it is an object type.
165     */
166    private static boolean isObjectType(DetailAST type) {
167        final int objectType = type.getFirstChild().getType();
168        return objectType == TokenTypes.IDENT || objectType == TokenTypes.DOT
169                || objectType == TokenTypes.ARRAY_DECLARATOR;
170    }
171
172    /**
173     * Determine if a given type is a numeric type.
174     * @param type code of the type for check.
175     * @return true if it's a numeric type.
176     * @see TokenTypes
177     */
178    private static boolean isNumericType(int type) {
179        return type == TokenTypes.LITERAL_BYTE
180                || type == TokenTypes.LITERAL_SHORT
181                || type == TokenTypes.LITERAL_INT
182                || type == TokenTypes.LITERAL_FLOAT
183                || type == TokenTypes.LITERAL_LONG
184                || type == TokenTypes.LITERAL_DOUBLE;
185    }
186
187    /**
188     * Checks if given node contains numeric constant for zero.
189     *
190     * @param expr node to check.
191     * @return true if given node contains numeric constant for zero.
192     */
193    private static boolean isZero(DetailAST expr) {
194        final int type = expr.getType();
195        switch (type) {
196            case TokenTypes.NUM_FLOAT:
197            case TokenTypes.NUM_DOUBLE:
198            case TokenTypes.NUM_INT:
199            case TokenTypes.NUM_LONG:
200                final String text = expr.getText();
201                return Double.compare(
202                    CheckUtils.parseDouble(text, type), 0.0) == 0;
203            default:
204                return false;
205        }
206    }
207}