-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Decompose class extends calls #2997
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
ChadKillingsworth
wants to merge
4
commits into
google:master
from
ChadKillingsworth:class-extends-decompose
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
dbc04f3
When the extends clause of a class is not a qualified name, alias the…
ChadKillingsworth 9570642
Correct featureSet for the new pass factory.
brad4d 6fd2815
Break up and comment some test cases.
brad4d 3e9796d
Use NodeUtil.mayHaveSideEffects() and some readability clean up.
brad4d File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
173 changes: 173 additions & 0 deletions
173
src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
/* | ||
* Copyright 2018 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.common.base.Preconditions.checkArgument; | ||
import static com.google.common.base.Preconditions.checkNotNull; | ||
|
||
import com.google.javascript.jscomp.deps.ModuleNames; | ||
import com.google.javascript.jscomp.parsing.parser.FeatureSet; | ||
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature; | ||
import com.google.javascript.rhino.IR; | ||
import com.google.javascript.rhino.Node; | ||
|
||
/** | ||
* Extracts ES6 class extends expressions and creates an alias. | ||
* | ||
* <p>Example: Before: | ||
* | ||
* <p><code>class Foo extends Bar() {}</code> | ||
* | ||
* <p>After: | ||
* | ||
* <p><code> | ||
* const $jscomp$classextends$var0 = Bar(); | ||
* class Foo extends $jscomp$classextends$var0 {} | ||
* </code> | ||
* | ||
* <p>This must be done before {@link Es6ConvertSuper}, because that pass only handles extends | ||
* clauses which are simple NAME or GETPROP nodes. | ||
*/ | ||
public final class Es6RewriteClassExtendsExpressions extends NodeTraversal.AbstractPostOrderCallback | ||
implements HotSwapCompilerPass { | ||
|
||
static final String CLASS_EXTENDS_VAR = "$classextends$var"; | ||
|
||
private final AbstractCompiler compiler; | ||
private int classExtendsVarCounter = 0; | ||
private static final FeatureSet features = FeatureSet.BARE_MINIMUM.with(Feature.CLASSES); | ||
|
||
Es6RewriteClassExtendsExpressions(AbstractCompiler compiler) { | ||
this.compiler = compiler; | ||
} | ||
|
||
@Override | ||
public void process(Node externs, Node root) { | ||
// TODO(bradfordcsmith): Do we really need to run this on externs? | ||
TranspilationPasses.processTranspile(compiler, externs, features, this); | ||
TranspilationPasses.processTranspile(compiler, root, features, this); | ||
} | ||
|
||
@Override | ||
public void hotSwapScript(Node scriptRoot, Node originalRoot) { | ||
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, features, this); | ||
} | ||
|
||
@Override | ||
public void visit(NodeTraversal t, Node n, Node parent) { | ||
if (n.isClass() && needsExtendsDecomposing(n)) { | ||
if (canDecomposeSimply(n)) { | ||
extractExtends(t, n); | ||
} else { | ||
decomposeInIIFE(t, n); | ||
} | ||
} | ||
} | ||
|
||
private boolean needsExtendsDecomposing(Node classNode) { | ||
checkArgument(classNode.isClass()); | ||
if (classNode.getSecondChild().isEmpty() || classNode.getSecondChild().isQualifiedName()) { | ||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
|
||
/** | ||
* Find common cases where we can safely decompose class extends expressions which are not | ||
* qualified names. Enables transpilation of complex extends expressions. | ||
* | ||
* <p>We can only decompose the expression in a limited set of cases to avoid changing evaluation | ||
* order of side-effect causing statements. | ||
*/ | ||
private boolean canDecomposeSimply(Node classNode) { | ||
Node enclosingStatement = checkNotNull(NodeUtil.getEnclosingStatement(classNode), classNode); | ||
if (enclosingStatement == classNode) { | ||
// `class Foo extends some_expression {}` | ||
// can always be converted to | ||
// ``` | ||
// const tmpvar = some_expression; | ||
// class Foo extends tmpvar {} | ||
// ``` | ||
return true; | ||
} else { | ||
Node classNodeParent = classNode.getParent(); | ||
if (NodeUtil.isNameDeclaration(enclosingStatement) | ||
&& classNodeParent.isName() | ||
&& classNodeParent.isFirstChildOf(enclosingStatement)) { | ||
// `const Foo = class extends some_expression {}, maybe_other_var;` | ||
// can always be converted to | ||
// ``` | ||
// const tmpvar = some_expression; | ||
// const Foo = class extends tmpvar {}, maybe_other_var; | ||
// ``` | ||
return true; | ||
} else if (enclosingStatement.isExprResult() | ||
&& classNodeParent.isOnlyChildOf(enclosingStatement) | ||
&& classNodeParent.isAssign() | ||
&& classNode.isSecondChildOf(classNodeParent)) { | ||
// `lhs = class extends some_expression {};` | ||
Node lhsNode = classNodeParent.getFirstChild(); | ||
// We can extract a temporary variable for some_expression as long as lhs expression | ||
// has no side effects. | ||
return !NodeUtil.mayHaveSideEffects(lhsNode); | ||
} else { | ||
return false; | ||
} | ||
} | ||
} | ||
|
||
private void extractExtends(NodeTraversal t, Node classNode) { | ||
String name = | ||
ModuleNames.fileToJsIdentifier(classNode.getStaticSourceFile().getName()) | ||
+ CLASS_EXTENDS_VAR | ||
+ (classExtendsVarCounter++); | ||
|
||
Node statement = NodeUtil.getEnclosingStatement(classNode); | ||
Node originalExtends = classNode.getSecondChild(); | ||
originalExtends.replaceWith(IR.name(name).useSourceInfoFrom(originalExtends)); | ||
Node extendsAlias = | ||
IR.constNode(IR.name(name), originalExtends) | ||
.useSourceInfoIfMissingFromForTree(originalExtends); | ||
statement.getParent().addChildBefore(extendsAlias, statement); | ||
NodeUtil.addFeatureToScript(NodeUtil.getEnclosingScript(classNode), Feature.CONST_DECLARATIONS); | ||
t.reportCodeChange(classNode); | ||
} | ||
|
||
/** | ||
* When a class is used in an expressions where adding an alias as the previous statement might | ||
* change execution order of a side-effect causing statement, wrap the class in an IIFE so that | ||
* decomposition can happen safely. | ||
*/ | ||
private void decomposeInIIFE(NodeTraversal t, Node classNode) { | ||
// converts | ||
// `class X extends something {}` | ||
// to | ||
// `(function() { return class X extends something {}; })()` | ||
Node functionBody = IR.block(); | ||
Node function = IR.function(IR.name(""), IR.paramList(), functionBody); | ||
Node call = NodeUtil.newCallNode(function); | ||
classNode.replaceWith(call); | ||
functionBody.addChildToBack(IR.returnNode(classNode)); | ||
call.useSourceInfoIfMissingFromForTree(classNode); | ||
// NOTE: extractExtends() will end up reporting the change for the new function, so we only | ||
// need to report the change to the enclosing scope | ||
t.reportCodeChange(call); | ||
// Now do the extends expression extraction within the IIFE | ||
extractExtends(t, classNode); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why here instead of immediate before class rewriting? Alternately, why isn't it part of class rewriting?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
See the comment at https://github.com/google/closure-compiler/pull/2997/files#diff-fa51555d8bc30554f2cbba232a8033bdR41
This must be performed before transpilation of
super
calls. So much of class rewriting depends on the extends clause being a qualified name.