-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GwtRunner.java
640 lines (571 loc) · 21.5 KB
/
GwtRunner.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/*
* Copyright 2016 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 static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.javascript.jscomp.BasicErrorManager;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CompilerOptions.IsolationMode;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CompilerOptions.TracerMode;
import com.google.javascript.jscomp.DefaultExterns;
import com.google.javascript.jscomp.DependencyOptions;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.ModuleIdentifier;
import com.google.javascript.jscomp.PropertyRenamingPolicy;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.SourceMap;
import com.google.javascript.jscomp.SourceMapInput;
import com.google.javascript.jscomp.VariableRenamingPolicy;
import com.google.javascript.jscomp.WarningLevel;
import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode;
import com.google.javascript.jscomp.deps.SourceCodeEscapers;
import com.google.javascript.jscomp.resources.ResourceLoader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* Runner for the GWT-compiled JSCompiler as a single exported method.
*/
public final class GwtRunner implements EntryPoint {
private static final CompilationLevel DEFAULT_COMPILATION_LEVEL =
CompilationLevel.SIMPLE_OPTIMIZATIONS;
private static final String OUTPUT_MARKER = "%output%";
private static final String OUTPUT_MARKER_JS_STRING = "%output|jsstring%";
private static final String EXTERNS_PREFIX = "externs/";
private GwtRunner() {}
@JsType(namespace = JsPackage.GLOBAL, name = "Object", isNative = true)
private static class Flags {
boolean angularPass;
boolean applyInputSourceMaps;
boolean assumeFunctionWrapper;
String compilationLevel;
boolean dartPass;
JsMap defines;
String dependencyMode;
String[] entryPoint;
String env;
boolean exportLocalPropertyDefinitions;
String[] extraAnnotationNames;
boolean generateExports;
String languageIn;
String languageOut;
boolean checksOnly;
boolean newTypeInf;
String isolationMode;
String outputWrapper;
@Deprecated
boolean polymerPass;
Double polymerVersion; // nb. nullable JS number represented by java.lang.Double in GWT.
boolean preserveTypeAnnotations;
boolean processClosurePrimitives;
boolean processCommonJsModules;
boolean renaming;
public String renamePrefixNamespace;
boolean rewritePolyfills;
String warningLevel;
boolean useTypesForOptimization;
String tracerMode;
String moduleResolutionMode;
// These flags do not match the Java compiler JAR.
File[] jsCode;
File[] externs;
boolean createSourceMap;
}
/**
* defaultFlags must have a value set for each field. Otherwise, GWT has no way to create the
* fields inside Flags (as it's native). If Flags is not-native, GWT eats its field names
* anyway.
*/
private static final Flags defaultFlags = new Flags();
static {
defaultFlags.angularPass = false;
defaultFlags.applyInputSourceMaps = true;
defaultFlags.assumeFunctionWrapper = false;
defaultFlags.checksOnly = false;
defaultFlags.compilationLevel = "SIMPLE";
defaultFlags.dartPass = false;
defaultFlags.defines = null;
defaultFlags.dependencyMode = null;
defaultFlags.entryPoint = null;
defaultFlags.env = "BROWSER";
defaultFlags.exportLocalPropertyDefinitions = false;
defaultFlags.extraAnnotationNames = null;
defaultFlags.generateExports = false;
defaultFlags.languageIn = "ECMASCRIPT6";
defaultFlags.languageOut = "ECMASCRIPT5";
defaultFlags.newTypeInf = false;
defaultFlags.isolationMode = "NONE";
defaultFlags.outputWrapper = null;
defaultFlags.polymerPass = false;
defaultFlags.polymerVersion = null;
defaultFlags.preserveTypeAnnotations = false;
defaultFlags.processClosurePrimitives = true;
defaultFlags.processCommonJsModules = false;
defaultFlags.renamePrefixNamespace = null;
defaultFlags.renaming = true;
defaultFlags.rewritePolyfills = true;
defaultFlags.warningLevel = "DEFAULT";
defaultFlags.useTypesForOptimization = true;
defaultFlags.jsCode = null;
defaultFlags.externs = null;
defaultFlags.createSourceMap = false;
defaultFlags.tracerMode = "OFF";
defaultFlags.moduleResolutionMode = "BROWSER";
}
@JsType(namespace = JsPackage.GLOBAL, name = "Object", isNative = true)
private static class File {
@JsProperty String path;
@JsProperty String src;
@JsProperty String sourceMap;
}
@JsType(namespace = JsPackage.GLOBAL, name = "Object", isNative = true)
private static class ModuleOutput {
@JsProperty String compiledCode;
@JsProperty String sourceMap;
@JsProperty JavaScriptObject[] errors;
@JsProperty JavaScriptObject[] warnings;
}
/**
* Reliably returns a string array from the flags/key combo.
*/
private static native String[] getStringArray(Flags flags, String key) /*-{
var value = flags[key];
if (value == null) {
return [];
} else if (Array.isArray(value)) {
return value;
}
return [value];
}-*/;
/**
* Wraps a generic JS object used as a map.
*/
private static final class JsMap extends JavaScriptObject {
protected JsMap() {}
/** @return This {@code JsMap} as a {@link Map}. */
ImmutableMap<String, Object> asMap() {
ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>();
for (String key : keys(this)) {
builder.put(key, get(key));
}
return builder.build();
}
/**
* Validates that the values of this {@code JsMap} are primitives: either number, string or
* boolean. Note that {@code typeof null} is object.
*/
private native void validatePrimitiveTypes() /*-{
var valid = {'number': '', 'string': '', 'boolean': ''};
Object.keys(this).forEach(function(key) {
var type = typeof this[key];
if (!(type in valid)) {
throw new TypeError('Type of define `' + key + '` unsupported: ' + type);
}
}, this);
}-*/;
private native Object get(String key) /*-{
return this[key];
}-*/;
}
@JsMethod(name = "keys", namespace = "Object")
private static native String[] keys(Object o);
private static native JavaScriptObject createError(String file, String description, String type,
int lineNo, int charNo) /*-{
return {file: file, description: description, type: type, lineNo: lineNo, charNo: charNo};
}-*/;
/**
* Convert a list of {@link JSError} instances to a JS array containing plain objects.
*/
private static JavaScriptObject[] toNativeErrorArray(List<JSError> errors) {
JavaScriptObject[] out = new JavaScriptObject[errors.size()];
for (int i = 0; i < errors.size(); ++i) {
JSError error = errors.get(i);
DiagnosticType type = error.getType();
out[i] = createError(error.sourceName, error.description, type != null ? type.key : null,
error.lineNumber, error.getCharno());
}
return out;
}
/**
* Generates the output code, taking into account the passed {@code outputWrapper}.
*/
private static String writeOutput(Compiler compiler, String outputWrapper) {
String code = compiler.toSource();
if (outputWrapper == null) {
return code;
}
String marker;
int pos = outputWrapper.indexOf(OUTPUT_MARKER_JS_STRING);
if (pos != -1) {
// With jsstring, run SourceCodeEscapers (as per AbstractCommandLineRunner).
code = SourceCodeEscapers.javascriptEscaper().escape(code);
marker = OUTPUT_MARKER_JS_STRING;
} else {
pos = outputWrapper.indexOf(OUTPUT_MARKER);
if (pos == -1) {
return code; // neither marker could be found, just return code
}
marker = OUTPUT_MARKER;
}
String prefix = outputWrapper.substring(0, pos);
SourceMap sourceMap = compiler.getSourceMap();
if (sourceMap != null) {
sourceMap.setWrapperPrefix(prefix);
}
return prefix + code + outputWrapper.substring(pos + marker.length());
}
private static List<SourceFile> createExterns(CompilerOptions.Environment environment) {
String[] resources = ResourceLoader.resourceList(GwtRunner.class);
Map<String, SourceFile> all = new HashMap<>();
for (String res : resources) {
if (res.startsWith(EXTERNS_PREFIX)) {
String filename = res.substring(EXTERNS_PREFIX.length());
all.put(filename, SourceFile.fromCode("externs.zip//" + res,
ResourceLoader.loadTextResource(GwtRunner.class, res)));
}
}
return DefaultExterns.prepareExterns(environment, all);
}
private static ImmutableList<ModuleIdentifier> createEntryPoints(String[] entryPoints) {
ImmutableList.Builder<ModuleIdentifier> builder = new ImmutableList.Builder<>();
for (String entryPoint : entryPoints) {
if (entryPoint.startsWith("goog:")) {
builder.add(ModuleIdentifier.forClosure(entryPoint));
} else {
builder.add(ModuleIdentifier.forFile(entryPoint));
}
}
return builder.build();
}
private static DependencyOptions createDependencyOptions(
CompilerOptions.DependencyMode dependencyMode,
List<ModuleIdentifier> entryPoints) {
// Copied from from AbstractCommandLineRunner.java.
if (dependencyMode == CompilerOptions.DependencyMode.STRICT) {
if (entryPoints.isEmpty()) {
throw new RuntimeException(
"When dependencyMode=STRICT, you must specify at least one entry point");
}
return new DependencyOptions()
.setDependencyPruning(true)
.setDependencySorting(true)
.setMoocherDropping(true)
.setEntryPoints(entryPoints);
} else if (dependencyMode == CompilerOptions.DependencyMode.LOOSE || !entryPoints.isEmpty()) {
return new DependencyOptions()
.setDependencyPruning(true)
.setDependencySorting(true)
.setMoocherDropping(false)
.setEntryPoints(entryPoints);
}
return null;
}
private static void applyDefaultOptions(CompilerOptions options) {
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
WarningLevel.DEFAULT.setOptionsForWarningLevel(options);
options.setLanguageIn(LanguageMode.ECMASCRIPT_2017);
options.setLanguageOut(LanguageMode.ECMASCRIPT5);
}
private static void applyOptionsFromFlags(CompilerOptions options, Flags flags) {
CompilationLevel level = DEFAULT_COMPILATION_LEVEL;
if (flags.compilationLevel != null) {
level = CompilationLevel.fromString(Ascii.toUpperCase(flags.compilationLevel));
if (level == null) {
throw new RuntimeException(
"Bad value for compilationLevel: " + flags.compilationLevel);
}
}
if (level == CompilationLevel.ADVANCED_OPTIMIZATIONS && !flags.renaming) {
throw new RuntimeException(
"renaming cannot be disabled when ADVANCED_OPTMIZATIONS is used");
}
level.setOptionsForCompilationLevel(options);
if (flags.assumeFunctionWrapper) {
level.setWrappedOutputOptimizations(options);
}
if (flags.useTypesForOptimization) {
level.setTypeBasedOptimizationOptions(options);
}
WarningLevel warningLevel = WarningLevel.DEFAULT;
if (flags.warningLevel != null) {
warningLevel = WarningLevel.valueOf(flags.warningLevel);
}
warningLevel.setOptionsForWarningLevel(options);
CompilerOptions.Environment environment = CompilerOptions.Environment.BROWSER;
if (flags.env != null) {
environment = CompilerOptions.Environment.valueOf(Ascii.toUpperCase(flags.env));
}
options.setEnvironment(environment);
CompilerOptions.DependencyMode dependencyMode = CompilerOptions.DependencyMode.NONE;
if (flags.dependencyMode != null) {
dependencyMode =
CompilerOptions.DependencyMode.valueOf(Ascii.toUpperCase(flags.dependencyMode));
}
List<ModuleIdentifier> entryPoints = createEntryPoints(getStringArray(flags, "entryPoint"));
DependencyOptions dependencyOptions = createDependencyOptions(dependencyMode, entryPoints);
if (dependencyOptions != null) {
options.setDependencyOptions(dependencyOptions);
}
LanguageMode languageIn = LanguageMode.fromString(flags.languageIn);
if (languageIn != null) {
options.setLanguageIn(languageIn);
}
LanguageMode languageOut = LanguageMode.fromString(flags.languageOut);
if (languageOut != null) {
options.setLanguageOut(languageOut);
}
if (flags.createSourceMap) {
options.setSourceMapOutputPath("%output%");
}
if (flags.defines != null) {
// CompilerOptions also validates types, but uses Preconditions and therefore won't generate
// a useful exception.
flags.defines.validatePrimitiveTypes();
options.setDefineReplacements(flags.defines.asMap());
}
if (flags.extraAnnotationNames != null) {
options.setExtraAnnotationNames(Arrays.asList(flags.extraAnnotationNames));
}
if (flags.tracerMode != null) {
options.setTracerMode(TracerMode.valueOf(flags.tracerMode));
}
if (flags.moduleResolutionMode != null) {
options.setModuleResolutionMode(ResolutionMode.valueOf(flags.moduleResolutionMode));
}
if (flags.isolationMode != null
&& IsolationMode.valueOf(flags.isolationMode) == IsolationMode.IIFE) {
flags.outputWrapper = "(function(){%output%}).call(this);";
}
options.setAngularPass(flags.angularPass);
options.setApplyInputSourceMaps(flags.applyInputSourceMaps);
options.setChecksOnly(flags.checksOnly);
options.setDartPass(flags.dartPass);
options.setExportLocalPropertyDefinitions(flags.exportLocalPropertyDefinitions);
options.setGenerateExports(flags.generateExports);
options.setNewTypeInference(flags.newTypeInf);
if (flags.polymerPass) {
options.setPolymerVersion(1);
} else if (flags.polymerVersion != null) {
options.setPolymerVersion(flags.polymerVersion.intValue());
}
options.setPreserveTypeAnnotations(flags.preserveTypeAnnotations);
options.setClosurePass(flags.processClosurePrimitives);
options.setProcessCommonJSModules(flags.processCommonJsModules);
options.setRenamePrefixNamespace(flags.renamePrefixNamespace);
if (!flags.renaming) {
options.setVariableRenaming(VariableRenamingPolicy.OFF);
options.setPropertyRenaming(PropertyRenamingPolicy.OFF);
}
options.setRewritePolyfills(flags.rewritePolyfills);
}
private static void disableUnsupportedOptions(CompilerOptions options) {
options.getDependencyOptions().setDependencySorting(false);
}
private static List<SourceFile> fromFileArray(File[] src, String unknownPrefix) {
List<SourceFile> out = new ArrayList<>();
if (src != null) {
for (int i = 0; i < src.length; ++i) {
File file = src[i];
String path = file.path;
if (path == null) {
path = unknownPrefix + i;
}
out.add(SourceFile.fromCode(path, nullToEmpty(file.src)));
}
}
return out;
}
private static ImmutableMap<String, SourceMapInput> buildSourceMaps(
File[] src, String unknownPrefix) {
ImmutableMap.Builder<String, SourceMapInput> inputSourceMaps = new ImmutableMap.Builder<>();
if (src != null) {
for (int i = 0; i < src.length; ++i) {
File file = src[i];
if (isNullOrEmpty(file.sourceMap)) {
continue;
}
String path = file.path;
if (path == null) {
path = unknownPrefix + i;
}
path += ".map";
SourceFile sf = SourceFile.fromCode(path, file.sourceMap);
inputSourceMaps.put(path, new SourceMapInput(sf));
}
}
return inputSourceMaps.build();
}
/**
* Updates the destination flags (user input) with source flags (the defaults). Returns a list
* of flags that are on the destination, but not on the source.
*/
private static native String[] updateFlags(Flags dst, Flags src) /*-{
for (var k in src) {
if (!(k in dst)) {
dst[k] = src[k];
}
}
var unhandled = [];
for (var k in dst) {
if (!(k in src)) {
unhandled.push(k);
}
}
return unhandled;
}-*/;
/**
* Public compiler call. Exposed in {@link #exportCompile}.
*/
public static ModuleOutput compile(Flags flags) {
String[] unhandled = updateFlags(flags, defaultFlags);
if (unhandled.length > 0) {
throw new RuntimeException("Unhandled flag: " + unhandled[0]);
}
List<SourceFile> jsCode = fromFileArray(flags.jsCode, "Input_");
ImmutableMap<String, SourceMapInput> sourceMaps = buildSourceMaps(flags.jsCode, "Input_");
CompilerOptions options = new CompilerOptions();
applyDefaultOptions(options);
applyOptionsFromFlags(options, flags);
options.setInputSourceMaps(sourceMaps);
disableUnsupportedOptions(options);
List<SourceFile> externs = fromFileArray(flags.externs, "Extern_");
externs.addAll(createExterns(options.getEnvironment()));
NodeErrorManager errorManager = new NodeErrorManager();
Compiler compiler = new Compiler(new NodePrintStream());
compiler.setErrorManager(errorManager);
compiler.compile(externs, jsCode, options);
ModuleOutput output = new ModuleOutput();
output.compiledCode = writeOutput(compiler, flags.outputWrapper);
output.errors = toNativeErrorArray(errorManager.errors);
output.warnings = toNativeErrorArray(errorManager.warnings);
if (flags.createSourceMap) {
StringBuilder b = new StringBuilder();
try {
compiler.getSourceMap().appendTo(b, "");
} catch (IOException e) {
// ignore
}
output.sourceMap = b.toString();
}
return output;
}
/**
* Exports the {@link #compile} method via JSNI.
*
* This will be placed on {@code module.exports}, {@code self.compile} or {@code window.compile}.
*/
public native void exportCompile() /*-{
var fn = $entry(@com.google.javascript.jscomp.gwt.client.GwtRunner::compile(*));
if (typeof module !== 'undefined' && module.exports) {
module.exports = fn;
} else if (typeof self === 'object') {
self.compile = fn;
} else {
window.compile = fn;
}
}-*/;
@Override
public void onModuleLoad() {
exportCompile();
}
/**
* Custom {@link BasicErrorManager} to record {@link JSError} instances.
*/
private static class NodeErrorManager extends BasicErrorManager {
final List<JSError> errors = new ArrayList<>();
final List<JSError> warnings = new ArrayList<>();
@Override
public void println(CheckLevel level, JSError error) {
if (level == CheckLevel.ERROR) {
errors.add(error);
} else if (level == CheckLevel.WARNING) {
warnings.add(error);
}
}
@Override
public void printSummary() {}
}
// TODO(johnlenz): remove this once GWT has a proper PrintStream implementation
private static class NodePrintStream extends PrintStream {
private String line = "";
NodePrintStream() {
super((OutputStream) null);
}
@Override
public void println(String s) {
print(s + "\n");
}
@Override
public void print(String s) {
if (useStdErr()) {
writeToStdErr(s);
} else {
writeFinishedLinesToConsole(s);
}
}
private void writeFinishedLinesToConsole(String s) {
line = line + s;
int start = 0;
int end = 0;
while ((end = line.indexOf('\n', start)) != -1) {
writeToConsole(line.substring(start, end));
start = end + 1;
}
line = line.substring(start);
}
private static native boolean useStdErr() /*-{
return !!(typeof process != "undefined" && process.stderr);
}-*/;
private native boolean writeToStdErr(String s) /*-{
process.stderr.write(s);
}-*/;
// NOTE: console methods always add a newline following the text.
private native void writeToConsole(String s) /*-{
console.log(s);
}-*/;
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void write(byte[] buffer, int offset, int length) {
}
@Override
public void write(int oneByte) {
}
}
}