-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Es6ConvertSuper.java
279 lines (252 loc) · 10.6 KB
/
Es6ConvertSuper.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
/*
* Copyright 2014 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;
import static com.google.javascript.jscomp.Es6ToEs3Converter.CANNOT_CONVERT_YET;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
/**
* Converts {@code super.method()} calls and adds constructors to any classes that lack them.
*
* <p>This has to run before the main {@link Es6ToEs3Converter} pass. The super() constructor calls
* are not converted here, but rather in {@link Es6ConvertSuperConstructorCalls}, which runs later.
*/
public final class Es6ConvertSuper extends NodeTraversal.AbstractPostOrderCallback
implements HotSwapCompilerPass {
static final DiagnosticType INVALID_SUPER_CALL =
DiagnosticType.error(
"JSC_INVALID_SUPER_CALL", "Calls to super cannot be used outside of a constructor.");
private final AbstractCompiler compiler;
public Es6ConvertSuper(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isClass()) {
boolean hasConstructor = false;
for (Node member = n.getLastChild().getFirstChild();
member != null;
member = member.getNext()) {
if (member.isMemberFunctionDef() && member.getString().equals("constructor")) {
hasConstructor = true;
break;
}
}
if (!hasConstructor) {
addSyntheticConstructor(n);
}
} else if (n.isSuper()) {
visitSuper(n, parent);
}
}
private void addSyntheticConstructor(Node classNode) {
Node superClass = classNode.getSecondChild();
Node classMembers = classNode.getLastChild();
Node memberDef;
if (superClass.isEmpty()) {
Node function = IR.function(IR.name(""), IR.paramList(), IR.block());
compiler.reportChangeToChangeScope(function);
memberDef = IR.memberFunctionDef("constructor", function);
} else {
if (!superClass.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
Node body = IR.block();
// If a class is defined in an externs file or as an interface, it's only a stub, not an
// implementation that should be instantiated.
// A call to super() shouldn't actually exist for these cases and is problematic to
// transpile, so don't generate it.
if (!classNode.isFromExterns() && !isInterface(classNode)) {
Node exprResult = IR.exprResult(IR.call(
IR.getprop(IR.superNode(), IR.string("apply")),
IR.thisNode(),
IR.name("arguments")));
body.addChildToFront(exprResult);
}
Node constructor = IR.function(
IR.name(""),
IR.paramList(IR.name("var_args")),
body);
compiler.reportChangeToChangeScope(constructor);
memberDef = IR.memberFunctionDef("constructor", constructor);
JSDocInfoBuilder info = new JSDocInfoBuilder(false);
info.recordParameter(
"var_args",
new JSTypeExpression(
new Node(Token.ELLIPSIS, new Node(Token.QMARK)), "<Es6ConvertSuper>"));
memberDef.setJSDocInfo(info.build());
}
memberDef.useSourceInfoIfMissingFromForTree(classNode);
classMembers.addChildToFront(memberDef);
compiler.reportChangeToEnclosingScope(memberDef);
}
private boolean isInterface(Node classNode) {
JSDocInfo classJsDocInfo = NodeUtil.getBestJSDocInfo(classNode);
return classJsDocInfo != null && classJsDocInfo.isInterface();
}
private void visitSuper(Node node, Node parent) {
Preconditions.checkState(node.isSuper());
Node exprRoot = node;
if (exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp()) {
exprRoot = exprRoot.getParent();
}
Node enclosingMemberDef =
NodeUtil.getEnclosingNode(
exprRoot,
new Predicate<Node>() {
@Override
public boolean apply(Node n) {
switch (n.getToken()) {
case MEMBER_FUNCTION_DEF:
case GETTER_DEF:
case SETTER_DEF:
case COMPUTED_PROP:
return true;
default:
return false;
}
}
});
if (parent.isCall()) {
// super(...)
visitSuperCall(node, parent, enclosingMemberDef);
} else if (parent.isGetProp() || parent.isGetElem()) {
if (parent.getFirstChild() == node) {
if (parent.getParent().isCall() && NodeUtil.isCallOrNewTarget(parent)) {
// super.something(...) or super['something'](..)
visitSuperPropertyCall(node, parent, enclosingMemberDef);
} else {
// super.something or super['something']
visitSuperPropertyAccess(node, parent, enclosingMemberDef);
}
} else {
// super.something used in some other way
compiler.report(JSError.make(node, CANNOT_CONVERT_YET,
"Only calls to super or to a method of super are supported."));
}
} else if (parent.isNew()) {
// new super(...)
compiler.report(JSError.make(node, INVALID_SUPER_CALL));
} else {
// some other use of super we don't support yet
compiler.report(JSError.make(node, CANNOT_CONVERT_YET,
"Only calls to super or to a method of super are supported."));
}
}
private void visitSuperCall(Node node, Node parent, Node enclosingMemberDef) {
Preconditions.checkState(parent.isCall(), parent);
Preconditions.checkState(node.isSuper(), node);
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
if (enclosingMemberDef.isMemberFunctionDef()
&& enclosingMemberDef.getString().equals("constructor")) {
// Calls to super() constructors will be transpiled by Es6ConvertSuperConstructorCalls later.
if (node.isFromExterns() || isInterface(clazz)) {
// If a class is defined in an externs file or as an interface, it's only a stub, not an
// implementation that should be instantiated.
// A call to super() shouldn't actually exist for these cases and is problematic to
// transpile, so just drop it.
Node enclosingStatement = NodeUtil.getEnclosingStatement(node);
Node enclosingStatementParent = enclosingStatement.getParent();
enclosingStatement.detach();
compiler.reportChangeToEnclosingScope(enclosingStatementParent);
}
// Calls to super() constructors will be transpiled by Es6ConvertSuperConstructorCalls
// later.
return;
} else {
// super can only be directly called in a constructor
compiler.report(JSError.make(node, INVALID_SUPER_CALL));
return;
}
}
private void visitSuperPropertyCall(Node node, Node parent, Node enclosingMemberDef) {
Preconditions.checkState(parent.isGetProp() || parent.isGetElem(), parent);
Preconditions.checkState(node.isSuper(), node);
Node grandparent = parent.getParent();
Preconditions.checkState(grandparent.isCall());
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
Node callTarget = parent;
if (enclosingMemberDef.isStaticMember()) {
callTarget.replaceChild(node, superName.cloneTree());
callTarget = IR.getprop(callTarget.detach(), IR.string("call"));
grandparent.addChildToFront(callTarget);
grandparent.addChildAfter(IR.thisNode(), callTarget);
grandparent.useSourceInfoIfMissingFromForTree(parent);
} else {
String newPropName = Joiner.on('.').join(superName.getQualifiedName(), "prototype");
Node newProp = NodeUtil.newQName(compiler, newPropName);
node.replaceWith(newProp);
callTarget = IR.getprop(callTarget.detach(), IR.string("call"));
grandparent.addChildToFront(callTarget);
grandparent.addChildAfter(IR.thisNode(), callTarget);
grandparent.putBooleanProp(Node.FREE_CALL, false);
grandparent.useSourceInfoIfMissingFromForTree(parent);
}
compiler.reportChangeToEnclosingScope(grandparent);
}
private void visitSuperPropertyAccess(Node node, Node parent, Node enclosingMemberDef) {
Preconditions.checkState(parent.isGetProp() || parent.isGetElem(), parent);
Preconditions.checkState(node.isSuper(), node);
Node grandparent = parent.getParent();
if (NodeUtil.isLValue(parent)) {
// We don't support assigning to a super property
compiler.report(
JSError.make(parent, CANNOT_CONVERT_YET, "assigning to a super property"));
return;
}
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
if (enclosingMemberDef.isStaticMember()) {
node.replaceWith(superName.cloneTree());
} else {
String newPropName = Joiner.on('.').join(superName.getQualifiedName(), "prototype");
Node newprop = NodeUtil.newQName(compiler, newPropName, node, "super");
node.replaceWith(newprop);
}
compiler.reportChangeToEnclosingScope(grandparent);
}
@Override
public void process(Node externs, Node root) {
// Might need to synthesize constructors for ambient classes in .d.ts externs
TranspilationPasses.processTranspile(compiler, externs, this);
TranspilationPasses.processTranspile(compiler, root, this);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, this);
}
}