Skip to content

Commit

Permalink
Add pass to extract ES6 class definitions out of non-simple contexts.
Browse files Browse the repository at this point in the history
Currently, JSCompiler only transpiles ES6 classes that appear as declarations or simple assignments in the original source code. Classes in other contexts are rejected as compilation errors.

There's no deep reason for this restriction. JSCompiler should accept ES6 classes anywhere they can appear according to the grammar of the language.

This CL adds a pass that runs before the main Es6ToEs3Converter pass. It replaces class definitions in complex contexts:

```
f(class{ /* ... */});
```

with an immediately preceding alias:
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=124866181
  • Loading branch information
brndn authored and blickly committed Jun 15, 2016
1 parent 604ceaa commit 0a77698
Show file tree
Hide file tree
Showing 6 changed files with 294 additions and 24 deletions.
27 changes: 17 additions & 10 deletions src/com/google/javascript/jscomp/ES6ModuleLoader.java
Expand Up @@ -188,21 +188,28 @@ static boolean isAbsoluteIdentifier(String name) {
return name.startsWith(MODULE_SLASH);
}

/**
* Turns a filename into a JS identifier that can be used in rewritten code.
* Removes leading ./, replaces / with $, removes trailing .js
* and replaces - with _.
*/
public static String toJSIdentifier(URI filename) {
return stripJsExtension(filename.toString())
.replaceAll("^\\." + Pattern.quote(MODULE_SLASH), "")
.replace(MODULE_SLASH, "$")
.replace('\\', '$')
.replace('-', '_')
.replace(':', '_')
.replace('.', '_')
.replace("%20", "_");
}

/**
* Turns a filename into a JS identifier that is used for moduleNames in
* rewritten code. Removes leading ./, replaces / with $, removes trailing .js
* and replaces - with _. All moduleNames get a "module$" prefix.
*/
public static String toModuleName(URI filename) {
String moduleName =
stripJsExtension(filename.toString())
.replaceAll("^\\." + Pattern.quote(MODULE_SLASH), "")
.replace(MODULE_SLASH, "$")
.replace('\\', '$')
.replace('-', '_')
.replace(':', '_')
.replace('.', '_')
.replace("%20", "_");
return "module$" + moduleName;
return "module$" + toJSIdentifier(filename);
}
}
104 changes: 104 additions & 0 deletions src/com/google/javascript/jscomp/Es6ExtractClasses.java
@@ -0,0 +1,104 @@
/*
* 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;

import com.google.javascript.jscomp.ExpressionDecomposer.DecompositionType;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

import java.util.HashSet;
import java.util.Set;

/**
* Extracts ES6 classes defined in function calls to local constants.
* <p>
* Example:
* Before: <code>foo(class { constructor() {} });</code>
* After:
* <code>
* const $jscomp$classdecl$var0 = class { constructor() {} };
* foo($jscomp$classdecl$var0);
* </code>
* <p>
* This must be done before {@link Es6ToEs3Converter}, because that pass only handles classes
* that are declarations or simple assignments.
* @see Es6ToEs3Converter#visitClass(Node, Node)
*/
public final class Es6ExtractClasses
extends NodeTraversal.AbstractPostOrderCallback implements HotSwapCompilerPass {

private static final String CLASS_DECL_VAR = "$classdecl$var";

private final AbstractCompiler compiler;
private final ExpressionDecomposer expressionDecomposer;
private int classDeclVarCounter = 0;

Es6ExtractClasses(AbstractCompiler compiler) {
this.compiler = compiler;
Set<String> consts = new HashSet<>();
this.expressionDecomposer = new ExpressionDecomposer(
compiler,
compiler.getUniqueNameIdSupplier(),
consts,
Scope.createGlobalScope(new Node(Token.SCRIPT)));
}

@Override
public void process(Node externs, Node root) {
NodeTraversal.traverseRootsEs6(compiler, this, externs, root);
}

@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
NodeTraversal.traverseEs6(compiler, scriptRoot, this);
}

@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isClass() && shouldExtractClass(n, parent)) {
extractClass(n, parent);
}
}

private boolean shouldExtractClass(Node classNode, Node parent) {
if (NodeUtil.isClassDeclaration(classNode)
|| parent.isName()
|| (parent.isAssign() && parent.getParent().isExprResult())) {
// No need to extract. Handled directly by Es6ToEs3Converter.ClassDeclarationMetadata#create.
return false;
}
// Don't extract the class if it's not safe to do so. For example,
// var c = maybeTrue() && class extends someSideEffect() {};
// TODO(brndn): it is possible to be less conservative. If the classNode is DECOMPOSABLE,
// we could use the expression decomposer to move it out of the way.
return expressionDecomposer.canExposeExpression(classNode) == DecompositionType.MOVABLE;
}

private void extractClass(Node classNode, Node parent) {
String name = ES6ModuleLoader.toJSIdentifier(
ES6ModuleLoader.createUri(classNode.getStaticSourceFile().getName()))
+ CLASS_DECL_VAR
+ (classDeclVarCounter++);
Node statement = NodeUtil.getEnclosingStatement(parent);
parent.replaceChild(classNode, IR.name(name));
Node classDeclaration = IR.constNode(IR.name(name), classNode)
.useSourceInfoIfMissingFromForTree(classNode);
statement.getParent().addChildBefore(classDeclaration, statement);
compiler.reportCodeChange();
}
}
2 changes: 2 additions & 0 deletions src/com/google/javascript/jscomp/ExpressionDecomposer.java
Expand Up @@ -672,6 +672,8 @@ static Node findExpressionRoot(Node subExpression) {
case RETURN:
case THROW:
case VAR:
case CONST:
case LET:
Preconditions.checkState(child == parent.getFirstChild());
return parent;
// Any of these indicate an unsupported expression:
Expand Down
10 changes: 10 additions & 0 deletions src/com/google/javascript/jscomp/TranspilationPasses.java
Expand Up @@ -50,12 +50,22 @@ public static void addEs6EarlyPasses(List<PassFactory> passes) {
*/
public static void addEs6LatePasses(List<PassFactory> passes) {
passes.add(es6ConvertSuper);
passes.add(es6ExtractClasses);
passes.add(convertEs6ToEs3);
passes.add(rewriteBlockScopedDeclaration);
passes.add(rewriteGenerators);
passes.add(rewritePolyfills);
}


static final HotSwapPassFactory es6ExtractClasses =
new HotSwapPassFactory("Es6ExtractClasses", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new Es6ExtractClasses(compiler);
}
};

static final HotSwapPassFactory es6RewriteDestructuring =
new HotSwapPassFactory("Es6RewriteDestructuring", true) {
@Override
Expand Down
89 changes: 89 additions & 0 deletions test/com/google/javascript/jscomp/Es6ExtractClassesTest.java
@@ -0,0 +1,89 @@
/*
* 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;

import com.google.javascript.jscomp.CompilerOptions.LanguageMode;

public final class Es6ExtractClassesTest extends CompilerTestCase {

@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new Es6ExtractClasses(compiler);
}

@Override
protected void setUp() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT6);
disableTypeCheck();
runTypeCheckAfterProcessing = true;
}

public void testExtractionFromCall() {
test(
"f(class{});",
LINE_JOINER.join(
"const testcode$classdecl$var0 = class {};", "f(testcode$classdecl$var0);"));
}

public void testConstAssignment() {
test(
"var foo = bar(class {});",
LINE_JOINER.join(
"const testcode$classdecl$var0 = class {};",
"var foo = bar(testcode$classdecl$var0);"));
}

public void testLetAssignment() {
test(
"let foo = bar(class {});",
LINE_JOINER.join(
"const testcode$classdecl$var0 = class {};",
"let foo = bar(testcode$classdecl$var0);"));
}

public void testVarAssignment() {
test(
"var foo = bar(class {});",
LINE_JOINER.join(
"const testcode$classdecl$var0 = class {};",
"var foo = bar(testcode$classdecl$var0);"));
}

public void testConditionalBlocksExtractionFromCall() {
testSame("maybeTrue() && f(class{});");
}

public void testExtractionFromArrayLiteral() {
test(
"var c = [class C {}];",
LINE_JOINER.join(
"const testcode$classdecl$var0 = class C {};", "var c = [testcode$classdecl$var0];"));
}

public void testConditionalBlocksExtractionFromArrayLiteral() {
testSame("var c = maybeTrue() && [class {}]");
}

public void testTernaryOperatorBlocksExtraction() {
testSame("var c = maybeTrue() ? class A {} : class B {}");
}

public void testClassesHandledByEs6ToEs3Converter() {
testSame("class C{}");
testSame("var c = class {};");
}
}

0 comments on commit 0a77698

Please sign in to comment.