-
Notifications
You must be signed in to change notification settings - Fork 142
/
JavaScriptImplGenerator.java
744 lines (678 loc) · 28.3 KB
/
JavaScriptImplGenerator.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
/*
* Copyright 2015 Google Inc.
*
* 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.j2cl.generator;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.j2cl.ast.AstUtils;
import com.google.j2cl.ast.DeclaredTypeDescriptor;
import com.google.j2cl.ast.Expression;
import com.google.j2cl.ast.Field;
import com.google.j2cl.ast.JavaScriptConstructorReference;
import com.google.j2cl.ast.ManglingNameUtils;
import com.google.j2cl.ast.Method;
import com.google.j2cl.ast.MethodDescriptor;
import com.google.j2cl.ast.MethodLike;
import com.google.j2cl.ast.Type;
import com.google.j2cl.ast.TypeDeclaration;
import com.google.j2cl.ast.TypeDescriptor;
import com.google.j2cl.ast.TypeDescriptors;
import com.google.j2cl.ast.TypeDescriptors.BootstrapType;
import com.google.j2cl.ast.TypeVariable;
import com.google.j2cl.ast.Variable;
import com.google.j2cl.ast.Visibility;
import com.google.j2cl.common.FilePosition;
import com.google.j2cl.common.InternalCompilerError;
import com.google.j2cl.common.Problems;
import com.google.j2cl.common.SourcePosition;
import com.google.j2cl.generator.ImportGatherer.ImportCategory;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/** Generates JavaScript source impl files. */
public class JavaScriptImplGenerator extends JavaScriptGenerator {
private NativeJavaScriptFile nativeSource;
private final ClosureTypesGenerator closureTypesGenerator;
protected final StatementTranspiler statementTranspiler;
public static final String FILE_SUFFIX = ".impl.java.js";
public JavaScriptImplGenerator(Problems problems, Type type) {
super(problems, type);
this.statementTranspiler = new StatementTranspiler(sourceBuilder, environment);
this.closureTypesGenerator = new ClosureTypesGenerator(environment);
}
private static String getMethodQualifiers(MethodDescriptor methodDescriptor) {
String staticQualifier = methodDescriptor.isStatic() ? "static " : "";
if (!methodDescriptor.isAbstract() && methodDescriptor.isJsAsync()) {
// Do not emit the "async" modifier for abstract methods since jscompiler will emit
// a warning due to the way async are transpiled down.
return staticQualifier + "async ";
}
return staticQualifier;
}
/**
* Emits the method header including (static) (async) (getter/setter) methodName(parametersList).
*/
private void emitMethodHeader(Method method) {
MethodDescriptor methodDescriptor = method.getDescriptor();
sourceBuilder.append(getMethodQualifiers(methodDescriptor));
sourceBuilder.emitWithMapping(
method.getSourcePosition(),
() -> sourceBuilder.append(ManglingNameUtils.getMangledName(methodDescriptor)));
sourceBuilder.append("(");
// TODO(goktug): Reuse with Expression transpiler which has similar logic.
String separator = "";
for (int i = 0; i < method.getParameters().size(); i++) {
sourceBuilder.append(separator);
// Emit parameters in the more readable inline short form.
emitParameter(method, i);
separator = ", ";
}
sourceBuilder.append(") ");
}
private void emitParameter(MethodLike expression, int i) {
Variable parameter = expression.getParameters().get(i);
if (parameter == expression.getJsVarargsParameter()) {
sourceBuilder.append("...");
}
sourceBuilder.append(
"/** " + closureTypesGenerator.getJsDocForParameter(expression, i) + " */ ");
sourceBuilder.emitWithMapping(
// Only map parameters if they are named.
AstUtils.emptySourcePositionIfNotNamed(parameter.getSourcePosition()),
() -> sourceBuilder.append(environment.getUniqueNameForVariable(parameter)));
}
@Override
public String getSuffix() {
return FILE_SUFFIX;
}
public void setNativeSource(NativeJavaScriptFile nativeSource) {
this.nativeSource = checkNotNull(nativeSource);
}
@Override
public String renderOutput() {
try {
renderImports();
if (type.isJsEnum()) {
renderClosureEnum();
} else {
renderClass();
}
renderExports();
return sourceBuilder.build();
} catch (RuntimeException e) {
// Catch all unchecked exceptions and rethrow them with more context to make debugging easier.
// Yes this is really being done on purpose.
throw new InternalCompilerError(
e,
"Error generating source for type %s.",
type.getDeclaration().getQualifiedBinaryName());
}
}
private void renderClosureEnum() {
TypeDeclaration typeDeclaration = type.getDeclaration();
sourceBuilder.append(
"/** @enum {"
+ closureTypesGenerator.getClosureTypeString(
AstUtils.getJsEnumValueFieldType(typeDeclaration))
+ "}");
if (type.getDeclaration().isDeprecated()) {
sourceBuilder.append(" @deprecated");
}
sourceBuilder.appendln(" */");
sourceBuilder.append("const ");
sourceBuilder.emitWithMapping(
type.getSourcePosition(),
() -> sourceBuilder.append(environment.aliasForType(typeDeclaration)));
sourceBuilder.append(" = ");
sourceBuilder.openBrace();
sourceBuilder.newLine();
for (Field field : type.getStaticFields()) {
sourceBuilder.emitWithMemberMapping(
field,
() -> {
if (field.getDescriptor().isDeprecated()) {
sourceBuilder.appendln(" /** @deprecated */");
}
sourceBuilder.emitWithMapping(
field.getSourcePosition(),
() -> {
sourceBuilder.append(ManglingNameUtils.getMangledName(field.getDescriptor()));
});
sourceBuilder.append(" : ");
renderExpression(field.getInitializer());
sourceBuilder.append(",");
sourceBuilder.newLine();
});
}
sourceBuilder.closeBrace();
sourceBuilder.append(";");
sourceBuilder.newLine();
}
public void renderClass() {
renderTypeAnnotation();
renderClassBody();
renderClassMetadata();
renderMarkImplementorCalls();
renderStaticFieldDeclarations();
renderNativeSource();
}
private void renderImports() {
TypeDeclaration typeDeclaration = type.getDeclaration();
// goog.module(...) declaration.
sourceBuilder.appendln("goog.module('" + typeDeclaration.getImplModuleName() + "');");
sourceBuilder.newLine();
// goog.require(...) for eager imports.
Map<String, String> aliasesByPath = new HashMap<>();
Iterable<Import> eagerImports = sortImports(importsByCategory.get(ImportCategory.LOADTIME));
for (Import eagerImport : eagerImports) {
String alias = eagerImport.getAlias();
String path = eagerImport.getImplModulePath();
String previousAlias = aliasesByPath.get(path);
if (previousAlias == null) {
sourceBuilder.appendln("const " + alias + " = goog.require('" + path + "');");
aliasesByPath.put(path, alias);
} else {
// Do not goog.require second time to avoid JsCompiler warnings.
sourceBuilder.appendln("const " + alias + " = " + previousAlias + ";");
}
}
if (!Iterables.isEmpty(eagerImports)) {
sourceBuilder.newLine();
}
// goog.forwardDeclare(...) for lazy imports.
Iterable<Import> lazyImports =
sortImports(
Iterables.concat(
importsByCategory.get(ImportCategory.RUNTIME),
importsByCategory.get(ImportCategory.JSDOC)));
for (Import lazyImport : lazyImports) {
String alias = lazyImport.getAlias();
String path = lazyImport.getImplModulePath();
sourceBuilder.appendln("let " + alias + " = goog.forwardDeclare('" + path + "');");
}
if (!Iterables.isEmpty(lazyImports)) {
sourceBuilder.newLine();
}
}
private void renderTypeAnnotation() {
if (type.isOverlayImplementation()) {
// Do nothing.
} else if (type.isInterface()) {
sourceBuilder.appendLines("/**", " * @interface");
sourceBuilder.newLine();
if (type.getDeclaration().hasTypeParameters()) {
String templates =
closureTypesGenerator.getCommaSeparatedClosureTypesString(
type.getDeclaration().getTypeParameterDescriptors());
sourceBuilder.appendln(" * @template " + templates);
}
for (DeclaredTypeDescriptor superInterfaceType : type.getSuperInterfaceTypeDescriptors()) {
renderIfClassExists(" * @extends {%s}", superInterfaceType, sourceBuilder);
}
if (type.getDeclaration().isDeprecated()) {
sourceBuilder.appendln(" * @deprecated");
}
sourceBuilder.appendln(" */");
} else { // Not an interface so it is a Class.
SourceBuilder buffer = new SourceBuilder();
if (type.isAbstract()) {
buffer.appendln(" * @abstract");
}
if (type.getDeclaration().hasTypeParameters()) {
String templates =
closureTypesGenerator.getCommaSeparatedClosureTypesString(
type.getDeclaration().getTypeParameterDescriptors());
buffer.appendln(" * @template " + templates);
}
if (type.getDeclaration().isDeprecated()) {
buffer.appendln(" * @deprecated");
}
if (type.getSuperTypeDescriptor() != null
&& type.getSuperTypeDescriptor().hasTypeArguments()) {
// No need to render if it does not have type arguments as it will also appear in the
// extends clause of the class definition.
renderIfClassExists(" * @extends {%s}", type.getSuperTypeDescriptor(), buffer);
}
for (DeclaredTypeDescriptor superInterfaceType : type.getSuperInterfaceTypeDescriptors()) {
renderIfClassExists(" * @implements {%s}", superInterfaceType, buffer);
}
String annotation = buffer.build();
if (!annotation.isEmpty()) {
sourceBuilder.appendln("/**");
sourceBuilder.append(annotation);
sourceBuilder.appendln(" */");
}
}
}
/**
* Renders the line using {@code formatString} only if {@code typeDescriptor} is an actual class
* in JavaScript.
*
* <p>Used to render the @extends/@implements clauses.
*/
private void renderIfClassExists(
String formatString, DeclaredTypeDescriptor typeDescriptor, SourceBuilder sourceBuilder) {
if (doesClassExistInJavaScript(typeDescriptor)) {
String typeArgumentsString =
typeDescriptor.hasTypeArguments()
? typeDescriptor.getTypeArgumentDescriptors().stream()
.map(td -> closureTypesGenerator.getClosureTypeString(td))
.collect(Collectors.joining(", ", "<", ">"))
: "";
sourceBuilder.appendln(
String.format(
formatString,
environment.aliasForType(typeDescriptor.getTypeDeclaration()) + typeArgumentsString));
}
}
private boolean doesClassExistInJavaScript(DeclaredTypeDescriptor type) {
return !type.isStarOrUnknown() && !type.isJsFunctionInterface();
}
private void renderClassBody() {
sourceBuilder.append("class ");
sourceBuilder.emitWithMapping(
type.getSourcePosition(),
() -> sourceBuilder.append(environment.aliasForType(type.getDeclaration())));
sourceBuilder.append(" " + getExtendsClause(type, environment));
sourceBuilder.openBrace();
sourceBuilder.newLine();
renderTypeMethods();
renderMarkImplementorMethod();
renderIsInstanceMethod();
renderCopyMethod();
renderLoadModules();
sourceBuilder.closeBrace();
sourceBuilder.newLine();
}
private static String getExtendsClause(Type type, GenerationEnvironment environment) {
DeclaredTypeDescriptor superTypeDescriptor = type.getSuperTypeDescriptor();
if (superTypeDescriptor == null || superTypeDescriptor.isStarOrUnknown()) {
return "";
}
String superTypeName = environment.aliasForType(superTypeDescriptor);
return String.format("extends %s ", superTypeName);
}
private void renderTypeMethods() {
for (Method method : type.getMethods()) {
sourceBuilder.emitWithMemberMapping(
method,
() -> {
if (method.isNative()) {
// If the method is native, output JsDoc comments so it can serve as a template for
// native.js. However if the method is pointing to a different namespace then there
// is no point on doing that since it cannot be provided via a native.js file.
if (method.getDescriptor().hasJsNamespace()) {
return;
}
sourceBuilder.append("// ");
renderMethodJsDoc(method);
sourceBuilder.append("// native ");
emitMethodHeader(method);
} else {
renderMethodJsDoc(method);
emitMethodHeader(method);
statementTranspiler.renderStatement(method.getBody());
}
sourceBuilder.newLine();
});
}
}
private void renderMethodJsDoc(Method method) {
if (!Strings.isNullOrEmpty(method.getJsDocDescription())) {
sourceBuilder.appendln("//" + method.getJsDocDescription());
}
String jsDoc = getJsDoc(method);
sourceBuilder.appendln(jsDoc.isEmpty() ? "" : "/**" + jsDoc + " */");
}
private String getJsDoc(Method method) {
MethodDescriptor methodDescriptor = method.getDescriptor();
StringBuilder jsDocBuilder = new StringBuilder();
if (methodDescriptor.getJsVisibility() != Visibility.PUBLIC) {
jsDocBuilder.append(" @" + methodDescriptor.getJsVisibility().jsText);
}
if (methodDescriptor.isAbstract()) {
jsDocBuilder.append(" @abstract");
}
if (method.isOverride() && !method.isConstructor()) {
jsDocBuilder.append(" @override");
}
if (!methodDescriptor.getTypeParameterTypeDescriptors().isEmpty()) {
String templateParamNames =
closureTypesGenerator.getCommaSeparatedClosureTypesString(
methodDescriptor.getTypeParameterTypeDescriptors());
jsDocBuilder.append(" @template " + templateParamNames);
}
if (type.getDeclaration().isJsFunctionImplementation()
&& methodDescriptor.isPolymorphic()
&& !method.getBody().getStatements().isEmpty()) {
// TODO(b/120800425): Solve the object<->function duality in JsFunction implementations in a
// more principled way.
if (methodDescriptor.getName().startsWith("$ctor")) {
// ctor treats the JsFunction implementation as a class to invoke java.lang.Object ctor
// method. Do not redefine @this, instead suppress invalid casts to allow casting this to
// a function if needed.
jsDocBuilder.append(" @suppress {invalidCasts}");
} else {
// Using @this redefines enclosing class of a method, hence any template variables defined
// in the class need to be declared in the method.
for (TypeVariable typeVariable : type.getDeclaration().getTypeParameterDescriptors()) {
jsDocBuilder.append(
" @template " + closureTypesGenerator.getClosureTypeString(typeVariable));
}
jsDocBuilder.append(
" @this {"
+ closureTypesGenerator.getClosureTypeString(type.getTypeDescriptor())
+ "}");
}
}
String returnTypeName =
closureTypesGenerator.getClosureTypeString(methodDescriptor.getReturnTypeDescriptor());
if (needsReturnJsDoc(methodDescriptor)) {
jsDocBuilder.append(" @return {" + returnTypeName + "}");
}
if (methodDescriptor.isDeprecated()) {
jsDocBuilder.append(" @deprecated");
}
return jsDocBuilder.toString();
}
private boolean needsReturnJsDoc(MethodDescriptor methodDescriptor) {
return !methodDescriptor.isConstructor()
&& !TypeDescriptors.isPrimitiveVoid(methodDescriptor.getReturnTypeDescriptor());
}
private void renderMarkImplementorMethod() {
if (!type.isInterface() || type.isOverlayImplementation()) {
return; // Only render markImplementor code for interfaces.
}
sourceBuilder.newLine();
sourceBuilder.appendln(
"static $markImplementor(/** "
+ TypeDescriptors.get().nativeFunction.getQualifiedJsName()
+ "*/ ctor)");
sourceBuilder.openBrace();
sourceBuilder.newLine();
for (DeclaredTypeDescriptor superInterface : type.getSuperInterfaceTypeDescriptors()) {
if (superInterface.isNative()) {
continue;
}
String superInterfaceName = environment.aliasForType(superInterface);
sourceBuilder.appendln(superInterfaceName + ".$markImplementor(ctor);");
}
sourceBuilder.appendLines(
"ctor.prototype.$implements__"
+ ManglingNameUtils.getMangledName(type.getDeclaration())
+ " = true;");
sourceBuilder.closeBrace();
sourceBuilder.newLine();
}
// TODO(b/34928687): Move this to the ast in a normalization pass.
private void renderIsInstanceMethod() {
TypeDeclaration underlyingType = type.getUnderlyingTypeDeclaration();
if (underlyingType.isJsFunctionInterface()) {
// JsFunction interfaces use the custom class JavaScriptFunction for casts, instanceof and
// class literal purposes. Hence no need to emit $isInstance in the overlay class.
return;
}
if (underlyingType.isNoopCast()) {
return;
}
if (type.containsMethod(MethodDescriptor.IS_INSTANCE_METHOD_NAME)) {
sourceBuilder.appendLines(
"/**", " * $isInstance() function implementation is provided separately.", " */");
sourceBuilder.newLine();
return;
}
sourceBuilder.appendLines("/** @return {boolean} */", "static $isInstance(/** ? */ instance) ");
sourceBuilder.openBrace();
sourceBuilder.newLine();
if (type.getDeclaration().isJsFunctionImplementation()) {
renderIsInstanceOfJsFunctionImplementationStatement(type.getDeclaration());
} else if (type.isOverlayImplementation()) {
TypeDeclaration overlaidTypeDeclaration = type.getOverlaidTypeDeclaration();
if (overlaidTypeDeclaration.isJsEnum()) {
renderIsInstanceOfJsEnumStatement(overlaidTypeDeclaration);
} else {
renderIsInstanceOfClassStatement(type.getOverlaidTypeDeclaration());
}
} else if (type.isInterface()) {
renderIsInstanceOfInterfaceStatement(type.getDeclaration());
} else {
renderIsInstanceOfClassStatement(type.getDeclaration());
}
sourceBuilder.closeBrace();
sourceBuilder.newLine();
}
private void renderIsInstanceOfJsEnumStatement(TypeDeclaration typeDeclaration) {
if (typeDeclaration.isJsEnum() && !typeDeclaration.isNative()) {
sourceBuilder.append(
"return "
+ environment.aliasForType(BootstrapType.ENUMS.getDeclaration())
+ ".isInstanceOf(instance, "
+ environment.aliasForType(typeDeclaration.getMetadataTypeDeclaration())
+ ");");
} else {
checkState(typeDeclaration.getJsEnumInfo().hasCustomValue());
DeclaredTypeDescriptor instanceOfValueType =
AstUtils.getJsEnumValueFieldInstanceCheckType(typeDeclaration);
sourceBuilder.append(
"return "
+ environment.aliasForType(instanceOfValueType.getTypeDeclaration())
+ ".$isInstance(instance);");
}
}
private void renderIsInstanceOfClassStatement(TypeDeclaration typeDescriptor) {
sourceBuilder.append(
"return instance instanceof " + environment.aliasForType(typeDescriptor) + ";");
}
private void renderIsInstanceOfInterfaceStatement(TypeDeclaration type) {
sourceBuilder.append(
"return instance != null && !!instance.$implements__"
+ ManglingNameUtils.getMangledName(type)
+ ";");
}
private void renderIsInstanceOfJsFunctionImplementationStatement(TypeDeclaration type) {
sourceBuilder.appendln(
"return instance != null && !!instance.$is__"
+ ManglingNameUtils.getMangledName(type)
+ ";");
}
// TODO(b/34928687): Move this to the ast in a normalization pass.
// TODO(b/80269359): may copy Objects methods (equals, hashCode, etc. ) as well.
private void renderCopyMethod() {
if (!type.getDeclaration().isJsFunctionImplementation()) {
return; // Only render the $copy method for jsfunctions
}
sourceBuilder.appendln(
"static $copy(/**"
+ environment.aliasForType(type.getDeclaration())
+ "*/ from, /** ? */ to) ");
sourceBuilder.openBrace();
for (Field field : type.getInstanceFields()) {
String fieldName = ManglingNameUtils.getMangledName(field.getDescriptor());
sourceBuilder.newLine();
sourceBuilder.append("to." + fieldName + " = from." + fieldName + ";");
}
sourceBuilder.newLine();
sourceBuilder.appendLines(
"// Marks the object is an instance of this class.",
"to.$is__" + ManglingNameUtils.getMangledName(type.getDeclaration()) + " = true;");
sourceBuilder.closeBrace();
sourceBuilder.newLine();
}
// TODO(b/67965153): Move this to the ast in a normalization pass.
private void renderClassMetadata() {
if (type.isOverlayImplementation()
&& (type.getOverlaidTypeDeclaration().isJsFunctionInterface()
|| type.getOverlaidTypeDeclaration().isInterface())) {
// JsFunction and Native interface overlays do not need class metadata.
sourceBuilder.newLine();
return;
}
String utilAlias = environment.aliasForType(BootstrapType.NATIVE_UTIL.getDescriptor());
TypeDeclaration targetTypeDescriptor = type.getUnderlyingTypeDeclaration();
String name =
targetTypeDescriptor.isNative()
// For native types the qualified JavaScript name is more useful to identify the
// type, in particular for debugging.
? targetTypeDescriptor.getQualifiedJsName()
: targetTypeDescriptor.getQualifiedBinaryName();
String obfuscatableName = "'" + name + "'";
String className = environment.aliasForType(type.getDeclaration());
if (targetTypeDescriptor.isInterface()) {
sourceBuilder.appendln(
utilAlias
+ ".$setClassMetadataForInterface("
+ className
+ ", "
+ obfuscatableName
+ ");");
} else if (targetTypeDescriptor.isEnum() && !targetTypeDescriptor.isJsEnum()) {
// TODO(b/117525773): targetTypeDescriptor.isEnum should already be false for JsEnums,
// making the second part of the condition unnecessary.
sourceBuilder.appendln(
utilAlias + ".$setClassMetadataForEnum(" + className + ", " + obfuscatableName + ");");
} else {
sourceBuilder.appendln(
utilAlias + ".$setClassMetadata(" + className + ", " + obfuscatableName + ");");
}
sourceBuilder.newLine();
}
private void renderLoadModules() {
MethodDescriptor methodDescriptor = AstUtils.getLoadModulesDescriptor(type.getTypeDescriptor());
sourceBuilder.newLine();
sourceBuilder.appendLines(
"static " + ManglingNameUtils.getMangledName(methodDescriptor) + "() ");
sourceBuilder.openBrace();
// goog.module.get(...) for lazy imports.
for (Import lazyImport : sortImports(importsByCategory.get(ImportCategory.RUNTIME))) {
String alias = lazyImport.getAlias();
String path = lazyImport.getImplModulePath();
sourceBuilder.newLine();
sourceBuilder.append(alias + " = goog.module.get('" + path + "');");
}
sourceBuilder.closeBrace();
sourceBuilder.newLine();
}
private void renderStaticFieldDeclarations() {
boolean hasFields = false;
for (Field staticField : type.getStaticFields()) {
sourceBuilder.emitWithMemberMapping(
staticField,
() -> {
statementTranspiler.renderStatement(
AstUtils.declarationStatement(staticField, type.getSourcePosition()));
sourceBuilder.newLine();
});
hasFields = true;
}
if (hasFields) {
sourceBuilder.newLine();
}
}
/**
* Here we call markImplementor on all interfaces such that the class can be queried at run time
* to determine if it implements an interface.
*/
private void renderMarkImplementorCalls() {
if (type.isOverlayImplementation()) {
return; // Do nothing
}
String className = environment.aliasForType(type.getDeclaration());
if (type.isInterface()) {
// TODO(b/20102666): remove cast after b/20102666 is handled in Closure.
sourceBuilder.appendln(
className
+ ".$markImplementor(/** @type {"
+ TypeDescriptors.get().nativeFunction.getQualifiedJsName()
+ "} */ ("
+ className
+ "));");
sourceBuilder.newLine();
} else { // Not an interface so it is a Class.
boolean marksImplementors = false;
for (TypeDescriptor interfaceTypeDescriptor : type.getSuperInterfaceTypeDescriptors()) {
if (interfaceTypeDescriptor.isNative()) {
continue;
}
JavaScriptConstructorReference markImplementorConstructor =
interfaceTypeDescriptor.getMetadataConstructorReference();
renderExpression(markImplementorConstructor);
sourceBuilder.appendln(".$markImplementor(" + className + ");");
marksImplementors = true;
}
if (marksImplementors) {
sourceBuilder.newLine();
}
}
}
private void renderNativeSource() {
if (nativeSource == null) {
return;
}
String className = environment.aliasForType(type.getDeclaration());
sourceBuilder.appendln("/* NATIVE.JS EPILOG */");
sourceBuilder.newLine();
// A predictable unique alias to current type so native.js could reference it safely.
String longAliasName =
type.getDeclaration().getQualifiedSourceName().replace("_", "__").replace('.', '_');
if (!className.equals(longAliasName)) {
sourceBuilder.appendln("const " + longAliasName + " = " + className + ";");
sourceBuilder.newLine();
}
int nativeSourceLine = 0;
int currentByteOffset = 0;
String content = nativeSource.getContent();
for (String line : Splitter.on('\n').split(content)) {
String trimmedLine = CharMatcher.whitespace().trimTrailingFrom(line);
if (!trimmedLine.isEmpty()) {
int firstNonWhitespaceColumn = CharMatcher.whitespace().negate().indexIn(trimmedLine);
sourceBuilder.append(Strings.repeat(" ", firstNonWhitespaceColumn));
// Only map the trimmed section of the line.
sourceBuilder.emitWithMapping(
SourcePosition.newBuilder()
.setStartFilePosition(
FilePosition.newBuilder()
.setLine(nativeSourceLine)
.setColumn(firstNonWhitespaceColumn)
.setByteOffset(currentByteOffset + firstNonWhitespaceColumn)
.build())
.setEndFilePosition(
FilePosition.newBuilder()
.setLine(nativeSourceLine)
.setColumn(trimmedLine.length())
.setByteOffset(currentByteOffset + trimmedLine.length())
.build())
.setFilePath(nativeSource.getRelativeFilePath())
.setName(type.getDeclaration().getQualifiedBinaryName() + ".<native>")
.build(),
() -> sourceBuilder.append(trimmedLine.substring(firstNonWhitespaceColumn)));
}
sourceBuilder.newLine();
nativeSourceLine++;
currentByteOffset += line.length() + 1;
}
sourceBuilder.newLine();
}
private void renderExports() {
sourceBuilder.appendLines("exports = " + environment.aliasForType(type.getDeclaration()) + ";");
// TODO(b/77961191): add a new line once the bug is resolved.
}
private void renderExpression(Expression expression) {
ExpressionTranspiler.render(expression, environment, sourceBuilder);
}
}