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