-
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathErrorChecker.java
More file actions
351 lines (288 loc) · 11.9 KB
/
ErrorChecker.java
File metadata and controls
351 lines (288 loc) · 11.9 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-23 The Processing Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package processing.mode.java;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.eclipse.jdt.core.compiler.IProblem;
import com.google.classpath.ClassPath;
import com.google.classpath.ClassPathFactory;
import com.google.classpath.RegExpResourceFilter;
import processing.app.Language;
import processing.app.Problem;
public class ErrorChecker {
// Delay delivering error check result after last sketch change
// https://github.com/processing/processing/issues/2677
private final static long DELAY_BEFORE_UPDATE = 650;
final private ScheduledExecutorService scheduler;
private volatile ScheduledFuture<?> scheduledUiUpdate = null;
private volatile long nextUiUpdate = 0;
private volatile boolean enabled;
private final Consumer<PreprocSketch> errorHandlerListener =
this::handleSketchProblems;
final private Consumer<List<Problem>> editor;
final private PreprocService pps;
public ErrorChecker(Consumer<List<Problem>> editor, PreprocService pps) {
this.editor = editor;
this.pps = pps;
scheduler = Executors.newSingleThreadScheduledExecutor();
enabled = JavaMode.errorCheckEnabled;
if (enabled) {
pps.registerListener(errorHandlerListener);
}
}
public void notifySketchChanged() {
nextUiUpdate = System.currentTimeMillis() + DELAY_BEFORE_UPDATE;
}
public void preferencesChanged() {
if (enabled != JavaMode.errorCheckEnabled) {
enabled = JavaMode.errorCheckEnabled;
if (enabled) {
pps.registerListener(errorHandlerListener);
} else {
pps.unregisterListener(errorHandlerListener);
editor.accept(Collections.emptyList());
nextUiUpdate = 0;
}
}
}
public void dispose() {
if (scheduler != null) {
scheduler.shutdownNow();
}
}
private void handleSketchProblems(PreprocSketch ps) {
Map<String, String[]> suggestCache =
JavaMode.importSuggestEnabled ? new HashMap<>() : Collections.emptyMap();
List<IProblem> iproblems;
if (ps.compilationUnit == null) {
iproblems = new ArrayList<>();
} else {
iproblems = ps.iproblems;
}
final List<Problem> problems = new ArrayList<>(ps.otherProblems);
if (problems.isEmpty()) { // Check for curly quotes
List<JavaProblem> curlyQuoteProblems = checkForCurlyQuotes(ps);
problems.addAll(curlyQuoteProblems);
}
if (problems.isEmpty()) {
AtomicReference<ClassPath> searchClassPath =
new AtomicReference<>(null);
List<Problem> cuProblems = iproblems.stream()
// Filter Warnings if they are not enabled
.filter(iproblem -> !(iproblem.isWarning() && !JavaMode.warningsEnabled))
.filter(iproblem -> !(isIgnorableProblem(iproblem)))
// Transform into our Problems
.map(iproblem -> {
JavaProblem p = convertIProblem(iproblem, ps);
// Handle import suggestions
if (p != null && JavaMode.importSuggestEnabled && isUndefinedTypeProblem(iproblem)) {
ClassPath cp = searchClassPath.updateAndGet(prev -> prev != null ?
prev : new ClassPathFactory().createFromPaths(ps.searchClassPathArray));
String[] s = suggestCache.computeIfAbsent(iproblem.getArguments()[0],
name -> getImportSuggestions(cp, name));
p.setImportSuggestions(s);
}
return p;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
problems.addAll(cuProblems);
}
if (scheduledUiUpdate != null) {
scheduledUiUpdate.cancel(true);
}
// https://github.com/processing/processing/issues/2677
long delay = nextUiUpdate - System.currentTimeMillis();
Runnable uiUpdater = () -> {
if (nextUiUpdate > 0 && System.currentTimeMillis() >= nextUiUpdate) {
EventQueue.invokeLater(() -> editor.accept(problems));
}
};
scheduledUiUpdate =
scheduler.schedule(uiUpdater, delay, TimeUnit.MILLISECONDS);
}
/**
* Determine if a problem can be suppressed from the user.
*
* <p>
* Determine if one can ignore an errors where an ignorable error is one
* "fixed" in later pipeline steps but can make JDT angry or do not actually
* cause issues when reaching javac.
* </p>
*
* @return True if ignorable and false otherwise.
*/
static private boolean isIgnorableProblem(IProblem iproblem) {
String message = iproblem.getMessage();
// Hide a useless error which is produced when a line ends with
// an identifier without a semicolon. "Missing a semicolon" is
// also produced and is preferred over this one.
// (Syntax error, insert ":: IdentifierOrNew" to complete Expression)
// See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=405780
boolean ignorable =
message.contains("Syntax error, insert \":: IdentifierOrNew\"");
// It's ok if the file names do not line up during preprocessing.
ignorable |= message.contains("must be defined in its own file");
return ignorable;
}
static private JavaProblem convertIProblem(IProblem iproblem, PreprocSketch ps) {
String originalFileName = new String(iproblem.getOriginatingFileName());
boolean isJavaTab = ps.isJavaTab(originalFileName);
// Java tabs' content isn't stored in a sketch's combined source code file,
// so they are processed differently
if (!isJavaTab) {
SketchInterval in = ps.mapJavaToSketch(iproblem);
if (in != SketchInterval.BEFORE_START) {
String badCode = ps.getPdeCode(in);
int line = ps.tabOffsetToTabLine(in.tabIndex, in.startTabOffset);
JavaProblem p = JavaProblem.fromIProblem(iproblem, in.tabIndex, line, badCode);
p.setPDEOffsets(0, -1);
return p;
}
} else {
int tabIndex = ps.getJavaTabIndex(originalFileName);
int line = iproblem.getSourceLineNumber() - 1;
JavaProblem p = JavaProblem.fromIProblem(iproblem, tabIndex, line, "");
p.setPDEOffsets(0, -1);
return p;
}
return null;
}
static private boolean isUndefinedTypeProblem(IProblem iproblem) {
int id = iproblem.getID();
return id == IProblem.UndefinedType ||
id == IProblem.UndefinedName ||
id == IProblem.UnresolvedVariable;
}
static private boolean isMissingBraceProblem(IProblem iproblem) {
if (iproblem.getID() == IProblem.ParsingErrorInsertToComplete) {
char brace = iproblem.getArguments()[0].charAt(0);
return brace == '{' || brace == '}';
} else if (iproblem.getID() == IProblem.ParsingErrorInsertTokenAfter) {
char brace = iproblem.getArguments()[1].charAt(0);
return brace == '{' || brace == '}';
}
return false;
}
static private final Pattern CURLY_QUOTE_REGEX =
Pattern.compile("([“”‘’])", Pattern.UNICODE_CHARACTER_CLASS);
/**
* Check the scrubbed code for curly quotes.
* They are a common copy/paste error, especially on macOS.
*/
static private List<JavaProblem> checkForCurlyQuotes(PreprocSketch ps) {
if (ps.compilationUnit == null) {
return new ArrayList<>();
}
List<JavaProblem> problems = new ArrayList<>(0);
Matcher matcher = CURLY_QUOTE_REGEX.matcher(ps.scrubbedPdeCode);
while (matcher.find()) {
int pdeOffset = matcher.start();
String q = matcher.group();
int tabIndex = ps.pdeOffsetToTabIndex(pdeOffset);
int tabOffset = ps.pdeOffsetToTabOffset(tabIndex, pdeOffset);
int tabLine = ps.tabOffsetToTabLine(tabIndex, tabOffset);
String message = Language.interpolate("editor.status.bad_curly_quote", q);
JavaProblem problem = new JavaProblem(message, JavaProblem.ERROR, tabIndex, tabLine);
problems.add(problem);
}
// Go through iproblems and look for problems involving curly quotes
List<JavaProblem> problems2 = new ArrayList<>(0);
IProblem[] iproblems = ps.compilationUnit.getProblems();
for (IProblem iproblem : iproblems) {
switch (iproblem.getID()) {
case IProblem.ParsingErrorDeleteToken,
IProblem.ParsingErrorDeleteTokens,
IProblem.ParsingErrorInvalidToken,
IProblem.ParsingErrorReplaceTokens,
IProblem.UnterminatedString -> {
SketchInterval in = ps.mapJavaToSketch(iproblem);
if (in == SketchInterval.BEFORE_START) continue;
String badCode = ps.getPdeCode(in);
matcher.reset(badCode);
while (matcher.find()) {
int offset = matcher.start();
String q = matcher.group();
int tabStart = in.startTabOffset + offset;
int tabStop = tabStart + 1;
int line = ps.tabOffsetToTabLine(in.tabIndex, tabStart);
// Prevent duplicate problems
boolean isDupe = problems.stream()
.filter(p -> p.getTabIndex() == in.tabIndex)
.filter(p -> p.getLineNumber() == line)
.findAny()
.isPresent();
if (isDupe) {
String message;
if (iproblem.getID() == IProblem.UnterminatedString) {
message = Language.interpolate("editor.status.unterm_string_curly", q);
} else {
message = Language.interpolate("editor.status.bad_curly_quote", q);
}
JavaProblem p = new JavaProblem(message, JavaProblem.ERROR, in.tabIndex, line);
problems2.add(p);
}
}
}
}
}
problems.addAll(problems2);
return problems;
}
static public String[] getImportSuggestions(ClassPath cp, String className) {
className = className.replace("[", "\\[").replace("]", "\\]");
RegExpResourceFilter filter = new RegExpResourceFilter(
Pattern.compile(".*"),
Pattern.compile("(.*\\$)?" + className + "\\.class",
Pattern.CASE_INSENSITIVE));
String[] resources = cp.findResources("", filter);
return Arrays.stream(resources)
// remove ".class" suffix
.map(res -> res.substring(0, res.length() - 6))
// replace path separators with dots
.map(res -> res.replace('/', '.'))
// replace inner class separators with dots
.map(res -> res.replace('$', '.'))
// sort, prioritize classes from java. package
.map(res -> res.startsWith("classes.") ? res.substring(8) : res)
.sorted((o1, o2) -> {
// put java.* first, should be prioritized more
boolean o1StartsWithJava = o1.startsWith("java");
boolean o2StartsWithJava = o2.startsWith("java");
if (o1StartsWithJava != o2StartsWithJava) {
if (o1StartsWithJava) return -1;
return 1;
}
return o1.compareTo(o2);
})
.toArray(String[]::new);
}
}