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.Collections;
023import java.util.HashSet;
024import java.util.Set;
025
026import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
027import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030
031/**
032 * Checks that any combination of String literals
033 * is on the left side of an equals() comparison.
034 * Also checks for String literals assigned to some field
035 * (such as {@code someString.equals(anotherString = "text")}).
036 *
037 * <p>Rationale: Calling the equals() method on String literals
038 * will avoid a potential NullPointerException.  Also, it is
039 * pretty common to see null check right before equals comparisons
040 * which is not necessary in the below example.
041 *
042 * <p>For example:
043 *
044 * <pre>
045 *  {@code
046 *    String nullString = null;
047 *    nullString.equals(&quot;My_Sweet_String&quot;);
048 *  }
049 * </pre>
050 * should be refactored to
051 *
052 * <pre>
053 *  {@code
054 *    String nullString = null;
055 *    &quot;My_Sweet_String&quot;.equals(nullString);
056 *  }
057 * </pre>
058 *
059 */
060@FileStatefulCheck
061public class EqualsAvoidNullCheck extends AbstractCheck {
062
063    /**
064     * A key is pointing to the warning message text in "messages.properties"
065     * file.
066     */
067    public static final String MSG_EQUALS_AVOID_NULL = "equals.avoid.null";
068
069    /**
070     * A key is pointing to the warning message text in "messages.properties"
071     * file.
072     */
073    public static final String MSG_EQUALS_IGNORE_CASE_AVOID_NULL = "equalsIgnoreCase.avoid.null";
074
075    /** Method name for comparison. */
076    private static final String EQUALS = "equals";
077
078    /** Type name for comparison. */
079    private static final String STRING = "String";
080
081    /** Whether to process equalsIgnoreCase() invocations. */
082    private boolean ignoreEqualsIgnoreCase;
083
084    /** Stack of sets of field names, one for each class of a set of nested classes. */
085    private FieldFrame currentFrame;
086
087    @Override
088    public int[] getDefaultTokens() {
089        return getRequiredTokens();
090    }
091
092    @Override
093    public int[] getAcceptableTokens() {
094        return getRequiredTokens();
095    }
096
097    @Override
098    public int[] getRequiredTokens() {
099        return new int[] {
100            TokenTypes.METHOD_CALL,
101            TokenTypes.CLASS_DEF,
102            TokenTypes.METHOD_DEF,
103            TokenTypes.LITERAL_IF,
104            TokenTypes.LITERAL_FOR,
105            TokenTypes.LITERAL_WHILE,
106            TokenTypes.LITERAL_DO,
107            TokenTypes.LITERAL_CATCH,
108            TokenTypes.LITERAL_TRY,
109            TokenTypes.VARIABLE_DEF,
110            TokenTypes.PARAMETER_DEF,
111            TokenTypes.CTOR_DEF,
112            TokenTypes.SLIST,
113            TokenTypes.ENUM_DEF,
114            TokenTypes.ENUM_CONSTANT_DEF,
115            TokenTypes.LITERAL_NEW,
116        };
117    }
118
119    /**
120     * Whether to ignore checking {@code String.equalsIgnoreCase(String)}.
121     * @param newValue whether to ignore checking
122     *    {@code String.equalsIgnoreCase(String)}.
123     */
124    public void setIgnoreEqualsIgnoreCase(boolean newValue) {
125        ignoreEqualsIgnoreCase = newValue;
126    }
127
128    @Override
129    public void beginTree(DetailAST rootAST) {
130        currentFrame = new FieldFrame(null);
131    }
132
133    @Override
134    public void visitToken(final DetailAST ast) {
135        switch (ast.getType()) {
136            case TokenTypes.VARIABLE_DEF:
137            case TokenTypes.PARAMETER_DEF:
138                currentFrame.addField(ast);
139                break;
140            case TokenTypes.METHOD_CALL:
141                processMethodCall(ast);
142                break;
143            case TokenTypes.SLIST:
144                processSlist(ast);
145                break;
146            case TokenTypes.LITERAL_NEW:
147                processLiteralNew(ast);
148                break;
149            default:
150                processFrame(ast);
151        }
152    }
153
154    @Override
155    public void leaveToken(DetailAST ast) {
156        final int astType = ast.getType();
157        if (astType != TokenTypes.VARIABLE_DEF
158                && astType != TokenTypes.PARAMETER_DEF
159                && astType != TokenTypes.METHOD_CALL
160                && astType != TokenTypes.SLIST
161                && astType != TokenTypes.LITERAL_NEW
162                || astType == TokenTypes.LITERAL_NEW
163                    && ast.findFirstToken(TokenTypes.OBJBLOCK) != null) {
164            currentFrame = currentFrame.getParent();
165        }
166        else if (astType == TokenTypes.SLIST) {
167            leaveSlist(ast);
168        }
169    }
170
171    @Override
172    public void finishTree(DetailAST ast) {
173        traverseFieldFrameTree(currentFrame);
174    }
175
176    /**
177     * Determine whether SLIST begins static or non-static block and add it as
178     * a frame in this case.
179     * @param ast SLIST ast.
180     */
181    private void processSlist(DetailAST ast) {
182        final int parentType = ast.getParent().getType();
183        if (parentType == TokenTypes.SLIST
184                || parentType == TokenTypes.STATIC_INIT
185                || parentType == TokenTypes.INSTANCE_INIT) {
186            final FieldFrame frame = new FieldFrame(currentFrame);
187            currentFrame.addChild(frame);
188            currentFrame = frame;
189        }
190    }
191
192    /**
193     * Determine whether SLIST begins static or non-static block.
194     * @param ast SLIST ast.
195     */
196    private void leaveSlist(DetailAST ast) {
197        final int parentType = ast.getParent().getType();
198        if (parentType == TokenTypes.SLIST
199                || parentType == TokenTypes.STATIC_INIT
200                || parentType == TokenTypes.INSTANCE_INIT) {
201            currentFrame = currentFrame.getParent();
202        }
203    }
204
205    /**
206     * Process CLASS_DEF, METHOD_DEF, LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO,
207     * LITERAL_CATCH, LITERAL_TRY, CTOR_DEF, ENUM_DEF, ENUM_CONSTANT_DEF.
208     * @param ast processed ast.
209     */
210    private void processFrame(DetailAST ast) {
211        final FieldFrame frame = new FieldFrame(currentFrame);
212        final int astType = ast.getType();
213        if (astType == TokenTypes.CLASS_DEF
214                || astType == TokenTypes.ENUM_DEF
215                || astType == TokenTypes.ENUM_CONSTANT_DEF) {
216            frame.setClassOrEnumOrEnumConstDef(true);
217            frame.setFrameName(ast.findFirstToken(TokenTypes.IDENT).getText());
218        }
219        currentFrame.addChild(frame);
220        currentFrame = frame;
221    }
222
223    /**
224     * Add the method call to the current frame if it should be processed.
225     * @param methodCall METHOD_CALL ast.
226     */
227    private void processMethodCall(DetailAST methodCall) {
228        final DetailAST dot = methodCall.getFirstChild();
229        if (dot.getType() == TokenTypes.DOT) {
230            final String methodName = dot.getLastChild().getText();
231            if (EQUALS.equals(methodName)
232                    || !ignoreEqualsIgnoreCase && "equalsIgnoreCase".equals(methodName)) {
233                currentFrame.addMethodCall(methodCall);
234            }
235        }
236    }
237
238    /**
239     * Determine whether LITERAL_NEW is an anonymous class definition and add it as
240     * a frame in this case.
241     * @param ast LITERAL_NEW ast.
242     */
243    private void processLiteralNew(DetailAST ast) {
244        if (ast.findFirstToken(TokenTypes.OBJBLOCK) != null) {
245            final FieldFrame frame = new FieldFrame(currentFrame);
246            currentFrame.addChild(frame);
247            currentFrame = frame;
248        }
249    }
250
251    /**
252     * Traverse the tree of the field frames to check all equals method calls.
253     * @param frame to check method calls in.
254     */
255    private void traverseFieldFrameTree(FieldFrame frame) {
256        for (FieldFrame child: frame.getChildren()) {
257            if (!child.getChildren().isEmpty()) {
258                traverseFieldFrameTree(child);
259            }
260            currentFrame = child;
261            child.getMethodCalls().forEach(this::checkMethodCall);
262        }
263    }
264
265    /**
266     * Check whether the method call should be violated.
267     * @param methodCall method call to check.
268     */
269    private void checkMethodCall(DetailAST methodCall) {
270        DetailAST objCalledOn = methodCall.getFirstChild().getFirstChild();
271        if (objCalledOn.getType() == TokenTypes.DOT) {
272            objCalledOn = objCalledOn.getLastChild();
273        }
274        final DetailAST expr = methodCall.findFirstToken(TokenTypes.ELIST).getFirstChild();
275        if (isObjectValid(objCalledOn)
276                && containsOneArgument(methodCall)
277                && containsAllSafeTokens(expr)
278                && isCalledOnStringFieldOrVariable(objCalledOn)) {
279            final String methodName = methodCall.getFirstChild().getLastChild().getText();
280            if (EQUALS.equals(methodName)) {
281                log(methodCall, MSG_EQUALS_AVOID_NULL);
282            }
283            else {
284                log(methodCall, MSG_EQUALS_IGNORE_CASE_AVOID_NULL);
285            }
286        }
287    }
288
289    /**
290     * Check whether the object equals method is called on is not a String literal
291     * and not too complex.
292     * @param objCalledOn the object equals method is called on ast.
293     * @return true if the object is valid.
294     */
295    private static boolean isObjectValid(DetailAST objCalledOn) {
296        boolean result = true;
297        final DetailAST previousSibling = objCalledOn.getPreviousSibling();
298        if (previousSibling != null
299                && previousSibling.getType() == TokenTypes.DOT) {
300            result = false;
301        }
302        if (isStringLiteral(objCalledOn)) {
303            result = false;
304        }
305        return result;
306    }
307
308    /**
309     * Checks for calling equals on String literal and
310     * anon object which cannot be null.
311     * @param objCalledOn object AST
312     * @return if it is string literal
313     */
314    private static boolean isStringLiteral(DetailAST objCalledOn) {
315        return objCalledOn.getType() == TokenTypes.STRING_LITERAL
316                || objCalledOn.getType() == TokenTypes.LITERAL_NEW;
317    }
318
319    /**
320     * Verify that method call has one argument.
321     *
322     * @param methodCall METHOD_CALL DetailAST
323     * @return true if method call has one argument.
324     */
325    private static boolean containsOneArgument(DetailAST methodCall) {
326        final DetailAST elist = methodCall.findFirstToken(TokenTypes.ELIST);
327        return elist.getChildCount() == 1;
328    }
329
330    /**
331     * Looks for all "safe" Token combinations in the argument
332     * expression branch.
333     * @param expr the argument expression
334     * @return - true if any child matches the set of tokens, false if not
335     */
336    private static boolean containsAllSafeTokens(final DetailAST expr) {
337        DetailAST arg = expr.getFirstChild();
338        arg = skipVariableAssign(arg);
339
340        boolean argIsNotNull = false;
341        if (arg.getType() == TokenTypes.PLUS) {
342            DetailAST child = arg.getFirstChild();
343            while (child != null
344                    && !argIsNotNull) {
345                argIsNotNull = child.getType() == TokenTypes.STRING_LITERAL
346                        || child.getType() == TokenTypes.IDENT;
347                child = child.getNextSibling();
348            }
349        }
350
351        return argIsNotNull
352                || !arg.branchContains(TokenTypes.IDENT)
353                    && !arg.branchContains(TokenTypes.LITERAL_NULL);
354    }
355
356    /**
357     * Skips over an inner assign portion of an argument expression.
358     * @param currentAST current token in the argument expression
359     * @return the next relevant token
360     */
361    private static DetailAST skipVariableAssign(final DetailAST currentAST) {
362        DetailAST result = currentAST;
363        if (currentAST.getType() == TokenTypes.ASSIGN
364                && currentAST.getFirstChild().getType() == TokenTypes.IDENT) {
365            result = currentAST.getFirstChild().getNextSibling();
366        }
367        return result;
368    }
369
370    /**
371     * Determine, whether equals method is called on a field of String type.
372     * @param objCalledOn object ast.
373     * @return true if the object is of String type.
374     */
375    private boolean isCalledOnStringFieldOrVariable(DetailAST objCalledOn) {
376        final boolean result;
377        final DetailAST previousSiblingAst = objCalledOn.getPreviousSibling();
378        if (previousSiblingAst == null) {
379            result = isStringFieldOrVariable(objCalledOn);
380        }
381        else {
382            if (previousSiblingAst.getType() == TokenTypes.LITERAL_THIS) {
383                result = isStringFieldOrVariableFromThisInstance(objCalledOn);
384            }
385            else {
386                final String className = previousSiblingAst.getText();
387                result = isStringFieldOrVariableFromClass(objCalledOn, className);
388            }
389        }
390        return result;
391    }
392
393    /**
394     * Whether the field or the variable is of String type.
395     * @param objCalledOn the field or the variable to check.
396     * @return true if the field or the variable is of String type.
397     */
398    private boolean isStringFieldOrVariable(DetailAST objCalledOn) {
399        boolean result = false;
400        final String name = objCalledOn.getText();
401        FieldFrame frame = currentFrame;
402        while (frame != null) {
403            final DetailAST field = frame.findField(name);
404            if (field != null
405                    && (frame.isClassOrEnumOrEnumConstDef()
406                            || checkLineNo(field, objCalledOn))) {
407                result = STRING.equals(getFieldType(field));
408                break;
409            }
410            frame = frame.getParent();
411        }
412        return result;
413    }
414
415    /**
416     * Whether the field or the variable from THIS instance is of String type.
417     * @param objCalledOn the field or the variable from THIS instance to check.
418     * @return true if the field or the variable from THIS instance is of String type.
419     */
420    private boolean isStringFieldOrVariableFromThisInstance(DetailAST objCalledOn) {
421        boolean result = false;
422        final String name = objCalledOn.getText();
423        final DetailAST field = getObjectFrame(currentFrame).findField(name);
424        if (field != null) {
425            result = STRING.equals(getFieldType(field));
426        }
427        return result;
428    }
429
430    /**
431     * Whether the field or the variable from the specified class is of String type.
432     * @param objCalledOn the field or the variable from the specified class to check.
433     * @param className the name of the class to check in.
434     * @return true if the field or the variable from the specified class is of String type.
435     */
436    private boolean isStringFieldOrVariableFromClass(DetailAST objCalledOn,
437            final String className) {
438        boolean result = false;
439        final String name = objCalledOn.getText();
440        FieldFrame frame = getObjectFrame(currentFrame);
441        while (frame != null) {
442            if (className.equals(frame.getFrameName())) {
443                final DetailAST field = frame.findField(name);
444                if (field != null) {
445                    result = STRING.equals(getFieldType(field));
446                }
447                break;
448            }
449            frame = getObjectFrame(frame.getParent());
450        }
451        return result;
452    }
453
454    /**
455     * Get the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.
456     * @param frame to start the search from.
457     * @return the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.
458     */
459    private static FieldFrame getObjectFrame(FieldFrame frame) {
460        FieldFrame objectFrame = frame;
461        while (objectFrame != null && !objectFrame.isClassOrEnumOrEnumConstDef()) {
462            objectFrame = objectFrame.getParent();
463        }
464        return objectFrame;
465    }
466
467    /**
468     * Check whether the field is declared before the method call in case of
469     * methods and initialization blocks.
470     * @param field field to check.
471     * @param objCalledOn object equals method called on.
472     * @return true if the field is declared before the method call.
473     */
474    private static boolean checkLineNo(DetailAST field, DetailAST objCalledOn) {
475        boolean result = false;
476        // Required for pitest coverage. We should specify columnNo passing condition
477        // in such a way, so that the minimal possible distance between field and
478        // objCalledOn will be the maximal condition to pass this check.
479        // The minimal distance between objCalledOn and field (of type String) initialization
480        // is calculated as follows:
481        // String(6) + space(1) + variableName(1) + assign(1) +
482        // anotherStringVariableName(1) + semicolon(1) = 11
483        // Example: length of "String s=d;" is 11 symbols.
484        final int minimumSymbolsBetween = 11;
485        if (field.getLineNo() < objCalledOn.getLineNo()
486                || field.getLineNo() == objCalledOn.getLineNo()
487                    && field.getColumnNo() + minimumSymbolsBetween <= objCalledOn.getColumnNo()) {
488            result = true;
489        }
490        return result;
491    }
492
493    /**
494     * Get field type.
495     * @param field to get the type from.
496     * @return type of the field.
497     */
498    private static String getFieldType(DetailAST field) {
499        String fieldType = null;
500        final DetailAST identAst = field.findFirstToken(TokenTypes.TYPE)
501                .findFirstToken(TokenTypes.IDENT);
502        if (identAst != null) {
503            fieldType = identAst.getText();
504        }
505        return fieldType;
506    }
507
508    /**
509     * Holds the names of fields of a type.
510     */
511    private static class FieldFrame {
512
513        /** Parent frame. */
514        private final FieldFrame parent;
515
516        /** Set of frame's children. */
517        private final Set<FieldFrame> children = new HashSet<>();
518
519        /** Set of fields. */
520        private final Set<DetailAST> fields = new HashSet<>();
521
522        /** Set of equals calls. */
523        private final Set<DetailAST> methodCalls = new HashSet<>();
524
525        /** Name of the class, enum or enum constant declaration. */
526        private String frameName;
527
528        /** Whether the frame is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF. */
529        private boolean classOrEnumOrEnumConstDef;
530
531        /**
532         * Creates new frame.
533         * @param parent parent frame.
534         */
535        FieldFrame(FieldFrame parent) {
536            this.parent = parent;
537        }
538
539        /**
540         * Set the frame name.
541         * @param frameName value to set.
542         */
543        public void setFrameName(String frameName) {
544            this.frameName = frameName;
545        }
546
547        /**
548         * Getter for the frame name.
549         * @return frame name.
550         */
551        public String getFrameName() {
552            return frameName;
553        }
554
555        /**
556         * Getter for the parent frame.
557         * @return parent frame.
558         */
559        public FieldFrame getParent() {
560            return parent;
561        }
562
563        /**
564         * Getter for frame's children.
565         * @return children of this frame.
566         */
567        public Set<FieldFrame> getChildren() {
568            return Collections.unmodifiableSet(children);
569        }
570
571        /**
572         * Add child frame to this frame.
573         * @param child frame to add.
574         */
575        public void addChild(FieldFrame child) {
576            children.add(child);
577        }
578
579        /**
580         * Add field to this FieldFrame.
581         * @param field the ast of the field.
582         */
583        public void addField(DetailAST field) {
584            fields.add(field);
585        }
586
587        /**
588         * Sets isClassOrEnum.
589         * @param value value to set.
590         */
591        public void setClassOrEnumOrEnumConstDef(boolean value) {
592            classOrEnumOrEnumConstDef = value;
593        }
594
595        /**
596         * Getter for classOrEnumOrEnumConstDef.
597         * @return classOrEnumOrEnumConstDef.
598         */
599        public boolean isClassOrEnumOrEnumConstDef() {
600            return classOrEnumOrEnumConstDef;
601        }
602
603        /**
604         * Add method call to this frame.
605         * @param methodCall METHOD_CALL ast.
606         */
607        public void addMethodCall(DetailAST methodCall) {
608            methodCalls.add(methodCall);
609        }
610
611        /**
612         * Determines whether this FieldFrame contains the field.
613         * @param name name of the field to check.
614         * @return true if this FieldFrame contains instance field field.
615         */
616        public DetailAST findField(String name) {
617            DetailAST resultField = null;
618            for (DetailAST field: fields) {
619                if (getFieldName(field).equals(name)) {
620                    resultField = field;
621                    break;
622                }
623            }
624            return resultField;
625        }
626
627        /**
628         * Getter for frame's method calls.
629         * @return method calls of this frame.
630         */
631        public Set<DetailAST> getMethodCalls() {
632            return Collections.unmodifiableSet(methodCalls);
633        }
634
635        /**
636         * Get the name of the field.
637         * @param field to get the name from.
638         * @return name of the field.
639         */
640        private static String getFieldName(DetailAST field) {
641            return field.findFirstToken(TokenTypes.IDENT).getText();
642        }
643
644    }
645
646}