001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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.HashSet;
023import java.util.Locale;
024import java.util.Objects;
025import java.util.Set;
026import java.util.regex.Pattern;
027
028import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
029import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
030import com.puppycrawl.tools.checkstyle.api.DetailAST;
031import com.puppycrawl.tools.checkstyle.api.Scope;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
034import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
035
036/**
037 * <p>
038 * Checks that a local variable or a parameter does not shadow
039 * a field that is defined in the same class.
040 * </p>
041 * <p>
042 * It is possible to configure the check to ignore all property setter methods.
043 * </p>
044 * <p>
045 * A method is recognized as a setter if it is in the following form
046 * </p>
047 * <pre>
048 * ${returnType} set${Name}(${anyType} ${name}) { ... }
049 * </pre>
050 * <p>
051 * where ${anyType} is any primitive type, class or interface name;
052 * ${name} is name of the variable that is being set and ${Name} its
053 * capitalized form that appears in the method name. By default it is expected
054 * that setter returns void, i.e. ${returnType} is 'void'. For example
055 * </p>
056 * <pre>
057 * void setTime(long time) { ... }
058 * </pre>
059 * <p>
060 * Any other return types will not let method match a setter pattern. However,
061 * by setting <em>setterCanReturnItsClass</em> property to <em>true</em>
062 * definition of a setter is expanded, so that setter return type can also be
063 * a class in which setter is declared. For example
064 * </p>
065 * <pre>
066 * class PageBuilder {
067 *   PageBuilder setName(String name) { ... }
068 * }
069 * </pre>
070 * <p>
071 * Such methods are known as chain-setters and a common when Builder-pattern
072 * is used. Property <em>setterCanReturnItsClass</em> has effect only if
073 * <em>ignoreSetter</em> is set to true.
074 * </p>
075 * <ul>
076 * <li>
077 * Property {@code ignoreFormat} - Define the RegExp for names of variables
078 * and parameters to ignore.
079 * Default value is {@code null}.
080 * </li>
081 * <li>
082 * Property {@code ignoreConstructorParameter} - Control whether to ignore constructor parameters.
083 * Default value is {@code false}.
084 * </li>
085 * <li>
086 * Property {@code ignoreSetter} - Allow to ignore the parameter of a property setter method.
087 * Default value is {@code false}.
088 * </li>
089 * <li>
090 * Property {@code setterCanReturnItsClass} - Allow to expand the definition of a setter method
091 * to include methods that return the class' instance.
092 * Default value is {@code false}.
093 * </li>
094 * <li>
095 * Property {@code ignoreAbstractMethods} - Control whether to ignore parameters
096 * of abstract methods.
097 * Default value is {@code false}.
098 * </li>
099 * <li>
100 * Property {@code tokens} - tokens to check
101 * Default value is:
102 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF">
103 * VARIABLE_DEF</a>,
104 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PARAMETER_DEF">
105 * PARAMETER_DEF</a>,
106 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LAMBDA">
107 * LAMBDA</a>.
108 * </li>
109 * </ul>
110 * <p>
111 * To configure the check:
112 * </p>
113 * <pre>
114 *  &lt;module name=&quot;HiddenField&quot;/&gt;
115 * </pre>
116 *
117 * <p>
118 * To configure the check so that it checks local variables but not parameters:
119 * </p>
120 * <pre>
121 * &lt;module name=&quot;HiddenField&quot;&gt;
122 *   &lt;property name=&quot;tokens&quot; value=&quot;VARIABLE_DEF&quot;/&gt;
123 * &lt;/module&gt;
124 * </pre>
125 *
126 * <p>
127 * To configure the check so that it ignores the variables and parameters named "test":
128 * </p>
129 * <pre>
130 * &lt;module name=&quot;HiddenField&quot;&gt;
131 *   &lt;property name=&quot;ignoreFormat&quot; value=&quot;^test$&quot;/&gt;
132 * &lt;/module&gt;
133 * </pre>
134 * <pre>
135 * class SomeClass
136 * {
137 *   private List&lt;String&gt; test;
138 *
139 *   private void addTest(List&lt;String&gt; test) // no violation
140 *   {
141 *     this.test.addAll(test);
142 *   }
143 *
144 *   private void foo()
145 *   {
146 *     final List&lt;String&gt; test = new ArrayList&lt;&gt;(); // no violation
147 *     ...
148 *   }
149 * }
150 * </pre>
151 * <p>
152 * To configure the check so that it ignores constructor parameters:
153 * </p>
154 * <pre>
155 * &lt;module name=&quot;HiddenField&quot;&gt;
156 *   &lt;property name=&quot;ignoreConstructorParameter&quot; value=&quot;true&quot;/&gt;
157 * &lt;/module&gt;
158 * </pre>
159 * <p>
160 * To configure the check so that it ignores the parameter of setter methods:
161 * </p>
162 * <pre>
163 * &lt;module name=&quot;HiddenField&quot;&gt;
164 *   &lt;property name=&quot;ignoreSetter&quot; value=&quot;true&quot;/&gt;
165 * &lt;/module&gt;
166 * </pre>
167 * <p>
168 * To configure the check so that it ignores the parameter of setter methods
169 * recognizing setter as returning either {@code void} or a class in which it is declared:
170 * </p>
171 * <pre>
172 * &lt;module name=&quot;HiddenField&quot;&gt;
173 *   &lt;property name=&quot;ignoreSetter&quot; value=&quot;true&quot;/&gt;
174 *   &lt;property name=&quot;setterCanReturnItsClass&quot; value=&quot;true&quot;/&gt;
175 * &lt;/module&gt;
176 * </pre>
177 *
178 * @since 3.0
179 */
180@FileStatefulCheck
181public class HiddenFieldCheck
182    extends AbstractCheck {
183
184    /**
185     * A key is pointing to the warning message text in "messages.properties"
186     * file.
187     */
188    public static final String MSG_KEY = "hidden.field";
189
190    /**
191     * Stack of sets of field names,
192     * one for each class of a set of nested classes.
193     */
194    private FieldFrame frame;
195
196    /** Define the RegExp for names of variables and parameters to ignore. */
197    private Pattern ignoreFormat;
198
199    /**
200     * Allow to ignore the parameter of a property setter method.
201     */
202    private boolean ignoreSetter;
203
204    /**
205     * Allow to expand the definition of a setter method to include methods
206     * that return the class' instance.
207     */
208    private boolean setterCanReturnItsClass;
209
210    /** Control whether to ignore constructor parameters. */
211    private boolean ignoreConstructorParameter;
212
213    /** Control whether to ignore parameters of abstract methods. */
214    private boolean ignoreAbstractMethods;
215
216    @Override
217    public int[] getDefaultTokens() {
218        return getAcceptableTokens();
219    }
220
221    @Override
222    public int[] getAcceptableTokens() {
223        return new int[] {
224            TokenTypes.VARIABLE_DEF,
225            TokenTypes.PARAMETER_DEF,
226            TokenTypes.CLASS_DEF,
227            TokenTypes.ENUM_DEF,
228            TokenTypes.ENUM_CONSTANT_DEF,
229            TokenTypes.LAMBDA,
230        };
231    }
232
233    @Override
234    public int[] getRequiredTokens() {
235        return new int[] {
236            TokenTypes.CLASS_DEF,
237            TokenTypes.ENUM_DEF,
238            TokenTypes.ENUM_CONSTANT_DEF,
239        };
240    }
241
242    @Override
243    public void beginTree(DetailAST rootAST) {
244        frame = new FieldFrame(null, true, null);
245    }
246
247    @Override
248    public void visitToken(DetailAST ast) {
249        final int type = ast.getType();
250        switch (type) {
251            case TokenTypes.VARIABLE_DEF:
252            case TokenTypes.PARAMETER_DEF:
253                processVariable(ast);
254                break;
255            case TokenTypes.LAMBDA:
256                processLambda(ast);
257                break;
258            default:
259                visitOtherTokens(ast, type);
260        }
261    }
262
263    /**
264     * Process a lambda token.
265     * Checks whether a lambda parameter shadows a field.
266     * Note, that when parameter of lambda expression is untyped,
267     * ANTLR parses the parameter as an identifier.
268     * @param ast the lambda token.
269     */
270    private void processLambda(DetailAST ast) {
271        final DetailAST firstChild = ast.getFirstChild();
272        if (firstChild.getType() == TokenTypes.IDENT) {
273            final String untypedLambdaParameterName = firstChild.getText();
274            if (frame.containsStaticField(untypedLambdaParameterName)
275                || isInstanceField(firstChild, untypedLambdaParameterName)) {
276                log(firstChild, MSG_KEY, untypedLambdaParameterName);
277            }
278        }
279    }
280
281    /**
282     * Called to process tokens other than {@link TokenTypes#VARIABLE_DEF}
283     * and {@link TokenTypes#PARAMETER_DEF}.
284     *
285     * @param ast token to process
286     * @param type type of the token
287     */
288    private void visitOtherTokens(DetailAST ast, int type) {
289        //A more thorough check of enum constant class bodies is
290        //possible (checking for hidden fields against the enum
291        //class body in addition to enum constant class bodies)
292        //but not attempted as it seems out of the scope of this
293        //check.
294        final DetailAST typeMods = ast.findFirstToken(TokenTypes.MODIFIERS);
295        final boolean isStaticInnerType =
296                typeMods != null
297                        && typeMods.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
298        final String frameName;
299
300        if (type == TokenTypes.CLASS_DEF || type == TokenTypes.ENUM_DEF) {
301            frameName = ast.findFirstToken(TokenTypes.IDENT).getText();
302        }
303        else {
304            frameName = null;
305        }
306        final FieldFrame newFrame = new FieldFrame(frame, isStaticInnerType, frameName);
307
308        //add fields to container
309        final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
310        // enum constants may not have bodies
311        if (objBlock != null) {
312            DetailAST child = objBlock.getFirstChild();
313            while (child != null) {
314                if (child.getType() == TokenTypes.VARIABLE_DEF) {
315                    final String name =
316                        child.findFirstToken(TokenTypes.IDENT).getText();
317                    final DetailAST mods =
318                        child.findFirstToken(TokenTypes.MODIFIERS);
319                    if (mods.findFirstToken(TokenTypes.LITERAL_STATIC) == null) {
320                        newFrame.addInstanceField(name);
321                    }
322                    else {
323                        newFrame.addStaticField(name);
324                    }
325                }
326                child = child.getNextSibling();
327            }
328        }
329        // push container
330        frame = newFrame;
331    }
332
333    @Override
334    public void leaveToken(DetailAST ast) {
335        if (ast.getType() == TokenTypes.CLASS_DEF
336            || ast.getType() == TokenTypes.ENUM_DEF
337            || ast.getType() == TokenTypes.ENUM_CONSTANT_DEF) {
338            //pop
339            frame = frame.getParent();
340        }
341    }
342
343    /**
344     * Process a variable token.
345     * Check whether a local variable or parameter shadows a field.
346     * Store a field for later comparison with local variables and parameters.
347     * @param ast the variable token.
348     */
349    private void processVariable(DetailAST ast) {
350        if (!ScopeUtil.isInInterfaceOrAnnotationBlock(ast)
351            && !CheckUtil.isReceiverParameter(ast)
352            && (ScopeUtil.isLocalVariableDef(ast)
353                || ast.getType() == TokenTypes.PARAMETER_DEF)) {
354            // local variable or parameter. Does it shadow a field?
355            final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT);
356            final String name = nameAST.getText();
357
358            if ((frame.containsStaticField(name) || isInstanceField(ast, name))
359                    && !isMatchingRegexp(name)
360                    && !isIgnoredParam(ast, name)) {
361                log(nameAST, MSG_KEY, name);
362            }
363        }
364    }
365
366    /**
367     * Checks whether method or constructor parameter is ignored.
368     * @param ast the parameter token.
369     * @param name the parameter name.
370     * @return true if parameter is ignored.
371     */
372    private boolean isIgnoredParam(DetailAST ast, String name) {
373        return isIgnoredSetterParam(ast, name)
374            || isIgnoredConstructorParam(ast)
375            || isIgnoredParamOfAbstractMethod(ast);
376    }
377
378    /**
379     * Check for instance field.
380     * @param ast token
381     * @param name identifier of token
382     * @return true if instance field
383     */
384    private boolean isInstanceField(DetailAST ast, String name) {
385        return !isInStatic(ast) && frame.containsInstanceField(name);
386    }
387
388    /**
389     * Check name by regExp.
390     * @param name string value to check
391     * @return true is regexp is matching
392     */
393    private boolean isMatchingRegexp(String name) {
394        return ignoreFormat != null && ignoreFormat.matcher(name).find();
395    }
396
397    /**
398     * Determines whether an AST node is in a static method or static
399     * initializer.
400     * @param ast the node to check.
401     * @return true if ast is in a static method or a static block;
402     */
403    private static boolean isInStatic(DetailAST ast) {
404        DetailAST parent = ast.getParent();
405        boolean inStatic = false;
406
407        while (parent != null && !inStatic) {
408            if (parent.getType() == TokenTypes.STATIC_INIT) {
409                inStatic = true;
410            }
411            else if (parent.getType() == TokenTypes.METHOD_DEF
412                        && !ScopeUtil.isInScope(parent, Scope.ANONINNER)
413                        || parent.getType() == TokenTypes.VARIABLE_DEF) {
414                final DetailAST mods =
415                    parent.findFirstToken(TokenTypes.MODIFIERS);
416                inStatic = mods.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
417                break;
418            }
419            else {
420                parent = parent.getParent();
421            }
422        }
423        return inStatic;
424    }
425
426    /**
427     * Decides whether to ignore an AST node that is the parameter of a
428     * setter method, where the property setter method for field 'xyz' has
429     * name 'setXyz', one parameter named 'xyz', and return type void
430     * (default behavior) or return type is name of the class in which
431     * such method is declared (allowed only if
432     * {@link #setSetterCanReturnItsClass(boolean)} is called with
433     * value <em>true</em>).
434     *
435     * @param ast the AST to check.
436     * @param name the name of ast.
437     * @return true if ast should be ignored because check property
438     *     ignoreSetter is true and ast is the parameter of a setter method.
439     */
440    private boolean isIgnoredSetterParam(DetailAST ast, String name) {
441        boolean isIgnoredSetterParam = false;
442        if (ignoreSetter && ast.getType() == TokenTypes.PARAMETER_DEF) {
443            final DetailAST parametersAST = ast.getParent();
444            final DetailAST methodAST = parametersAST.getParent();
445            if (parametersAST.getChildCount() == 1
446                && methodAST.getType() == TokenTypes.METHOD_DEF
447                && isSetterMethod(methodAST, name)) {
448                isIgnoredSetterParam = true;
449            }
450        }
451        return isIgnoredSetterParam;
452    }
453
454    /**
455     * Determine if a specific method identified by methodAST and a single
456     * variable name aName is a setter. This recognition partially depends
457     * on mSetterCanReturnItsClass property.
458     *
459     * @param aMethodAST AST corresponding to a method call
460     * @param aName name of single parameter of this method.
461     * @return true of false indicating of method is a setter or not.
462     */
463    private boolean isSetterMethod(DetailAST aMethodAST, String aName) {
464        final String methodName =
465            aMethodAST.findFirstToken(TokenTypes.IDENT).getText();
466        boolean isSetterMethod = false;
467
468        if (("set" + capitalize(aName)).equals(methodName)) {
469            // method name did match set${Name}(${anyType} ${aName})
470            // where ${Name} is capitalized version of ${aName}
471            // therefore this method is potentially a setter
472            final DetailAST typeAST = aMethodAST.findFirstToken(TokenTypes.TYPE);
473            final String returnType = typeAST.getFirstChild().getText();
474            if (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) != null
475                    || setterCanReturnItsClass && frame.isEmbeddedIn(returnType)) {
476                // this method has signature
477                //
478                //     void set${Name}(${anyType} ${name})
479                //
480                // and therefore considered to be a setter
481                //
482                // or
483                //
484                // return type is not void, but it is the same as the class
485                // where method is declared and and mSetterCanReturnItsClass
486                // is set to true
487                isSetterMethod = true;
488            }
489        }
490
491        return isSetterMethod;
492    }
493
494    /**
495     * Capitalizes a given property name the way we expect to see it in
496     * a setter name.
497     * @param name a property name
498     * @return capitalized property name
499     */
500    private static String capitalize(final String name) {
501        String setterName = name;
502        // we should not capitalize the first character if the second
503        // one is a capital one, since according to JavaBeans spec
504        // setXYzz() is a setter for XYzz property, not for xYzz one.
505        if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) {
506            setterName = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1);
507        }
508        return setterName;
509    }
510
511    /**
512     * Decides whether to ignore an AST node that is the parameter of a
513     * constructor.
514     * @param ast the AST to check.
515     * @return true if ast should be ignored because check property
516     *     ignoreConstructorParameter is true and ast is a constructor parameter.
517     */
518    private boolean isIgnoredConstructorParam(DetailAST ast) {
519        boolean result = false;
520        if (ignoreConstructorParameter
521                && ast.getType() == TokenTypes.PARAMETER_DEF) {
522            final DetailAST parametersAST = ast.getParent();
523            final DetailAST constructorAST = parametersAST.getParent();
524            result = constructorAST.getType() == TokenTypes.CTOR_DEF;
525        }
526        return result;
527    }
528
529    /**
530     * Decides whether to ignore an AST node that is the parameter of an
531     * abstract method.
532     * @param ast the AST to check.
533     * @return true if ast should be ignored because check property
534     *     ignoreAbstractMethods is true and ast is a parameter of abstract methods.
535     */
536    private boolean isIgnoredParamOfAbstractMethod(DetailAST ast) {
537        boolean result = false;
538        if (ignoreAbstractMethods
539                && ast.getType() == TokenTypes.PARAMETER_DEF) {
540            final DetailAST method = ast.getParent().getParent();
541            if (method.getType() == TokenTypes.METHOD_DEF) {
542                final DetailAST mods = method.findFirstToken(TokenTypes.MODIFIERS);
543                result = mods.findFirstToken(TokenTypes.ABSTRACT) != null;
544            }
545        }
546        return result;
547    }
548
549    /**
550     * Setter to define the RegExp for names of variables and parameters to ignore.
551     * @param pattern a pattern.
552     */
553    public void setIgnoreFormat(Pattern pattern) {
554        ignoreFormat = pattern;
555    }
556
557    /**
558     * Setter to allow to ignore the parameter of a property setter method.
559     * @param ignoreSetter decide whether to ignore the parameter of
560     *     a property setter method.
561     */
562    public void setIgnoreSetter(boolean ignoreSetter) {
563        this.ignoreSetter = ignoreSetter;
564    }
565
566    /**
567     * Setter to allow to expand the definition of a setter method to include methods
568     * that return the class' instance.
569     *
570     * @param aSetterCanReturnItsClass if true then setter can return
571     *        either void or class in which it is declared. If false then
572     *        in order to be recognized as setter method (otherwise
573     *        already recognized as a setter) must return void.  Later is
574     *        the default behavior.
575     */
576    public void setSetterCanReturnItsClass(
577        boolean aSetterCanReturnItsClass) {
578        setterCanReturnItsClass = aSetterCanReturnItsClass;
579    }
580
581    /**
582     * Setter to control whether to ignore constructor parameters.
583     * @param ignoreConstructorParameter decide whether to ignore
584     *     constructor parameters.
585     */
586    public void setIgnoreConstructorParameter(
587        boolean ignoreConstructorParameter) {
588        this.ignoreConstructorParameter = ignoreConstructorParameter;
589    }
590
591    /**
592     * Setter to control whether to ignore parameters of abstract methods.
593     * @param ignoreAbstractMethods decide whether to ignore
594     *     parameters of abstract methods.
595     */
596    public void setIgnoreAbstractMethods(
597        boolean ignoreAbstractMethods) {
598        this.ignoreAbstractMethods = ignoreAbstractMethods;
599    }
600
601    /**
602     * Holds the names of static and instance fields of a type.
603     */
604    private static class FieldFrame {
605
606        /** Name of the frame, such name of the class or enum declaration. */
607        private final String frameName;
608
609        /** Is this a static inner type. */
610        private final boolean staticType;
611
612        /** Parent frame. */
613        private final FieldFrame parent;
614
615        /** Set of instance field names. */
616        private final Set<String> instanceFields = new HashSet<>();
617
618        /** Set of static field names. */
619        private final Set<String> staticFields = new HashSet<>();
620
621        /**
622         * Creates new frame.
623         * @param parent parent frame.
624         * @param staticType is this a static inner type (class or enum).
625         * @param frameName name associated with the frame, which can be a
626         */
627        /* package */ FieldFrame(FieldFrame parent, boolean staticType, String frameName) {
628            this.parent = parent;
629            this.staticType = staticType;
630            this.frameName = frameName;
631        }
632
633        /**
634         * Adds an instance field to this FieldFrame.
635         * @param field  the name of the instance field.
636         */
637        public void addInstanceField(String field) {
638            instanceFields.add(field);
639        }
640
641        /**
642         * Adds a static field to this FieldFrame.
643         * @param field  the name of the instance field.
644         */
645        public void addStaticField(String field) {
646            staticFields.add(field);
647        }
648
649        /**
650         * Determines whether this FieldFrame contains an instance field.
651         * @param field the field to check.
652         * @return true if this FieldFrame contains instance field field.
653         */
654        public boolean containsInstanceField(String field) {
655            return instanceFields.contains(field)
656                    || parent != null
657                    && !staticType
658                    && parent.containsInstanceField(field);
659        }
660
661        /**
662         * Determines whether this FieldFrame contains a static field.
663         * @param field the field to check.
664         * @return true if this FieldFrame contains static field field.
665         */
666        public boolean containsStaticField(String field) {
667            return staticFields.contains(field)
668                    || parent != null
669                    && parent.containsStaticField(field);
670        }
671
672        /**
673         * Getter for parent frame.
674         * @return parent frame.
675         */
676        public FieldFrame getParent() {
677            return parent;
678        }
679
680        /**
681         * Check if current frame is embedded in class or enum with
682         * specific name.
683         *
684         * @param classOrEnumName name of class or enum that we are looking
685         *     for in the chain of field frames.
686         *
687         * @return true if current frame is embedded in class or enum
688         *     with name classOrNameName
689         */
690        private boolean isEmbeddedIn(String classOrEnumName) {
691            FieldFrame currentFrame = this;
692            boolean isEmbeddedIn = false;
693            while (currentFrame != null) {
694                if (Objects.equals(currentFrame.frameName, classOrEnumName)) {
695                    isEmbeddedIn = true;
696                    break;
697                }
698                currentFrame = currentFrame.parent;
699            }
700            return isEmbeddedIn;
701        }
702
703    }
704
705}