001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2022 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.design;
021
022import java.util.Arrays;
023import java.util.Objects;
024import java.util.Optional;
025import java.util.Set;
026import java.util.function.Predicate;
027import java.util.regex.Matcher;
028import java.util.regex.Pattern;
029import java.util.stream.Collectors;
030
031import com.puppycrawl.tools.checkstyle.StatelessCheck;
032import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
033import com.puppycrawl.tools.checkstyle.api.DetailAST;
034import com.puppycrawl.tools.checkstyle.api.Scope;
035import com.puppycrawl.tools.checkstyle.api.TokenTypes;
036import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
037import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
038import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
039
040/**
041 * <p>
042 * Checks that classes are designed for extension (subclass creation).
043 * </p>
044 * <p>
045 * Nothing wrong could be with founded classes.
046 * This check makes sense only for library projects (not application projects)
047 * which care of ideal OOP-design to make sure that class works in all cases even misusage.
048 * Even in library projects this check most likely will find classes that are designed for extension
049 * by somebody. User needs to use suppressions extensively to got a benefit from this check,
050 * and keep in suppressions all confirmed/known classes that are deigned for inheritance
051 * intentionally to let the check catch only new classes, and bring this to team/user attention.
052 * </p>
053 *
054 * <p>
055 * ATTENTION: Only user can decide whether a class is designed for extension or not.
056 * The check just shows all classes which are possibly designed for extension.
057 * If smth inappropriate is found please use suppression.
058 * </p>
059 *
060 * <p>
061 * ATTENTION: If the method which can be overridden in a subclass has a javadoc comment
062 * (a good practice is to explain its self-use of overridable methods) the check will not
063 * rise a violation. The violation can also be skipped if the method which can be overridden
064 * in a subclass has one or more annotations that are specified in ignoredAnnotations
065 * option. Note, that by default @Override annotation is not included in the
066 * ignoredAnnotations set as in a subclass the method which has the annotation can also be
067 * overridden in its subclass.
068 * </p>
069 * <p>
070 * Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter
071 * "Item 17: Design and document for inheritance or else prohibit it".
072 * </p>
073 * <p>
074 * Some quotes from book:
075 * </p>
076 * <blockquote>The class must document its self-use of overridable methods.
077 * By convention, a method that invokes overridable methods contains a description
078 * of these invocations at the end of its documentation comment. The description
079 * begins with the phrase “This implementation.”
080 * </blockquote>
081 * <blockquote>
082 * The best solution to this problem is to prohibit subclassing in classes that
083 * are not designed and documented to be safely subclassed.
084 * </blockquote>
085 * <blockquote>
086 * If a concrete class does not implement a standard interface, then you may
087 * inconvenience some programmers by prohibiting inheritance. If you feel that you
088 * must allow inheritance from such a class, one reasonable approach is to ensure
089 * that the class never invokes any of its overridable methods and to document this
090 * fact. In other words, eliminate the class’s self-use of overridable methods entirely.
091 * In doing so, you’ll create a class that is reasonably safe to subclass. Overriding a
092 * method will never affect the behavior of any other method.
093 * </blockquote>
094 * <p>
095 * The check finds classes that have overridable methods (public or protected methods
096 * that are non-static, not-final, non-abstract) and have non-empty implementation.
097 * </p>
098 * <p>
099 * Rationale: This library design style protects superclasses against being broken
100 * by subclasses. The downside is that subclasses are limited in their flexibility,
101 * in particular they cannot prevent execution of code in the superclass, but that
102 * also means that subclasses cannot corrupt the state of the superclass by forgetting
103 * to call the superclass's method.
104 * </p>
105 * <p>
106 * More specifically, it enforces a programming style where superclasses provide
107 * empty "hooks" that can be implemented by subclasses.
108 * </p>
109 * <p>
110 * Example of code that cause violation as it is designed for extension:
111 * </p>
112 * <pre>
113 * public abstract class Plant {
114 *   private String roots;
115 *   private String trunk;
116 *
117 *   protected void validate() {
118 *     if (roots == null) throw new IllegalArgumentException("No roots!");
119 *     if (trunk == null) throw new IllegalArgumentException("No trunk!");
120 *   }
121 *
122 *   public abstract void grow();
123 * }
124 *
125 * public class Tree extends Plant {
126 *   private List leaves;
127 *
128 *   &#64;Overrides
129 *   protected void validate() {
130 *     super.validate();
131 *     if (leaves == null) throw new IllegalArgumentException("No leaves!");
132 *   }
133 *
134 *   public void grow() {
135 *     validate();
136 *   }
137 * }
138 * </pre>
139 * <p>
140 * Example of code without violation:
141 * </p>
142 * <pre>
143 * public abstract class Plant {
144 *   private String roots;
145 *   private String trunk;
146 *
147 *   private void validate() {
148 *     if (roots == null) throw new IllegalArgumentException("No roots!");
149 *     if (trunk == null) throw new IllegalArgumentException("No trunk!");
150 *     validateEx();
151 *   }
152 *
153 *   protected void validateEx() { }
154 *
155 *   public abstract void grow();
156 * }
157 * </pre>
158 * <ul>
159 * <li>
160 * Property {@code ignoredAnnotations} - Specify annotations which allow the check to
161 * skip the method from validation.
162 * Type is {@code java.lang.String[]}.
163 * Default value is {@code After, AfterClass, Before, BeforeClass, Test}.
164 * </li>
165 * <li>
166 * Property {@code requiredJavadocPhrase} - Specify the comment text pattern which qualifies a
167 * method as designed for extension. Supports multi-line regex.
168 * Type is {@code java.util.regex.Pattern}.
169 * Default value is {@code ".*"}.
170 * </li>
171 * </ul>
172 * <p>
173 * To configure the check:
174 * </p>
175 * <pre>
176 * &lt;module name=&quot;DesignForExtension&quot;/&gt;
177 * </pre>
178 * <p>
179 * To configure the check to allow methods which have @Override and @Test annotations
180 * to be designed for extension.
181 * </p>
182 * <pre>
183 * &lt;module name=&quot;DesignForExtension&quot;&gt;
184 *   &lt;property name=&quot;ignoredAnnotations&quot; value=&quot;Override, Test&quot;/&gt;
185 * &lt;/module&gt;
186 * </pre>
187 * <pre>
188 * public class A {
189 *   &#64;Override
190 *   public int foo() {
191 *     return 2;
192 *   }
193 *
194 *   public int foo2() {return 8;} // violation
195 * }
196 *
197 * public class B {
198 *   &#47;**
199 *    * This implementation ...
200 *      &#64;return some int value.
201 *    *&#47;
202 *   public int foo() {
203 *     return 1;
204 *   }
205 *
206 *   public int foo3() {return 3;} // violation
207 * }
208 *
209 * public class FooTest {
210 *   &#64;Test
211 *   public void testFoo() {
212 *     final B b = new A();
213 *     assertEquals(2, b.foo());
214 *   }
215 *
216 *   public int foo4() {return 4;} // violation
217 * }
218 * </pre>
219 * <p>
220 * To configure the check to allow methods which contain a specified comment text
221 * pattern in their javadoc to be designed for extension.
222 * </p>
223 * <pre>
224 * &lt;module name=&quot;DesignForExtension&quot;&gt;
225 *   &lt;property name=&quot;requiredJavadocPhrase&quot;
226 *     value=&quot;This implementation&quot;/&gt;
227 * &lt;/module&gt;
228 * </pre>
229 * <pre>
230 * public class A {
231 *   /&#42;&#42;
232 *   &#42; This implementation ...
233 *   &#42;/
234 *   public int foo() {return 2;} // ok, required javadoc phrase in comment
235 *
236 *   /&#42;&#42;
237 *   &#42; Do not extend ...
238 *   &#42;/
239 *   public int foo2() {return 8;} // violation, required javadoc phrase not in comment
240 *
241 *   public int foo3() {return 3;} // violation, required javadoc phrase not in comment
242 * }
243 * </pre>
244 * <p>
245 * To configure the check to allow methods which contain a specified comment text
246 * pattern in their javadoc which can span multiple lines
247 * to be designed for extension.
248 * </p>
249 * <pre>
250 * &lt;module name=&quot;DesignForExtension&quot;&gt;
251 *   &lt;property name=&quot;requiredJavadocPhrase&quot;
252 *     value=&quot;This[\s\S]*implementation&quot;/&gt;
253 * &lt;/module&gt;
254 * </pre>
255 * <pre>
256 * public class A {
257 *   /&#42;&#42;
258 *   &#42; This
259 *   &#42; implementation ...
260 *   &#42;/
261 *   public int foo() {return 2;} // ok, required javadoc phrase in comment
262 *
263 *   /&#42;&#42;
264 *   &#42; Do not extend ...
265 *   &#42;/
266 *   public int foo2() {return 8;} // violation, required javadoc phrase not in comment
267 *
268 *   public int foo3() {return 3;} // violation, required javadoc phrase not in comment
269 * }
270 * </pre>
271 * <p>
272 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
273 * </p>
274 * <p>
275 * Violation Message Keys:
276 * </p>
277 * <ul>
278 * <li>
279 * {@code design.forExtension}
280 * </li>
281 * </ul>
282 *
283 * @since 3.1
284 */
285@StatelessCheck
286public class DesignForExtensionCheck extends AbstractCheck {
287
288    /**
289     * A key is pointing to the warning message text in "messages.properties"
290     * file.
291     */
292    public static final String MSG_KEY = "design.forExtension";
293
294    /**
295     * Specify annotations which allow the check to skip the method from validation.
296     */
297    private Set<String> ignoredAnnotations = Arrays.stream(new String[] {"Test", "Before", "After",
298        "BeforeClass", "AfterClass", }).collect(Collectors.toSet());
299
300    /**
301     * Specify the comment text pattern which qualifies a method as designed for extension.
302     * Supports multi-line regex.
303     */
304    private Pattern requiredJavadocPhrase = Pattern.compile(".*");
305
306    /**
307     * Setter to specify annotations which allow the check to skip the method from validation.
308     *
309     * @param ignoredAnnotations method annotations.
310     */
311    public void setIgnoredAnnotations(String... ignoredAnnotations) {
312        this.ignoredAnnotations = Arrays.stream(ignoredAnnotations).collect(Collectors.toSet());
313    }
314
315    /**
316     * Setter to specify the comment text pattern which qualifies a
317     * method as designed for extension. Supports multi-line regex.
318     *
319     * @param requiredJavadocPhrase method annotations.
320     */
321    public void setRequiredJavadocPhrase(Pattern requiredJavadocPhrase) {
322        this.requiredJavadocPhrase = requiredJavadocPhrase;
323    }
324
325    @Override
326    public int[] getDefaultTokens() {
327        return getRequiredTokens();
328    }
329
330    @Override
331    public int[] getAcceptableTokens() {
332        return getRequiredTokens();
333    }
334
335    @Override
336    public int[] getRequiredTokens() {
337        // The check does not subscribe to CLASS_DEF token as now it is stateless. If the check
338        // subscribes to CLASS_DEF token it will become stateful, since we need to have additional
339        // stack to hold CLASS_DEF tokens.
340        return new int[] {TokenTypes.METHOD_DEF};
341    }
342
343    @Override
344    public boolean isCommentNodesRequired() {
345        return true;
346    }
347
348    @Override
349    public void visitToken(DetailAST ast) {
350        if (!hasJavadocComment(ast)
351                && canBeOverridden(ast)
352                && (isNativeMethod(ast)
353                    || !hasEmptyImplementation(ast))
354                && !hasIgnoredAnnotation(ast, ignoredAnnotations)
355                && !ScopeUtil.isInRecordBlock(ast)) {
356            final DetailAST classDef = getNearestClassOrEnumDefinition(ast);
357            if (canBeSubclassed(classDef)) {
358                final String className = classDef.findFirstToken(TokenTypes.IDENT).getText();
359                final String methodName = ast.findFirstToken(TokenTypes.IDENT).getText();
360                log(ast, MSG_KEY, className, methodName);
361            }
362        }
363    }
364
365    /**
366     * Checks whether a method has a javadoc comment.
367     *
368     * @param methodDef method definition token.
369     * @return true if a method has a javadoc comment.
370     */
371    private boolean hasJavadocComment(DetailAST methodDef) {
372        return hasJavadocCommentOnToken(methodDef, TokenTypes.MODIFIERS)
373                || hasJavadocCommentOnToken(methodDef, TokenTypes.TYPE);
374    }
375
376    /**
377     * Checks whether a token has a javadoc comment.
378     *
379     * @param methodDef method definition token.
380     * @param tokenType token type.
381     * @return true if a token has a javadoc comment.
382     */
383    private boolean hasJavadocCommentOnToken(DetailAST methodDef, int tokenType) {
384        final DetailAST token = methodDef.findFirstToken(tokenType);
385        return branchContainsJavadocComment(token);
386    }
387
388    /**
389     * Checks whether a javadoc comment exists under the token.
390     *
391     * @param token tree token.
392     * @return true if a javadoc comment exists under the token.
393     */
394    private boolean branchContainsJavadocComment(DetailAST token) {
395        boolean result = false;
396        DetailAST curNode = token;
397        while (curNode != null) {
398            if (curNode.getType() == TokenTypes.BLOCK_COMMENT_BEGIN
399                    && JavadocUtil.isJavadocComment(curNode)) {
400                result = hasValidJavadocComment(curNode);
401                break;
402            }
403
404            DetailAST toVisit = curNode.getFirstChild();
405            while (toVisit == null) {
406                if (curNode == token) {
407                    break;
408                }
409
410                toVisit = curNode.getNextSibling();
411                curNode = curNode.getParent();
412            }
413            curNode = toVisit;
414        }
415
416        return result;
417    }
418
419    /**
420     * Checks whether a javadoc contains the specified comment pattern that denotes
421     * a method as designed for extension.
422     *
423     * @param detailAST the ast we are checking for possible extension
424     * @return true if the javadoc of this ast contains the required comment pattern
425     */
426    private boolean hasValidJavadocComment(DetailAST detailAST) {
427        final String javadocString =
428            JavadocUtil.getBlockCommentContent(detailAST);
429
430        final Matcher requiredJavadocPhraseMatcher =
431            requiredJavadocPhrase.matcher(javadocString);
432
433        return requiredJavadocPhraseMatcher.find();
434    }
435
436    /**
437     * Checks whether a method is native.
438     *
439     * @param ast method definition token.
440     * @return true if a methods is native.
441     */
442    private static boolean isNativeMethod(DetailAST ast) {
443        final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS);
444        return mods.findFirstToken(TokenTypes.LITERAL_NATIVE) != null;
445    }
446
447    /**
448     * Checks whether a method has only comments in the body (has an empty implementation).
449     * Method is OK if its implementation is empty.
450     *
451     * @param ast method definition token.
452     * @return true if a method has only comments in the body.
453     */
454    private static boolean hasEmptyImplementation(DetailAST ast) {
455        boolean hasEmptyBody = true;
456        final DetailAST methodImplOpenBrace = ast.findFirstToken(TokenTypes.SLIST);
457        final DetailAST methodImplCloseBrace = methodImplOpenBrace.getLastChild();
458        final Predicate<DetailAST> predicate = currentNode -> {
459            return currentNode != methodImplCloseBrace
460                && !TokenUtil.isCommentType(currentNode.getType());
461        };
462        final Optional<DetailAST> methodBody =
463            TokenUtil.findFirstTokenByPredicate(methodImplOpenBrace, predicate);
464        if (methodBody.isPresent()) {
465            hasEmptyBody = false;
466        }
467        return hasEmptyBody;
468    }
469
470    /**
471     * Checks whether a method can be overridden.
472     * Method can be overridden if it is not private, abstract, final or static.
473     * Note that the check has nothing to do for interfaces.
474     *
475     * @param methodDef method definition token.
476     * @return true if a method can be overridden in a subclass.
477     */
478    private static boolean canBeOverridden(DetailAST methodDef) {
479        final DetailAST modifiers = methodDef.findFirstToken(TokenTypes.MODIFIERS);
480        return ScopeUtil.getSurroundingScope(methodDef).isIn(Scope.PROTECTED)
481            && !ScopeUtil.isInInterfaceOrAnnotationBlock(methodDef)
482            && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null
483            && modifiers.findFirstToken(TokenTypes.ABSTRACT) == null
484            && modifiers.findFirstToken(TokenTypes.FINAL) == null
485            && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null;
486    }
487
488    /**
489     * Checks whether a method has any of ignored annotations.
490     *
491     * @param methodDef method definition token.
492     * @param annotations a set of ignored annotations.
493     * @return true if a method has any of ignored annotations.
494     */
495    private static boolean hasIgnoredAnnotation(DetailAST methodDef, Set<String> annotations) {
496        final DetailAST modifiers = methodDef.findFirstToken(TokenTypes.MODIFIERS);
497        final Optional<DetailAST> annotation = TokenUtil.findFirstTokenByPredicate(modifiers,
498            currentToken -> {
499                return currentToken.getType() == TokenTypes.ANNOTATION
500                    && annotations.contains(getAnnotationName(currentToken));
501            });
502        return annotation.isPresent();
503    }
504
505    /**
506     * Gets the name of the annotation.
507     *
508     * @param annotation to get name of.
509     * @return the name of the annotation.
510     */
511    private static String getAnnotationName(DetailAST annotation) {
512        final DetailAST dotAst = annotation.findFirstToken(TokenTypes.DOT);
513        final DetailAST parent = Objects.requireNonNullElse(dotAst, annotation);
514        return parent.findFirstToken(TokenTypes.IDENT).getText();
515    }
516
517    /**
518     * Returns CLASS_DEF or ENUM_DEF token which is the nearest to the given ast node.
519     * Searches the tree towards the root until it finds a CLASS_DEF or ENUM_DEF node.
520     *
521     * @param ast the start node for searching.
522     * @return the CLASS_DEF or ENUM_DEF token.
523     */
524    private static DetailAST getNearestClassOrEnumDefinition(DetailAST ast) {
525        DetailAST searchAST = ast;
526        while (searchAST.getType() != TokenTypes.CLASS_DEF
527               && searchAST.getType() != TokenTypes.ENUM_DEF) {
528            searchAST = searchAST.getParent();
529        }
530        return searchAST;
531    }
532
533    /**
534     * Checks if the given class (given CLASS_DEF node) can be subclassed.
535     *
536     * @param classDef class definition token.
537     * @return true if the containing class can be subclassed.
538     */
539    private static boolean canBeSubclassed(DetailAST classDef) {
540        final DetailAST modifiers = classDef.findFirstToken(TokenTypes.MODIFIERS);
541        return classDef.getType() != TokenTypes.ENUM_DEF
542            && modifiers.findFirstToken(TokenTypes.FINAL) == null
543            && hasDefaultOrExplicitNonPrivateCtor(classDef);
544    }
545
546    /**
547     * Checks whether a class has default or explicit non-private constructor.
548     *
549     * @param classDef class ast token.
550     * @return true if a class has default or explicit non-private constructor.
551     */
552    private static boolean hasDefaultOrExplicitNonPrivateCtor(DetailAST classDef) {
553        // check if subclassing is prevented by having only private ctors
554        final DetailAST objBlock = classDef.findFirstToken(TokenTypes.OBJBLOCK);
555
556        boolean hasDefaultConstructor = true;
557        boolean hasExplicitNonPrivateCtor = false;
558
559        DetailAST candidate = objBlock.getFirstChild();
560
561        while (candidate != null) {
562            if (candidate.getType() == TokenTypes.CTOR_DEF) {
563                hasDefaultConstructor = false;
564
565                final DetailAST ctorMods =
566                        candidate.findFirstToken(TokenTypes.MODIFIERS);
567                if (ctorMods.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) {
568                    hasExplicitNonPrivateCtor = true;
569                    break;
570                }
571            }
572            candidate = candidate.getNextSibling();
573        }
574
575        return hasDefaultConstructor || hasExplicitNonPrivateCtor;
576    }
577
578}