forked from bazelbuild/rules_closure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsChecker.java
More file actions
364 lines (325 loc) · 13.1 KB
/
Copy pathJsChecker.java
File metadata and controls
364 lines (325 loc) · 13.1 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
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
* Copyright 2016 The Closure Rules Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.javascript.jscomp.JsCheckerHelper.convertPathToModuleName;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CompilerOptions.IncrementalCheckMode;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.parsing.Config;
import io.bazel.rules.closure.BuildInfo.ClosureJsLibrary;
import io.bazel.rules.closure.worker.CommandLineProgram;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
/**
* Program for incrementally checking JavaScript code.
*
* <p>This program is invoked once for each {@code closure_js_library} rule. It validates JS files
* for most of the really bad syntax errors, but doesn't do robust type checking because it can't
* take the full program into consideration. This program also performs linting, which is something
* that does not happen on {@code closure_js_binary} rules.
*
* <p>But most importantly, this program does strict dependency checking. It is able to verify that
* required namespaces are provided by direct dependencies rather than transitive dependencies. It
* does this in an incremental fashion by producing a txt file containing a sorted list of all
* namespaces provided by the srcs listed in a {@code closure_js_library}. These files are then
* accessed via the {@code --deps} flag on subsequent invocations for parent rules.
*/
public final class JsChecker {
private static final String USAGE =
String.format("Usage:\n java %s [FLAGS]\n", JsChecker.class.getName());
@Option(
name = "--label",
usage = "Name of rule being compiled.")
private String label = "@repo//ohmygoth:some_lib";
@Option(
name = "--legacy",
usage = "Used for sources defined by legacy rules.")
private boolean legacy;
@Option(
name = "--src",
usage = "JavaScript source and externs files.")
private List<String> sources = new ArrayList<>();
@Option(
name = "--mystery_src",
usage = "Transitive JS dependency whose position in the graph we're uncertain.")
private List<String> mysterySources = new ArrayList<>();
@Option(
name = "--dep",
usage = "foo-provides.txt files from deps targets.")
private List<String> deps = new ArrayList<>();
@Option(
name = "--js_module_root",
usage = "Prefixes to disregard in module namespaces, e.g. "
+ "bazel-out/local-fastbuild/genfiles. These values must be reverse sorted by the number "
+ "of path components.")
private List<String> roots = new ArrayList<>();
@Option(
name = "--convention",
usage = "Coding convention for linting.")
private JsCheckerConvention convention = JsCheckerConvention.CLOSURE;
@Option(
name = "--suppress",
usage = "Diagnostic types to not show as errors or warnings.")
private List<String> suppress = new ArrayList<>();
@Option(
name = "--testonly",
usage = "Indicates a testonly rule is being compiled.")
private boolean testonly;
@Option(
name = "--output",
usage = "Path of outputted ClosureJsLibrary.pbtxt file.")
private String output = "";
@Option(
name = "--output_ijs_file",
usage = "Path of the generated .i.js file representing the given sources.")
private String outputIjsFile = "";
@Option(
name = "--output_errors",
usage = "Name of output file for compiler errors in --nofail mode.")
private String outputErrors = "";
@Option(
name = "--expect_failure",
usage = "Invert exit code and disable printing warnings")
private boolean expectFailure;
@Option(
name = "--help",
usage = "Displays this message on stdout and exit")
private boolean help;
private boolean run() throws IOException {
final JsCheckerState state = new JsCheckerState(label, legacy, testonly, roots, mysterySources);
final Set<String> actuallySuppressed = new HashSet<>();
// read provided files created by this program on deps
for (String dep : deps) {
state.provided.addAll(
JsCheckerHelper.loadClosureJsLibraryInfo(Paths.get(dep))
.getNamespaceList());
}
Map<String, String> labels = new HashMap<>();
labels.put("", label);
Set<String> modules = new LinkedHashSet<>();
for (String source : sources) {
for (String module : convertPathToModuleName(source, state.roots).asSet()) {
modules.add(module);
labels.put(module, label);
state.provides.add(module);
}
}
for (String source : mysterySources) {
for (String module : convertPathToModuleName(source, state.roots).asSet()) {
checkArgument(!module.startsWith("blaze-out/"),
"oh no: %s", state.roots);
modules.add(module);
state.provided.add(module);
}
}
// configure compiler
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setLanguage(LanguageMode.STABLE);
options.setStrictModeInput(true);
options.setIncrementalChecks(IncrementalCheckMode.GENERATE_IJS);
options.setCodingConvention(convention.convention);
options.setSkipTranspilationAndCrash(true);
options.setContinueAfterErrors(true);
options.setPrettyPrint(true);
options.setPreserveTypeAnnotations(true);
options.setPreserveDetailedSourceInfo(true);
options.setEmitUseStrict(false);
options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE);
JsCheckerErrorFormatter errorFormatter =
new JsCheckerErrorFormatter(compiler, state.roots, labels);
errorFormatter.setColorize(true);
JsCheckerErrorManager errorManager = new JsCheckerErrorManager(errorFormatter);
compiler.setErrorManager(errorManager);
// configure which error messages appear
if (!legacy) {
for (String error
: Iterables.concat(
Diagnostics.JSCHECKER_ONLY_ERRORS,
Diagnostics.JSCHECKER_EXTRA_ERRORS)) {
options.setWarningLevel(Diagnostics.GROUPS.forName(error), CheckLevel.ERROR);
}
}
final Set<DiagnosticType> suppressions = Sets.newHashSetWithExpectedSize(256);
for (String code : suppress) {
ImmutableSet<DiagnosticType> types = Diagnostics.getDiagnosticTypesForSuppressCode(code);
if (types.isEmpty()) {
System.err.println("ERROR: Bad --suppress value: " + code);
return false;
}
suppressions.addAll(types);
}
options.addWarningsGuard(
new WarningsGuard() {
@Override
public CheckLevel level(JSError error) {
// TODO(jart): Figure out how to support this.
if (error.getType().key
.equals("JSC_CONSTANT_WITHOUT_EXPLICIT_TYPE")) {
return CheckLevel.OFF;
}
// Closure Rules will always ignore these checks no matter what.
if (Diagnostics.IGNORE_ALWAYS.contains(error.getType())) {
return CheckLevel.OFF;
}
// Disable warnings specific to conventions other than the one we're using.
if (!convention.diagnostics.contains(error.getType())) {
for (JsCheckerConvention conv : JsCheckerConvention.values()) {
if (!conv.equals(convention)) {
if (conv.diagnostics.contains(error.getType())) {
suppressions.add(error.getType());
return CheckLevel.OFF;
}
}
}
}
// Disable warnings we've suppressed.
Collection<String> groupNames = Diagnostics.DIAGNOSTIC_GROUPS.get(error.getType());
if (suppressions.contains(error.getType())) {
actuallySuppressed.add(error.getType().key);
actuallySuppressed.addAll(groupNames);
return CheckLevel.OFF;
}
// Ignore linter warnings on generated sources.
if (groupNames.contains("lintChecks")
&& JsCheckerHelper.isGeneratedPath(error.getSourceName())) {
return CheckLevel.OFF;
}
return null;
}
});
// Run the compiler.
compiler.setPassConfig(new JsCheckerPassConfig(state, options));
compiler.disableThreads();
compiler.compile(
ImmutableList.<SourceFile>of(),
getSourceFiles(Iterables.concat(sources, mysterySources)),
options);
// In order for suppress to be maintainable, we need to make sure the suppress codes relating to
// linting were actually suppressed. However we can only offer this safety on the checks over
// which JsChecker has sole dominion. Other suppress codes won't actually be suppressed until
// they've been propagated up to the closure_js_binary rule.
if (!suppress.contains("superfluousSuppress")) {
Set<String> useless =
Sets.intersection(
Sets.difference(ImmutableSet.copyOf(suppress), actuallySuppressed),
Diagnostics.JSCHECKER_ONLY_SUPPRESS_CODES);
if (!useless.isEmpty()) {
errorManager.report(CheckLevel.ERROR,
JSError.make(Diagnostics.SUPERFLUOUS_SUPPRESS, label, Joiner.on(", ").join(useless)));
}
}
// TODO: Make compiler.compile() package private so we don't have to do this.
errorManager.stderr.clear();
errorManager.generateReport();
// write errors
if (!expectFailure) {
for (String line : errorManager.stderr) {
System.err.println(line);
}
}
if (!outputErrors.isEmpty()) {
Files.write(Paths.get(outputErrors), errorManager.stderr, UTF_8);
}
// write .i.js type summary for this library
if (!outputIjsFile.isEmpty()) {
Files.write(Paths.get(outputIjsFile), compiler.toSource().getBytes(UTF_8));
}
// write file full of information about these sauces
if (!output.isEmpty()) {
ClosureJsLibrary.Builder info =
ClosureJsLibrary.newBuilder()
.setLabel(label)
.setLegacy(legacy)
.addAllNamespace(state.provides)
.addAllModule(modules);
if (!legacy) {
for (DiagnosticType suppression : suppressions) {
if (!Diagnostics.JSCHECKER_ONLY_SUPPRESS_CODES.contains(suppression.key)) {
info.addSuppress(suppression.key);
}
}
}
Files.write(Paths.get(output), info.build().toString().getBytes(UTF_8));
}
return errorManager.getErrorCount() == 0;
}
private static ImmutableList<SourceFile> getSourceFiles(Iterable<String> filenames)
throws IOException {
ImmutableList.Builder<SourceFile> result = new ImmutableList.Builder<>();
for (String filename : filenames) {
if (filename.endsWith(".zip")) {
result.addAll(SourceFile.fromZipFile(filename, UTF_8));
} else {
result.add(SourceFile.fromFile(filename));
}
}
return result.build();
}
public static final class Program implements CommandLineProgram {
@Inject
Program() {}
@Override
public Integer apply(Iterable<String> args) {
JsChecker checker = new JsChecker();
CmdLineParser parser = new CmdLineParser(checker);
parser.getProperties().withAtSyntax(false).withUsageWidth(80);
try {
parser.parseArgument(ImmutableList.copyOf(args));
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println(USAGE);
parser.printUsage(System.err);
System.err.println();
return 1;
}
if (checker.help) {
System.err.println(USAGE);
parser.printUsage(System.out);
System.err.println();
return 0;
}
try {
boolean success = checker.run();
if (success && checker.expectFailure) {
System.err.println("ERROR: Expected failure but did not fail");
}
return success == !checker.expectFailure ? 0 : 1;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}