View Javadoc
1   /*
2    * Copyright (c) 2011-2024 Qulice.com
3    *
4    * All rights reserved.
5    *
6    * Redistribution and use in source and binary forms, with or without
7    * modification, are permitted provided that the following conditions
8    * are met: 1) Redistributions of source code must retain the above
9    * copyright notice, this list of conditions and the following
10   * disclaimer. 2) Redistributions in binary form must reproduce the above
11   * copyright notice, this list of conditions and the following
12   * disclaimer in the documentation and/or other materials provided
13   * with the distribution. 3) Neither the name of the Qulice.com nor
14   * the names of its contributors may be used to endorse or promote
15   * products derived from this software without specific prior written
16   * permission.
17   *
18   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
20   * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21   * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22   * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23   * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
29   * OF THE POSSIBILITY OF SUCH DAMAGE.
30   */
31  package com.qulice.checkstyle;
32  
33  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
34  import com.puppycrawl.tools.checkstyle.api.DetailAST;
35  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
36  import java.util.HashSet;
37  import java.util.Set;
38  
39  /**
40   * Checks if inner classes are properly accessed using their qualified name
41   * with the outer class.
42   *
43   * @since 0.18
44   * @todo #738:30min Static inner classes should be qualified with outer class
45   *  Implement QualifyInnerClassCheck so it follows what defined in
46   *  QualifyInnerClassCheck test and add this check to checks.xml and CheckTest.
47   */
48  public final class QualifyInnerClassCheck extends AbstractCheck {
49      // FIXME: do we need to clear these fields in the end?
50      /**
51       * Set of all nested classes.
52       */
53      private final Set<String> nested = new HashSet<>();
54  
55      /**
56       * Whether we already visited root class of the .java file.
57       */
58      private boolean root;
59  
60      @Override
61      public int[] getDefaultTokens() {
62          return new int[]{
63              TokenTypes.CLASS_DEF,
64              TokenTypes.ENUM_DEF,
65              TokenTypes.INTERFACE_DEF,
66              TokenTypes.LITERAL_NEW,
67          };
68      }
69  
70      @Override
71      public int[] getAcceptableTokens() {
72          return this.getDefaultTokens();
73      }
74  
75      @Override
76      public int[] getRequiredTokens() {
77          return this.getDefaultTokens();
78      }
79  
80      @Override
81      public void visitToken(final DetailAST ast) {
82          if (ast.getType() == TokenTypes.CLASS_DEF
83              || ast.getType() == TokenTypes.ENUM_DEF
84              || ast.getType() == TokenTypes.INTERFACE_DEF) {
85              this.scanForNestedClassesIfNecessary(ast);
86          }
87          if (ast.getType() == TokenTypes.LITERAL_NEW) {
88              this.visitNewExpression(ast);
89          }
90      }
91  
92      /**
93       * Checks if class to be instantiated is nested and unqualified.
94       *
95       * FIXME: currently only simple paths are detected
96       * (i.e. `new Foo`, but not `new Foo.Bar`)
97       * @param expr EXPR LITERAL_NEW node that needs to be checked
98       */
99      private void visitNewExpression(final DetailAST expr) {
100         final DetailAST child = expr.getFirstChild();
101         if (child.getType() == TokenTypes.IDENT) {
102             if (this.nested.contains(child.getText())) {
103                 this.log(child, "Static inner class should be qualified with outer class");
104             }
105         } else if (child.getType() != TokenTypes.DOT) {
106             final String message = String.format("unsupported input %d", child.getType());
107             throw new IllegalStateException(message);
108         }
109     }
110 
111     /**
112      * If provided class is top-level, scans it for nested classes.
113      * FIXME: currently it assumes there can be only one top-level class
114      *
115      * @param node Class-like AST node
116      */
117     private void scanForNestedClassesIfNecessary(final DetailAST node) {
118         if (!this.root) {
119             this.root = true;
120             this.scanClass(node);
121         }
122     }
123 
124     /**
125      * Scans class for all nested sub-classes.
126      *
127      * FIXME: checkstyle discourages manual traversing of AST,
128      * but exactly this is happening here.
129      * @param node Class-like AST node that needs to be checked
130      */
131     private void scanClass(final DetailAST node) {
132         this.nested.add(getClassName(node));
133         final DetailAST content = node.findFirstToken(TokenTypes.OBJBLOCK);
134         if (content == null) {
135             return;
136         }
137         for (
138             DetailAST child = content.getFirstChild();
139             child != null;
140             child  = child.getNextSibling()
141         ) {
142             if (child.getType() == TokenTypes.CLASS_DEF
143                 || child.getType() == TokenTypes.ENUM_DEF
144                 || child.getType() == TokenTypes.INTERFACE_DEF) {
145                 this.scanClass(child);
146             }
147         }
148     }
149 
150     /**
151      * Returns class name.
152      * @param clazz Class-like AST node
153      * @return Class name
154      */
155     private static String getClassName(final DetailAST clazz) {
156         for (
157             DetailAST child = clazz.getFirstChild();
158             child != null;
159             child = child.getNextSibling()
160         ) {
161             if (child.getType() == TokenTypes.IDENT) {
162                 return child.getText();
163             }
164         }
165         throw new IllegalStateException("unexpected input: can not find class name");
166     }
167 }