001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2021 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;
021
022import java.util.List;
023import java.util.Map;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.TextBlock;
031import com.puppycrawl.tools.checkstyle.api.TokenTypes;
032import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
033import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
034
035/**
036 * <p>
037 * Restricts using
038 * <a href = "https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.3">
039 * Unicode escapes</a>
040 * (such as &#92;u221e). It is possible to allow using escapes for
041 * <a href="https://en.wiktionary.org/wiki/Appendix:Control_characters">
042 * non-printable, control characters</a>.
043 * Also, this check can be configured to allow using escapes
044 * if trail comment is present. By the option it is possible to
045 * allow using escapes if literal contains only them.
046 * </p>
047 * <ul>
048 * <li>
049 * Property {@code allowEscapesForControlCharacters} - Allow use escapes for
050 * non-printable, control characters.
051 * Type is {@code boolean}.
052 * Default value is {@code false}.
053 * </li>
054 * <li>
055 * Property {@code allowByTailComment} - Allow use escapes if trail comment is present.
056 * Type is {@code boolean}.
057 * Default value is {@code false}.
058 * </li>
059 * <li>
060 * Property {@code allowIfAllCharactersEscaped} - Allow if all characters in literal are escaped.
061 * Type is {@code boolean}.
062 * Default value is {@code false}.
063 * </li>
064 * <li>
065 * Property {@code allowNonPrintableEscapes} - Allow use escapes for
066 * non-printable, whitespace characters.
067 * Type is {@code boolean}.
068 * Default value is {@code false}.
069 * </li>
070 * </ul>
071 * <p>
072 * To configure the check:
073 * </p>
074 * <pre>
075 * &lt;module name="AvoidEscapedUnicodeCharacters"/&gt;
076 * </pre>
077 * <p>
078 * Examples of using Unicode:</p>
079 * <pre>
080 * String unitAbbrev = "μs";     // OK, perfectly clear even without a comment.
081 * String unitAbbrev = "&#92;u03bcs";// violation, the reader has no idea what this is.
082 * return '&#92;ufeff' + content;    // OK, an example of non-printable,
083 *                               // control characters (byte order mark).
084 * </pre>
085 * <p>
086 * An example of how to configure the check to allow using escapes
087 * for non-printable, control characters:
088 * </p>
089 * <pre>
090 * &lt;module name="AvoidEscapedUnicodeCharacters"&gt;
091 *   &lt;property name="allowEscapesForControlCharacters" value="true"/&gt;
092 * &lt;/module&gt;
093 * </pre>
094 * <p>
095 * Example of using escapes for non-printable, control characters:
096 * </p>
097 * <pre>
098 * String unitAbbrev = "μs";      // OK, a normal String
099 * String unitAbbrev = "&#92;u03bcs"; // violation, "&#92;u03bcs" is a printable character.
100 * return '&#92;ufeff' + content;     // OK, non-printable control character.
101 * </pre>
102 * <p>
103 * An example of how to configure the check to allow using escapes
104 * if trail comment is present:
105 * </p>
106 * <pre>
107 * &lt;module name="AvoidEscapedUnicodeCharacters"&gt;
108 *   &lt;property name="allowByTailComment" value="true"/&gt;
109 * &lt;/module&gt;
110 * </pre>
111 * <p>Example of using escapes if trail comment is present:
112 * </p>
113 * <pre>
114 * String unitAbbrev = "μs";      // OK, a normal String
115 * String unitAbbrev = "&#92;u03bcs"; // OK, Greek letter mu, "s"
116 * return '&#92;ufeff' + content;
117 * // -----^--------------------- violation, comment is not used within same line.
118 * </pre>
119 * <p>
120 * An example of how to configure the check to allow if
121 * all characters in literal are escaped.
122 * </p>
123 * <pre>
124 * &lt;module name="AvoidEscapedUnicodeCharacters"&gt;
125 *   &lt;property name="allowIfAllCharactersEscaped" value="true"/&gt;
126 * &lt;/module&gt;
127 * </pre>
128 * <p>Example of using escapes if all characters in literal are escaped:</p>
129 * <pre>
130 * String unitAbbrev = "μs";      // OK, a normal String
131 * String unitAbbrev = "&#92;u03bcs"; // violation, not all characters are escaped ('s').
132 * String unitAbbrev = "&#92;u03bc&#92;u03bc&#92;u03bc"; // OK
133 * String unitAbbrev = "&#92;u03bc&#92;u03bcs";// violation, not all characters are escaped ('s').
134 * return '&#92;ufeff' + content;          // OK, all control characters are escaped
135 * </pre>
136 * <p>An example of how to configure the check to allow using escapes
137 * for non-printable whitespace characters:
138 * </p>
139 * <pre>
140 * &lt;module name="AvoidEscapedUnicodeCharacters"&gt;
141 *   &lt;property name="allowNonPrintableEscapes" value="true"/&gt;
142 * &lt;/module&gt;
143 * </pre>
144 * <p>Example of using escapes for non-printable whitespace characters:</p>
145 * <pre>
146 * String unitAbbrev = "μs";       // OK, a normal String
147 * String unitAbbrev1 = "&#92;u03bcs"; // violation, printable escape character.
148 * String unitAbbrev2 = "&#92;u03bc&#92;u03bc&#92;u03bc"; // violation, printable escape character.
149 * String unitAbbrev3 = "&#92;u03bc&#92;u03bcs";// violation, printable escape character.
150 * return '&#92;ufeff' + content;           // OK, non-printable escape character.
151 * </pre>
152 * <p>
153 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
154 * </p>
155 * <p>
156 * Violation Message Keys:
157 * </p>
158 * <ul>
159 * <li>
160 * {@code forbid.escaped.unicode.char}
161 * </li>
162 * </ul>
163 *
164 * @since 5.8
165 */
166@FileStatefulCheck
167public class AvoidEscapedUnicodeCharactersCheck
168    extends AbstractCheck {
169
170    /**
171     * A key is pointing to the warning message text in "messages.properties"
172     * file.
173     */
174    public static final String MSG_KEY = "forbid.escaped.unicode.char";
175
176    /** Regular expression for Unicode chars. */
177    private static final Pattern UNICODE_REGEXP = Pattern.compile("\\\\u+[a-fA-F0-9]{4}");
178
179    /**
180     * Regular expression Unicode control characters.
181     *
182     * @see <a href="https://en.wiktionary.org/wiki/Appendix:Control_characters">
183     *     Appendix:Control characters</a>
184     */
185    private static final Pattern UNICODE_CONTROL = Pattern.compile("\\\\u+"
186            + "(00[0-1][0-9A-Fa-f]"
187            + "|00[8-9][0-9A-Fa-f]"
188            + "|00[aA][dD]"
189            + "|034[fF]"
190            + "|070[fF]"
191            + "|180[eE]"
192            + "|200[b-fB-F]"
193            + "|202[a-eA-E]"
194            + "|206[0-4a-fA-F]"
195            + "|[fF]{3}[9a-bA-B]"
196            + "|[fF][eE][fF]{2})");
197
198    /**
199     * Regular expression for all escaped chars.
200     * See "EscapeSequence" at
201     * https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html#jls-3.10.7
202     */
203    private static final Pattern ALL_ESCAPED_CHARS = Pattern.compile("^("
204            + UNICODE_REGEXP.pattern()
205            + "|\""
206            + "|'"
207            + "|\\\\"
208            + "|\\\\b"
209            + "|\\\\f"
210            + "|\\\\n"
211            + "|\\\\r"
212            + "|\\\\s"
213            + "|\\\\t"
214            + ")+$");
215
216    /** Regular expression for escaped backslash. */
217    private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\\\\\");
218
219    /** Regular expression for non-printable unicode chars. */
220    private static final Pattern NON_PRINTABLE_CHARS = Pattern.compile("\\\\u0000"
221            + "|\\\\u0009"
222            + "|\\\\u000[bB]"
223            + "|\\\\u000[cC]"
224            + "|\\\\u0020"
225            + "|\\\\u007[fF]"
226            + "|\\\\u0085"
227            + "|\\\\u009[fF]"
228            + "|\\\\u00[aA]0"
229            + "|\\\\u00[aA][dD]"
230            + "|\\\\u04[fF]9"
231            + "|\\\\u05[bB][eE]"
232            + "|\\\\u05[dD]0"
233            + "|\\\\u05[eE][aA]"
234            + "|\\\\u05[fF]3"
235            + "|\\\\u05[fF]4"
236            + "|\\\\u0600"
237            + "|\\\\u0604"
238            + "|\\\\u061[cC]"
239            + "|\\\\u06[dD]{2}"
240            + "|\\\\u06[fF]{2}"
241            + "|\\\\u070[fF]"
242            + "|\\\\u0750"
243            + "|\\\\u077[fF]"
244            + "|\\\\u0[eE]00"
245            + "|\\\\u0[eE]7[fF]"
246            + "|\\\\u1680"
247            + "|\\\\u180[eE]"
248            + "|\\\\u1[eE]00"
249            + "|\\\\u2000"
250            + "|\\\\u2001"
251            + "|\\\\u2002"
252            + "|\\\\u2003"
253            + "|\\\\u2004"
254            + "|\\\\u2005"
255            + "|\\\\u2006"
256            + "|\\\\u2007"
257            + "|\\\\u2008"
258            + "|\\\\u2009"
259            + "|\\\\u200[aA]"
260            + "|\\\\u200[fF]"
261            + "|\\\\u2025"
262            + "|\\\\u2028"
263            + "|\\\\u2029"
264            + "|\\\\u202[fF]"
265            + "|\\\\u205[fF]"
266            + "|\\\\u2064"
267            + "|\\\\u2066"
268            + "|\\\\u2067"
269            + "|\\\\u2068"
270            + "|\\\\u2069"
271            + "|\\\\u206[aA]"
272            + "|\\\\u206[fF]"
273            + "|\\\\u20[aA][fF]"
274            + "|\\\\u2100"
275            + "|\\\\u213[aA]"
276            + "|\\\\u3000"
277            + "|\\\\u[dD]800"
278            + "|\\\\u[fF]8[fF]{2}"
279            + "|\\\\u[fF][bB]50"
280            + "|\\\\u[fF][dD][fF]{2}"
281            + "|\\\\u[fF][eE]70"
282            + "|\\\\u[fF][eE][fF]{2}"
283            + "|\\\\u[fF]{2}0[eE]"
284            + "|\\\\u[fF]{2}61"
285            + "|\\\\u[fF]{2}[dD][cC]"
286            + "|\\\\u[fF]{3}9"
287            + "|\\\\u[fF]{3}[aA]"
288            + "|\\\\u[fF]{3}[bB]"
289            + "|\\\\u[fF]{4}");
290
291    /** Cpp style comments. */
292    private Map<Integer, TextBlock> singlelineComments;
293    /** C style comments. */
294    private Map<Integer, List<TextBlock>> blockComments;
295
296    /** Allow use escapes for non-printable, control characters. */
297    private boolean allowEscapesForControlCharacters;
298
299    /** Allow use escapes if trail comment is present. */
300    private boolean allowByTailComment;
301
302    /** Allow if all characters in literal are escaped. */
303    private boolean allowIfAllCharactersEscaped;
304
305    /** Allow use escapes for non-printable, whitespace characters. */
306    private boolean allowNonPrintableEscapes;
307
308    /**
309     * Setter to allow use escapes for non-printable, control characters.
310     *
311     * @param allow user's value.
312     */
313    public final void setAllowEscapesForControlCharacters(boolean allow) {
314        allowEscapesForControlCharacters = allow;
315    }
316
317    /**
318     * Setter to allow use escapes if trail comment is present.
319     *
320     * @param allow user's value.
321     */
322    public final void setAllowByTailComment(boolean allow) {
323        allowByTailComment = allow;
324    }
325
326    /**
327     * Setter to allow if all characters in literal are escaped.
328     *
329     * @param allow user's value.
330     */
331    public final void setAllowIfAllCharactersEscaped(boolean allow) {
332        allowIfAllCharactersEscaped = allow;
333    }
334
335    /**
336     * Setter to allow use escapes for non-printable, whitespace characters.
337     *
338     * @param allow user's value.
339     */
340    public final void setAllowNonPrintableEscapes(boolean allow) {
341        allowNonPrintableEscapes = allow;
342    }
343
344    @Override
345    public int[] getDefaultTokens() {
346        return getRequiredTokens();
347    }
348
349    @Override
350    public int[] getAcceptableTokens() {
351        return getRequiredTokens();
352    }
353
354    @Override
355    public int[] getRequiredTokens() {
356        return new int[] {
357            TokenTypes.STRING_LITERAL,
358            TokenTypes.CHAR_LITERAL,
359            TokenTypes.TEXT_BLOCK_CONTENT,
360        };
361    }
362
363    @Override
364    public void beginTree(DetailAST rootAST) {
365        singlelineComments = getFileContents().getSingleLineComments();
366        blockComments = getFileContents().getBlockComments();
367    }
368
369    @Override
370    public void visitToken(DetailAST ast) {
371        final String literal =
372            CheckUtil.stripIndentAndInitialNewLineFromTextBlock(ast.getText());
373
374        if (hasUnicodeChar(literal) && !(allowByTailComment && hasTrailComment(ast)
375                || isAllCharactersEscaped(literal)
376                || allowEscapesForControlCharacters
377                        && isOnlyUnicodeValidChars(literal, UNICODE_CONTROL)
378                || allowNonPrintableEscapes
379                        && isOnlyUnicodeValidChars(literal, NON_PRINTABLE_CHARS))) {
380            log(ast, MSG_KEY);
381        }
382    }
383
384    /**
385     * Checks if literal has Unicode chars.
386     *
387     * @param literal String literal.
388     * @return true if literal has Unicode chars.
389     */
390    private static boolean hasUnicodeChar(String literal) {
391        final String literalWithoutEscapedBackslashes =
392                ESCAPED_BACKSLASH.matcher(literal).replaceAll("");
393        return UNICODE_REGEXP.matcher(literalWithoutEscapedBackslashes).find();
394    }
395
396    /**
397     * Check if String literal contains Unicode control chars.
398     *
399     * @param literal String literal.
400     * @param pattern RegExp for valid characters.
401     * @return true, if String literal contains Unicode control chars.
402     */
403    private static boolean isOnlyUnicodeValidChars(String literal, Pattern pattern) {
404        final int unicodeMatchesCounter =
405                countMatches(UNICODE_REGEXP, literal);
406        final int unicodeValidMatchesCounter =
407                countMatches(pattern, literal);
408        return unicodeMatchesCounter - unicodeValidMatchesCounter == 0;
409    }
410
411    /**
412     * Check if trail comment is present after ast token.
413     *
414     * @param ast current token.
415     * @return true if trail comment is present after ast token.
416     */
417    private boolean hasTrailComment(DetailAST ast) {
418        int lineNo = ast.getLineNo();
419
420        // Since the trailing comment in the case of text blocks must follow the """ delimiter,
421        // we need to look for it after TEXT_BLOCK_LITERAL_END.
422        if (ast.getType() == TokenTypes.TEXT_BLOCK_CONTENT) {
423            lineNo = ast.getNextSibling().getLineNo();
424        }
425        boolean result = false;
426        if (singlelineComments.containsKey(lineNo)) {
427            result = true;
428        }
429        else {
430            final List<TextBlock> commentList = blockComments.get(lineNo);
431            if (commentList != null) {
432                final TextBlock comment = commentList.get(commentList.size() - 1);
433                final String line = getLines()[lineNo - 1];
434                result = isTrailingBlockComment(comment, line);
435            }
436        }
437        return result;
438    }
439
440    /**
441     * Whether the C style comment is trailing.
442     *
443     * @param comment the comment to check.
444     * @param line the line where the comment starts.
445     * @return true if the comment is trailing.
446     */
447    private static boolean isTrailingBlockComment(TextBlock comment, String line) {
448        return comment.getText().length != 1
449            || CommonUtil.isBlank(line.substring(comment.getEndColNo() + 1));
450    }
451
452    /**
453     * Count regexp matches into String literal.
454     *
455     * @param pattern pattern.
456     * @param target String literal.
457     * @return count of regexp matches.
458     */
459    private static int countMatches(Pattern pattern, String target) {
460        int matcherCounter = 0;
461        final Matcher matcher = pattern.matcher(target);
462        while (matcher.find()) {
463            matcherCounter++;
464        }
465        return matcherCounter;
466    }
467
468    /**
469     * Checks if all characters in String literal is escaped.
470     *
471     * @param literal current literal.
472     * @return true if all characters in String literal is escaped.
473     */
474    private boolean isAllCharactersEscaped(String literal) {
475        return allowIfAllCharactersEscaped
476                && ALL_ESCAPED_CHARS.matcher(literal).find();
477    }
478
479}