-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPMDExternalLanguageAnnotator.java
More file actions
298 lines (259 loc) · 8.5 KB
/
PMDExternalLanguageAnnotator.java
File metadata and controls
298 lines (259 loc) · 8.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package software.xdev.pmd.annotator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.codeInsight.daemon.impl.actions.SuppressFix;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.AnnotationBuilder;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.ExternalAnnotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.diagnostic.ControlFlowException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import net.sourceforge.pmd.lang.rule.Rule;
import net.sourceforge.pmd.reporting.Report;
import net.sourceforge.pmd.reporting.RuleViolation;
import software.xdev.pmd.analysis.PMDAnalysisResult;
import software.xdev.pmd.analysis.PMDAnalyzer;
import software.xdev.pmd.config.ConfigurationLocationSource;
import software.xdev.pmd.currentfile.CurrentFileAnalysisManager;
import software.xdev.pmd.markdown.RuleDescriptionDocMarkdownToHtmlService;
import software.xdev.pmd.util.Notifications;
public class PMDExternalLanguageAnnotator
extends ExternalAnnotator<PMDExternalLanguageAnnotator.FileInfo, PMDExternalLanguageAnnotator.PMDAnnotations>
{
private static final Logger LOG = Logger.getInstance(PMDExternalLanguageAnnotator.class);
@Nullable
@Override
public FileInfo collectInformation(
@NotNull final PsiFile psiFile,
@NotNull final Editor editor,
final boolean hasErrors)
{
return new FileInfo(psiFile, editor.getDocument());
}
@Nullable
@Override
public PMDAnnotations doAnnotate(final FileInfo info)
{
if(this.workaround != null)
{
final PMDAnnotations workaroundReturn = this.workaround.check(info);
if(workaroundReturn != null)
{
return workaroundReturn;
}
}
final PsiFile file = info.file();
final Project project = file.getProject();
try
{
final PMDAnalysisResult analysisResult = this.analyze(
file,
project,
ProgressManager.getInstance().getProgressIndicator());
project.getService(CurrentFileAnalysisManager.class)
.reportAnalysisResult(file, this, analysisResult);
final PMDAnnotations annotations = new PMDAnnotations(
analysisResult,
info.document());
if(this.workaround != null)
{
this.workaround.store(info, annotations);
}
return annotations;
}
catch(final RuntimeException ex)
{
// Control-flow exceptions (e.g. this class ProcessCanceledException) should never be logged
// Instead, these should have been rethrown if caught.
if(ex instanceof ControlFlowException)
{
throw ex;
}
LOG.error("Failed to annotate", ex);
Notifications.showException(project, ex);
return null;
}
}
private PMDAnalysisResult analyze(
final PsiFile file,
final Project project,
final ProgressIndicator progress)
{
final PMDAnalyzer analyzer = project.getService(PMDAnalyzer.class);
final Module module = ModuleUtilCore.findModuleForFile(file);
return analyzer.analyze(
Optional.ofNullable(module),
Set.of(file),
true,
project.getService(ConfigurationLocationSource.class).getConfigurationLocations(module),
progress
);
}
@Override
public void apply(
@NotNull final PsiFile psiFile,
final PMDAnnotations annotationResult,
@NotNull final AnnotationHolder holder)
{
if(annotationResult == null)
{
return;
}
final Report report = annotationResult.analysisResult().report();
if(report == null)
{
return;
}
final List<RuleViolation> violations = report.getViolations();
if(violations.isEmpty())
{
return;
}
final Project project = psiFile.getProject();
final InspectionManager inspectionManager = InspectionManager.getInstance(project);
final RuleDescriptionDocMarkdownToHtmlService
ruleDescriptionDocMarkdownToHtmlService =
project.getService(RuleDescriptionDocMarkdownToHtmlService.class);
final Document document = annotationResult.document();
for(final RuleViolation violation : violations)
{
final int startLineOffset = document.getLineStartOffset(violation.getBeginLine() - 1);
final int endOffset =
violation.getEndLine() - violation.getBeginLine() > 5 // Only mark first line for long violations
? document.getLineEndOffset(violation.getBeginLine() - 1)
: document.getLineStartOffset(violation.getEndLine() - 1) + violation.getEndColumn();
final int startOffset = startLineOffset + violation.getBeginColumn() - 1;
final PsiElement psiElement = psiFile.findElementAt(startOffset);
try
{
final Rule rule = violation.getRule();
final TextRange range = TextRange.create(startOffset, endOffset);
final String pmdSuffix = "PMD: ";
AnnotationBuilder annotationBuilder = holder.newAnnotation(
getSeverity(violation),
pmdSuffix + violation.getDescription())
.tooltip(
pmdSuffix + rule.getName()
+ "<p>"
+ violation.getDescription()
+ "</p>"
+ "<p>"
+ ruleDescriptionDocMarkdownToHtmlService.mdToHtml(rule.getDescription())
+ "</p>")
.range(range);
if(psiElement != null)
{
final SuppressFix suppressFix = new SuppressFix("PMD." + rule.getName());
annotationBuilder = annotationBuilder.newLocalQuickFix(
suppressFix,
inspectionManager.createProblemDescriptor(
psiElement,
pmdSuffix + rule.getName(),
suppressFix,
getProblemHighlightType(violation),
false))
.range(range)
.registerFix();
}
annotationBuilder
.withFix(new SupressIntentionAction(violation))
.create();
}
catch(final IllegalArgumentException e)
{
// Catching "Invalid range specified" from TextRange.create thrown when file has been updated while
// analyzing
LOG.warn("Error while annotating file with PMD warnings", e);
}
}
}
private static HighlightSeverity getSeverity(final RuleViolation violation)
{
return switch(violation.getRule().getPriority())
{
case HIGH -> HighlightSeverity.ERROR;
case MEDIUM_HIGH, MEDIUM -> HighlightSeverity.WARNING;
case MEDIUM_LOW -> HighlightSeverity.WEAK_WARNING;
case LOW -> HighlightSeverity.INFORMATION;
};
}
private static ProblemHighlightType getProblemHighlightType(final RuleViolation violation)
{
return switch(violation.getRule().getPriority())
{
case HIGH -> ProblemHighlightType.ERROR;
case MEDIUM_HIGH, MEDIUM -> ProblemHighlightType.WARNING;
case MEDIUM_LOW -> ProblemHighlightType.WEAK_WARNING;
case LOW -> ProblemHighlightType.INFORMATION;
};
}
public record FileInfo(PsiFile file, Document document)
{
}
public record PMDAnnotations(PMDAnalysisResult analysisResult, Document document)
{
}
// region Workaround
record MarkdownCacheKey(Project project, String markdown)
{
}
private FirstAnnotateRunFaultyDuplicationWorkaround workaround =
new FirstAnnotateRunFaultyDuplicationWorkaround(this::unbindWorkaround);
private void unbindWorkaround()
{
this.workaround = null;
}
// Due to some reason the initial analysis is sometimes executed twice
// The second analysis is faulty (PMD Problem?) and results in the suppressed violations not being reported
static class FirstAnnotateRunFaultyDuplicationWorkaround
{
private final Runnable unbind;
private FileInfo initialAnalysisFileInfo;
private PMDAnnotations firstRunResult;
FirstAnnotateRunFaultyDuplicationWorkaround(final Runnable unbind)
{
this.unbind = unbind;
}
PMDAnnotations check(final FileInfo info)
{
if(this.initialAnalysisFileInfo == null)
{
this.initialAnalysisFileInfo = info;
}
else if(this.initialAnalysisFileInfo.equals(info))
{
this.unbind.run();
// DETECTED DUPLICATE INITIAL FILE ANNOTATION -> ABORT IT
return this.firstRunResult;
}
else
{
this.unbind.run();
}
return null;
}
void store(final FileInfo fileInfo, final PMDAnnotations analysisResult)
{
if(fileInfo == this.initialAnalysisFileInfo)
{
this.firstRunResult = analysisResult;
}
}
}
// endregion
}