|
| 1 | +/* |
| 2 | + * Copyright 2024 The Error Prone Authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.errorprone.bugpatterns; |
| 18 | + |
| 19 | +import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; |
| 20 | +import static com.google.errorprone.matchers.Description.NO_MATCH; |
| 21 | +import static com.google.errorprone.matchers.Matchers.anyOf; |
| 22 | +import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; |
| 23 | +import static com.google.errorprone.util.ASTHelpers.getStartPosition; |
| 24 | +import static com.google.errorprone.util.ErrorProneTokens.getTokens; |
| 25 | +import static com.google.errorprone.util.SourceVersion.supportsTextBlocks; |
| 26 | +import static java.util.stream.Collectors.joining; |
| 27 | + |
| 28 | +import com.google.common.base.Splitter; |
| 29 | +import com.google.common.escape.Escaper; |
| 30 | +import com.google.common.escape.Escapers; |
| 31 | +import com.google.errorprone.BugPattern; |
| 32 | +import com.google.errorprone.VisitorState; |
| 33 | +import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; |
| 34 | +import com.google.errorprone.fixes.SuggestedFix; |
| 35 | +import com.google.errorprone.matchers.Description; |
| 36 | +import com.google.errorprone.matchers.Matcher; |
| 37 | +import com.google.googlejavaformat.java.Formatter; |
| 38 | +import com.google.googlejavaformat.java.FormatterException; |
| 39 | +import com.sun.source.tree.ExpressionTree; |
| 40 | +import com.sun.source.tree.LiteralTree; |
| 41 | +import com.sun.source.tree.MethodInvocationTree; |
| 42 | +import com.sun.tools.javac.parser.Tokens.TokenKind; |
| 43 | + |
| 44 | +/** See the summary. */ |
| 45 | +@BugPattern( |
| 46 | + severity = WARNING, |
| 47 | + summary = "This test data will be more readable if correctly formatted.") |
| 48 | +public final class MisformattedTestData extends BugChecker implements MethodInvocationTreeMatcher { |
| 49 | + @Override |
| 50 | + public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { |
| 51 | + // We're not only matching text blocks below, just taking the fact that it's a single literal |
| 52 | + // argument containing source code as a sign that it should be formatted in a text block. |
| 53 | + if (!supportsTextBlocks(state.context)) { |
| 54 | + return NO_MATCH; |
| 55 | + } |
| 56 | + if (!ADD_SOURCE_CALL.matches(tree, state)) { |
| 57 | + return NO_MATCH; |
| 58 | + } |
| 59 | + if (tree.getArguments().size() != 2) { |
| 60 | + return NO_MATCH; |
| 61 | + } |
| 62 | + var sourceTree = tree.getArguments().get(1); |
| 63 | + if (!(sourceTree instanceof LiteralTree)) { |
| 64 | + return NO_MATCH; |
| 65 | + } |
| 66 | + var sourceValue = ((LiteralTree) sourceTree).getValue(); |
| 67 | + if (!(sourceValue instanceof String)) { |
| 68 | + return NO_MATCH; |
| 69 | + } |
| 70 | + |
| 71 | + Formatter formatter = new Formatter(); |
| 72 | + String formattedSource; |
| 73 | + try { |
| 74 | + formattedSource = formatter.formatSource((String) sourceValue); |
| 75 | + } catch (FormatterException exception) { |
| 76 | + return NO_MATCH; |
| 77 | + } |
| 78 | + if (formattedSource.equals(sourceValue)) { |
| 79 | + return NO_MATCH; |
| 80 | + } |
| 81 | + // This is a bit crude: but tokenize between the comma and the 2nd argument in order to work out |
| 82 | + // an appropriate indent level for the text block. This is assuming that the source has already |
| 83 | + // been formatted so that the arguments are nicely indented. |
| 84 | + int startPos = state.getEndPosition(tree.getArguments().get(0)); |
| 85 | + int endPos = getStartPosition(tree.getArguments().get(1)); |
| 86 | + var tokens = |
| 87 | + getTokens( |
| 88 | + state.getSourceCode().subSequence(startPos, endPos).toString(), |
| 89 | + startPos, |
| 90 | + state.context); |
| 91 | + var afterCommaPos = |
| 92 | + tokens.reverse().stream() |
| 93 | + .filter(t -> t.kind().equals(TokenKind.COMMA)) |
| 94 | + .findFirst() |
| 95 | + .orElseThrow() |
| 96 | + .endPos(); |
| 97 | + var spaces = |
| 98 | + state.getSourceCode().subSequence(afterCommaPos, endPos).toString().replace("\n", ""); |
| 99 | + return describeMatch( |
| 100 | + sourceTree, |
| 101 | + SuggestedFix.replace( |
| 102 | + sourceTree, |
| 103 | + "\"\"\"\n" |
| 104 | + + LINE_SPLITTER |
| 105 | + .splitToStream(escape(formattedSource)) |
| 106 | + .map(line -> line.isEmpty() ? "" : spaces + line) |
| 107 | + .collect(joining("\n")) |
| 108 | + + spaces |
| 109 | + + "\"\"\"")); |
| 110 | + } |
| 111 | + |
| 112 | + // TODO(ghm): Consider generalising this via an annotation. |
| 113 | + private static final Matcher<ExpressionTree> ADD_SOURCE_CALL = |
| 114 | + anyOf( |
| 115 | + instanceMethod() |
| 116 | + .onExactClass("com.google.errorprone.CompilationTestHelper") |
| 117 | + .named("addSourceLines"), |
| 118 | + instanceMethod() |
| 119 | + .onExactClass("com.google.errorprone.BugCheckerRefactoringTestHelper") |
| 120 | + .named("addInputLines"), |
| 121 | + instanceMethod() |
| 122 | + .onExactClass("com.google.errorprone.BugCheckerRefactoringTestHelper") |
| 123 | + .named("addOutputLines")); |
| 124 | + |
| 125 | + private static final Splitter LINE_SPLITTER = Splitter.on('\n'); |
| 126 | + |
| 127 | + private static String escape(String line) { |
| 128 | + return ESCAPER.escape(line).replace("\"\"\"", "\\\"\"\""); |
| 129 | + } |
| 130 | + |
| 131 | + private static final Escaper ESCAPER = Escapers.builder().addEscape('\\', "\\\\").build(); |
| 132 | +} |
0 commit comments