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.LinkedList;
37  import java.util.List;
38  
39  /**
40   * Checks for not using concatenation of string literals in any form.
41   *
42   * <p>The following constructs are prohibited:
43   *
44   * <pre>
45   * String a = "done in " + time + " seconds";
46   * System.out.println("File not found: " + file);
47   * x += "done";
48   * </pre>
49   *
50   * <p>You should avoid string concatenation at all cost. Why? There are two
51   * reasons: readability of the code and translateability. First of all it's
52   * difficult to understand how the text will look after concatenation,
53   * especially if the text is long and there are more than a few {@code +}
54   * operators. Second, you won't be able to translate your text to other
55   * languages later, if you don't have solid string literals.
56   *
57   * <p>There are two alternatives to concatenation: {@link StringBuilder}
58   * and {@link String#format(String,Object[])}.
59   *
60   * @since 0.3
61   */
62  public final class StringLiteralsConcatenationCheck extends AbstractCheck {
63  
64      @Override
65      public int[] getDefaultTokens() {
66          return new int[] {TokenTypes.OBJBLOCK};
67      }
68  
69      @Override
70      public int[] getAcceptableTokens() {
71          return this.getDefaultTokens();
72      }
73  
74      @Override
75      public int[] getRequiredTokens() {
76          return this.getDefaultTokens();
77      }
78  
79      @Override
80      public void visitToken(final DetailAST ast) {
81          final List<DetailAST> pluses = this.findChildAstsOfType(
82              ast,
83              TokenTypes.PLUS,
84              TokenTypes.PLUS_ASSIGN
85          );
86          for (final DetailAST plus : pluses) {
87              if (!this.findChildAstsOfType(
88                  plus,
89                  TokenTypes.STRING_LITERAL
90              ).isEmpty()) {
91                  this.log(plus, "Concatenation of string literals prohibited");
92              }
93          }
94      }
95  
96      /**
97       * Recursively traverse the <code>tree</code> and return all ASTs subtrees
98       * matching any type from <code>types</code>.
99       * @param tree AST to traverse.
100      * @param types Token types to match against.
101      * @return All ASTs subtrees with token types matching any from
102      *  <tt>types</tt>.
103      * @see TokenTypes
104      */
105     private List<DetailAST> findChildAstsOfType(final DetailAST tree,
106         final int... types) {
107         final List<DetailAST> children = new LinkedList<>();
108         DetailAST child = tree.getFirstChild();
109         while (child != null) {
110             if (StringLiteralsConcatenationCheck.isOfType(child, types)) {
111                 children.add(child);
112             } else {
113                 children.addAll(this.findChildAstsOfType(child, types));
114             }
115             child = child.getNextSibling();
116         }
117         return children;
118     }
119 
120     /**
121      * Checks if this <code>ast</code> is of any type from <code>types</code>.
122      * @param ast AST to check.
123      * @param types Token types to match against.
124      * @return True if of type, false otherwise.
125      * @see TokenTypes
126      */
127     private static boolean isOfType(final DetailAST ast, final int... types) {
128         boolean yes = false;
129         for (final int type : types) {
130             if (ast.getType() == type) {
131                 yes = true;
132                 break;
133             }
134         }
135         return yes;
136     }
137 }