-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JsfileParser.java
431 lines (397 loc) · 15.8 KB
/
JsfileParser.java
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*
* Copyright 2015 The Closure Compiler Authors.
*
* 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.gwt.client;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.TreeMultimap;
import com.google.common.collect.TreeMultiset;
import com.google.javascript.jscomp.BasicErrorManager;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.GatherModuleMetadata;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode;
import com.google.javascript.jscomp.gwt.client.Util.JsArray;
import com.google.javascript.jscomp.gwt.client.Util.JsObject;
import com.google.javascript.jscomp.modules.ModuleMetadataMap.ModuleMetadata;
import com.google.javascript.jscomp.parsing.Config;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Nullable;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsMethod;
/**
* GWT module to parse files for dependency and
* {@literal @}{@code fileoverview} annotation
* information.
*/
public class JsfileParser {
/**
* All the information parsed out of a single file.
* Exported as a JSON object:
* <pre> {@code {
* "custom_annotations": {?Array<[string, string]>}, @.*
* "goog": {?bool}, whether 'goog' is implicitly required
* "has_soy_delcalls": {?Array<string>}, @fileoverview @hassoydelcall {.*}
* "has_soy_deltemplates": {?Array<string>}, @fileoverview @hassoydeltemplate {.*}
* "imported_modules": {?Array<string>}, import ... from .*
* "is_config": {?bool}, @fileoverview @config
* "is_externs": {?bool}, @fileoverview @externs
* "load_flags": {?Array<[string, string]>},
* "mod_name": {?Array<string>}, @fileoverview @modName .*, @modName {.*}
* "mods": {?Array<string>}, @fileoverview @mods {.*}
* "provide_goog": {?bool}, @fileoverview @provideGoog
* "provides": {?Array<string>},
* "requires": {?Array<string>}, note: look for goog.* for 'goog'
* "requires_css": {?Array<string>}, @fileoverview @requirecss {.*}
* "testonly": {?bool}, goog.setTestOnly
* "type_requires": {?Array<string>},
* "visibility: {?Array<string>}, @fileoverview @visibility {.*}
* }}</pre>
* Any trivial values are omitted.
*/
static final class FileInfo {
final ErrorReporter reporter;
boolean goog = false;
boolean isConfig = false;
boolean isExterns = false;
boolean provideGoog = false;
boolean testonly = false;
final Set<String> hasSoyDelcalls = new TreeSet<>();
final Set<String> hasSoyDeltemplates = new TreeSet<>();
// Use a LinkedHashSet as import order matters!
final Set<String> importedModules = new LinkedHashSet<>();
final List<String> modName = new ArrayList<>();
final List<String> mods = new ArrayList<>();
// Note: multiple copies doesn't make much sense, but we report
// each copy so that calling code can choose how to handle it
final Multiset<String> provides = TreeMultiset.create();
final Multiset<String> requires = TreeMultiset.create();
final Multiset<String> typeRequires = TreeMultiset.create();
final Multiset<String> requiresCss = TreeMultiset.create();
final Multiset<String> visibility = TreeMultiset.create();
final Multimap<String, String> customAnnotations = TreeMultimap.create();
final Multimap<String, String> loadFlags = TreeMultimap.create();
FileInfo(ErrorReporter reporter) {
this.reporter = reporter;
}
private void handleGoog() {
if (provideGoog) {
provides.add("goog");
} else if (goog) {
requires.add("goog");
}
}
/** Exports the file info as a JSON object. */
JsObject<Object> full() {
handleGoog();
return new SparseObject()
.set("custom_annotations", customAnnotations)
.set("goog", goog)
.set("has_soy_delcalls", hasSoyDelcalls)
.set("has_soy_deltemplates", hasSoyDeltemplates)
.set("imported_modules", importedModules)
.set("is_config", isConfig)
.set("is_externs", isExterns)
.set("load_flags", loadFlags)
.set("modName", modName)
.set("mods", mods)
.set("provide_goog", provideGoog)
.set("provides", provides)
.set("requires", requires)
.set("requiresCss", requiresCss)
.set("testonly", testonly)
.set("type_requires", typeRequires)
.set("visibility", visibility)
.object;
}
}
/**
* Exports the {@link #compile} method via JSNI.
*
* <p>This will be placed on {@code module.exports.gjd} or the global {@code jscomp.gjd}.
*/
public native void exportGjd() /*-{
var fn = $entry(@com.google.javascript.jscomp.gwt.client.JsfileParser::gjd(*));
if (typeof module !== 'undefined' && module.exports) {
module.exports.gjd = fn;
}
}-*/;
/** Represents a single JSDoc annotation, with an optional argument. */
private static class CommentAnnotation {
/** Annotation name, e.g. "@fileoverview" or "@externs". */
final String name;
/**
* Annotation value: either the bare identifier immediately after the
* annotation, or else string in braces.
*/
final String value;
CommentAnnotation(String name, String value) {
this.name = name;
this.value = value;
}
/** Returns all the annotations in a given comment string. */
static List<CommentAnnotation> parse(String comment) {
// TODO(sdh): This is reinventing a large part of JSDocInfoParser. We should
// try to consolidate as much as possible. This requires several steps:
// 1. Make all the annotations we look for first-class in JSDocInfo
// 2. Support custom annotations (may already be done?)
// 3. Fix up existing code so that all these annotations are in @fileoverview
// 4. Change this code to simply inspect the script's JSDocInfo instead of re-parsing
List<CommentAnnotation> out = new ArrayList<>();
Matcher matcher = ANNOTATION_RE.matcher(comment);
while (matcher.find()) {
String name = matcher.group(ANNOTATION_NAME_GROUP);
String value = Strings.nullToEmpty(matcher.group(ANNOTATION_VALUE_GROUP));
out.add(new CommentAnnotation(name, value));
}
return out;
}
// Regex for a JSDoc annotation with an `@name` and an optional brace-delimited `{value}`.
// The `@` should not match the middle of a word.
private static final Pattern ANNOTATION_RE =
Pattern.compile(
"(?:[^a-zA-Z0-9_$]|^)(@[a-zA-Z]+)(?:\\s*\\{\\s*([^}\\t\\n\\v\\f\\r ]+)\\s*\\})?");
private static final int ANNOTATION_NAME_GROUP = 1;
private static final int ANNOTATION_VALUE_GROUP = 2;
}
/** Method exported to JS to parse a file for dependencies and annotations. */
@JsMethod(namespace = "jscomp")
public static JsObject<Object> gjd(String code, String filename, @Nullable Reporter reporter) {
return parse(code, filename, reporter).full();
}
/** Internal implementation to produce the {@link FileInfo} object. */
private static FileInfo parse(String code, String filename, @Nullable Reporter reporter) {
ErrorReporter errorReporter = new DelegatingReporter(reporter);
Compiler compiler =
new Compiler(
new BasicErrorManager() {
@Override
public void println(CheckLevel level, JSError error) {
if (level == CheckLevel.ERROR) {
errorReporter.error(
error.description,
error.sourceName,
error.getLineNumber(),
error.getCharno());
} else if (level == CheckLevel.WARNING) {
errorReporter.warning(
error.description,
error.sourceName,
error.getLineNumber(),
error.getCharno());
}
}
@Override
protected void printSummary() {}
});
SourceFile source = SourceFile.fromCode(filename, code);
compiler.init(
ImmutableList.<SourceFile>of(),
ImmutableList.<SourceFile>of(source),
new CompilerOptions());
Config config =
ParserRunner.createConfig(
// TODO(sdh): ES8 STRICT, with a non-strict fallback - then give warnings.
Config.LanguageMode.ECMASCRIPT8,
Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE,
Config.RunMode.KEEP_GOING,
/* extraAnnotationNames */ ImmutableSet.<String>of(),
/* parseInlineSourceMaps */ true,
Config.StrictMode.SLOPPY);
FileInfo info = new FileInfo(errorReporter);
ParserRunner.ParseResult parsed = ParserRunner.parse(source, code, config, errorReporter);
parsed.ast.setInputId(new InputId(filename));
String version = parsed.features.version();
if (!version.equals("es3")) {
info.loadFlags.put("lang", version);
}
for (Comment comment : parsed.comments) {
if (comment.type == Comment.Type.JSDOC) {
parseComment(comment, info);
}
}
GatherModuleMetadata gatherModuleMetadata =
new GatherModuleMetadata(
compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER);
gatherModuleMetadata.process(new Node(Token.ROOT), parsed.ast);
compiler.generateReport();
ModuleMetadata module =
Iterables.getOnlyElement(
compiler.getModuleMetadataMap().getModulesByPath().values());
if (module.isEs6Module()) {
info.loadFlags.put("module", "es6");
} else if (module.isGoogModule()) {
info.loadFlags.put("module", "goog");
}
info.goog = module.usesClosure();
// If something doesn't have an external dependency on Closure, then it does not have any
// externally required files or symbols to provide. This is needed for bundles that contain
// base.js as well as other files. These bundles should look like they do not require or provide
// anything at all.
if (module.usesClosure()) {
info.provides.addAll(module.googNamespaces());
info.requires.addAll(module.requiredGoogNamespaces());
info.typeRequires.addAll(module.requiredTypes());
info.testonly = module.isTestOnly();
}
info.importedModules.addAll(module.es6ImportSpecifiers().elementSet());
return info;
}
/** Mutates {@code info} with information from the given {@code comment}. */
private static void parseComment(Comment comment, FileInfo info) {
boolean fileOverview = comment.value.contains("@fileoverview");
for (CommentAnnotation annotation : CommentAnnotation.parse(comment.value)) {
switch (annotation.name) {
case "@fileoverview":
case "@author":
case "@see":
case "@link":
break;
case "@mods":
if (!annotation.value.isEmpty()) {
info.mods.add(annotation.value);
}
break;
case "@visibility":
if (!annotation.value.isEmpty()) {
info.visibility.add(annotation.value);
}
break;
case "@modName":
if (!annotation.value.isEmpty()) {
info.modName.add(annotation.value);
}
break;
case "@config":
info.isConfig = true;
break;
case "@provideGoog":
info.provideGoog = true;
break;
case "@requirecss":
if (!annotation.value.isEmpty()) {
info.requiresCss.add(annotation.value);
}
break;
case "@hassoydeltemplate":
if (!annotation.value.isEmpty()) {
info.hasSoyDeltemplates.add(annotation.value);
}
break;
case "@hassoydelcall":
if (!annotation.value.isEmpty()) {
info.hasSoyDelcalls.add(annotation.value);
}
break;
case "@externs":
info.isExterns = true;
break;
case "@enhanceable":
case "@pintomodule":
info.customAnnotations.put(annotation.name.substring(1), annotation.value);
break;
case "@enhance":
if (!annotation.value.isEmpty()) {
info.customAnnotations.put(annotation.name.substring(1), annotation.value);
}
break;
default:
if (fileOverview) {
info.customAnnotations.put(annotation.name.substring(1), annotation.value);
}
}
}
}
/** JS function interface for reporting errors. */
@JsFunction
public interface Reporter {
void report(boolean fatal, String message, String sourceName, int line, int lineOffset);
}
private static final class DelegatingReporter implements ErrorReporter {
final Reporter delegate;
DelegatingReporter(Reporter delegate) {
this.delegate = delegate != null ? delegate : NULL_REPORTER;
}
@Override
public void warning(String message, String sourceName, int line, int lineOffset) {
delegate.report(false, message, sourceName, line, lineOffset);
}
@Override
public void error(String message, String sourceName, int line, int lineOffset) {
delegate.report(true, message, sourceName, line, lineOffset);
}
}
private static final Reporter NULL_REPORTER = new Reporter() {
@Override
public void report(
boolean fatal, String message, String sourceName, int line, int lineOffset) {}
};
/** Sparse object helper class: only adds non-trivial values. */
private static class SparseObject {
final JsObject<Object> object = new JsObject<>();
SparseObject set(String key, Iterable<String> iterable) {
JsArray<String> array = JsArray.copyOf(iterable);
if (array.getLength() > 0) {
object.set(key, array);
}
return this;
}
SparseObject set(String key, Multimap<String, String> map) {
JsArray<JsArray<String>> array = new JsArray<>();
for (Map.Entry<String, String> entry : map.entries()) {
JsArray<String> pair = new JsArray<>();
pair.push(entry.getKey());
pair.push(entry.getValue());
array.push(pair);
}
if (array.getLength() > 0) {
object.set(key, array);
}
return this;
}
SparseObject set(String key, String value) {
if (value != null && !value.isEmpty()) {
object.set(key, value);
}
return this;
}
SparseObject set(String key, boolean value) {
if (value) {
object.set(key, value);
}
return this;
}
}
}