Skip to content

Commit

Permalink
Correct logic for NodeUtil.isEs6Constructor()
Browse files Browse the repository at this point in the history
It is possible for a class to have a static
member named "constructor".

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=231829535
  • Loading branch information
brad4d authored and blickly committed Feb 1, 2019
1 parent 1836f5b commit bb170cd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/com/google/javascript/jscomp/NodeUtil.java
Expand Up @@ -5697,10 +5697,21 @@ static boolean isConstructor(Node fnNode) {
}

private static boolean isEs6Constructor(Node fnNode) {
return fnNode.isFunction()
&& fnNode.getGrandparent() != null
&& fnNode.getGrandparent().isClassMembers()
&& fnNode.getParent().matchesQualifiedName("constructor");
if (!fnNode.isFunction()) {
return false;
}
Node memberFunctionDef = fnNode.getParent();
if (memberFunctionDef == null || !memberFunctionDef.isMemberFunctionDef()) {
return false; // not a member function
}
if (memberFunctionDef.isStaticMember()) {
return false; // it is possible to have a static method named "constructor"
}
Node classMembers = memberFunctionDef.getParent();
if (classMembers == null || !classMembers.isClassMembers()) {
return false; // method definition in an object literal
}
return memberFunctionDef.matchesQualifiedName("constructor");
}

static boolean isGetterOrSetter(Node propNode) {
Expand Down
5 changes: 5 additions & 0 deletions test/com/google/javascript/jscomp/NodeUtilTest.java
Expand Up @@ -3582,6 +3582,11 @@ public void testIsConstructor() {
getFunctionNode("var x = {}; /** @constructor */ x.Foo = function() {}")))
.isTrue();
assertThat(NodeUtil.isConstructor(getFunctionNode("class Foo { constructor() {} }"))).isTrue();
assertThat(NodeUtil.isConstructor(getFunctionNode("class Foo { static constructor() {} }")))
.isFalse();
assertThat(NodeUtil.isConstructor(getFunctionNode("class Foo { get constructor() {} }")))
.isFalse();
assertThat(NodeUtil.isConstructor(getFunctionNode("let Foo = { constructor() {} }"))).isFalse();

assertThat(NodeUtil.isConstructor(getFunctionNode("function Foo() {}"))).isFalse();
assertThat(NodeUtil.isConstructor(getFunctionNode("var Foo = function() {}"))).isFalse();
Expand Down

0 comments on commit bb170cd

Please sign in to comment.