Skip to content

WIP: support for class fields #169

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
},
"dependencies": {
"acorn": "^6.4.1",
"acorn-class-fields": "^0.3.4",
"acorn-dynamic-import": "^4.0.0",
"acorn-jsx": "^5.2.0",
"chalk": "^2.4.2",
Expand Down
22 changes: 18 additions & 4 deletions scripts/test262-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ exports.features_list = {
//generators: [4, "generators"],

// test262 features acorn doesn't parse and thus are S3
"class-fields-private": [3, "unsupportedFeatures"],
"class-fields-public": [3, "unsupportedFeatures"],
"class-methods-private": [3, "unsupportedFeatures"],
"class-methods-private": [3, "privateMethods"],
"class-static-fields-private": [3, "unsupportedFeatures"],
"class-static-fields-public": [3, "unsupportedFeatures"],
"class-static-methods-private": [3, "unsupportedFeatures"],
Expand All @@ -20,6 +18,7 @@ exports.features_list = {
// buble bug: Does not transpile new.target
"new.target": [2, "newTarget"],
"regexp-lookbehind": [2, "notTranspiledFeatures"],
"class-fields-private": [2, "privateFields"],
};

const mapFilePatterns = files => {
Expand Down Expand Up @@ -202,10 +201,11 @@ exports.file_list = [
"built-ins/Function/prototype/toString/method-*",
]},

// buble bug: class methods should not be enumerable on the prototype
// buble bug: class methods and fields should not be enumerable on the prototype
{ level: 1, desc: "nonEnumerablePrototypeProperties", files: [
"language/computed-property-names/to-name-side-effects/class.js",
"language/computed-property-names/to-name-side-effects/numbers-class.js"
"*/class/elements/*(computed-names|computed-symbol-names).js",
]},

// buble bug: destructuring null or undefined should fail
Expand Down Expand Up @@ -437,6 +437,7 @@ exports.file_list = [
"built-ins/RegExp/dotall/without-dotall.js",
"built-ins/Function/prototype/toString/unicode.js",
"built-ins/RegExp/property-escapes/character-class.js",
"language/*/class/elements/*(grammar-privatename-identifier-semantics-stringvalue|grammar-field-identifier-alt|grammar-field-identifier|rs-static-privatename-identifier-alt|rs-static-async-method-privatename-identifier|rs-privatename-identifier-initializer-alt|rs-private-getter-alt|rs-private-setter|grammar-privatename-identifier|rs-static-privatename-identifier-by-classname|rs-static-privatename-identifier-alt-by-classname|rs-static-privatename-identifier-initializer|rs-private-getter|rs-private-method|rs-privatename-identifier|rs-static-privatename-identifier-initializer-alt|rs-private-method-alt|rs-static-generator-method-privatename-identifier|grammar-field-classelementname-initializer-alt|rs-static-async-generator-method-privatename-identifier|grammar-privatename-classelementname-initializer|rs-static-method-privatename-identifier|grammar-field-classelementname-initializer|rs-field-identifier|rs-field-identifier-initializer|rs-privatename-identifier-alt|rs-privatename-identifier-initializer|rs-static-privatename-identifier-initializer-alt-by-classname|rs-static-privatename-identifier|rs-private-setter-alt|grammar-privatename-classelementname-initializer-alt).js"
]},

{ level: 1, desc: "taggedTemplateOperatorPrecedence", files: [
Expand Down Expand Up @@ -606,6 +607,7 @@ exports.file_list = [
]},

{ level: 4, desc: "generators", files: [
"*/class/elements/*-gen-*",
"*Generator*", "*generator*", "*gen-meth-*", "*gen-func-*",
"*gen-named-func-expr-*", "*gen-method*", "*async-gen-*",
"*fn-name-gen.js",
Expand Down Expand Up @@ -920,6 +922,18 @@ exports.file_list = [
"language/expressions/tagged-template/cache-(differing-expressions|identical-source).js",
"language/expressions/tagged-template/template-object-template-map.js",
]},

// Field names should be converted to strings on class declaration
// Transpiled code does not convert them until instantiation
{ level: 1, desc: "fieldNameToStringOnClassDeclaration", files: [
"*evaluation-error/computed-name*",
]},

// Class fields without initializer should be defined but have value undefined
// Transpiled code does not define them
{ level: 1, desc: "uninitializedClassFields", files: [
"*/class/elements/*-(literal-names|string-literal-names|literal-names-asi).js",
]},
].map(i => ({ config: i.config, desc: i.desc, level: i.level, pattern: mapFilePatterns(i.files) }));

exports.skip_list = [
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Parser } from 'acorn';
import acornJsx from 'acorn-jsx';
import acornDynamicImport from 'acorn-dynamic-import';
import classFields from 'acorn-class-fields';
import Program from './program/Program.js';
import { features, matrix } from './support.js';
import getSnippet from './utils/getSnippet.js';

const parser = Parser.extend(acornDynamicImport, acornJsx());
const parser = Parser.extend(acornDynamicImport, acornJsx(), classFields);

const dangerousTransforms = ['dangerousTaggedTemplateString', 'dangerousForOf'];

Expand Down
46 changes: 45 additions & 1 deletion src/program/types/ClassBody.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,34 @@ export default class ClassBody extends Node {
if (!inFunctionExpression) code.appendLeft(constructor.end, ';');
}

const classFields = [];
this.body.forEach(element => {
if (element.type === 'FieldDefinition') {
if (element.computed) {
classFields.push(`this${code.slice(element.start, element.end)};`);
} else {
classFields.push(`this.${code.slice(element.start, element.end)};`);
}

code.remove(element.start, element.end);

if (code.byStart[element.end].content !== '') {
let toEnd = 0;
for (; toEnd < code.byStart[element.end].content.length; toEnd++) {
const chars = code.byStart[element.end].content.slice(0, toEnd);

if (chars.indexOf(';') !== -1) {
break;
}
}

if (toEnd > 0) {
code.remove(element.end, element.end + toEnd);
}
}
}
});

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's possible to use move here instead of removing the text and inserting it somewhere else?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it's possible to do this, since we're creating the constructor as a string, not a magic string. Right now the logic is collect fields => join fields with newlines => insert into top of constructor. To do this with move (besides converting constructor to magic string), we'd have to loop backwards (so we can always append to the front) or track the end position of the last inserted field.

Copy link
Member

@adrianheine adrianheine Nov 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's probably complicated if possible at all. Let's leave it as it currently is and deal with issues once they arise. Maybe it will be possible to move the super call to the front, that should fix a lot of issues.

const namedFunctions =
this.program.options.namedFunctionExpressions !== false;
const namedConstructor =
Expand All @@ -67,6 +95,7 @@ export default class ClassBody extends Node {
} else {
const fn =
`function ${name} () {` +
(classFields.length ? `\n${i1}` + classFields.join(`\n${i1}`) + `\n${i1}` : '') +
(superName
? `\n${i1}${superName}.apply(this, arguments);\n${i0}}`
: `}`) +
Expand All @@ -77,13 +106,24 @@ export default class ClassBody extends Node {
introBlock += inheritanceBlock + `\n\n${i0}`;
}
} else if (!constructor) {
let fn = 'function ' + (namedConstructor ? name + ' ' : '') + '() {}';
let fn =
'function ' +
(namedConstructor ? name + ' ' : '') +
'() {' +
(classFields.length ? `\n${i1}` + classFields.join(`\n${i1}`) + `\n${i0}` : '') +
'}';
if (this.parent.type === 'ClassDeclaration') fn += ';';
if (this.body.length) fn += `\n\n${i0}`;

introBlock += fn;
}

if (constructor) {
if (classFields.length) {
code.appendLeft(constructor.value.body.start + 1, `\n${i1}` + classFields.join(`\n${i1}`));
}
}

const scope = this.findScope(false);

const prototypeGettersAndSetters = [];
Expand All @@ -96,6 +136,10 @@ export default class ClassBody extends Node {
CompileError.missingTransform("getters and setters", "getterSetter", method);
}

if (method.type === 'FieldDefinition') {
return;
}

if (method.kind === 'constructor') {
const constructorName = namedConstructor ? ' ' + name : '';
code.overwrite(
Expand Down
164 changes: 164 additions & 0 deletions test/samples/classes.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,170 @@ module.exports = [
};`
},

{
description: 'transpiles a class declaration with class fields and constructor',

input: `
class Foo {
constructor ( answer ) {
this.answer = answer;
}

baz = 0
}`,

output: `
var Foo = function Foo ( answer ) {
this.baz = 0;
this.answer = answer;
};

`
},

{
description: 'transpiles a class declaration with class fields without a constructor',

input: `
class Foo {
baz = 0
}`,

output: `
var Foo = function Foo () {
this.baz = 0;
};

`
},

{
description: 'transpiles a class declaration with computed class fields',

input: `
const baz = 'bar'
class Foo {
[baz] = 0
}`,

output: `
var baz = 'bar'
var Foo = function Foo () {
this[baz] = 0;
};

`
},

{
description: 'transpiles a class declaration with class fields with no value',

input: `
class Foo {
baz;
}`,

output: `
var Foo = function Foo () {
this.baz;
};

`
},

{
description: 'transpiles a class declaration with computed class fields with no value',

input: `
const baz = 'bar'
class Foo {
[baz];
}`,

output: `
var baz = 'bar'
var Foo = function Foo () {
this[baz];
};

`
},

{
description: 'transpiles a class declaration with class fields separated by semicolons',

input: `
class X { constructor() {} m = 5; y = 4; }
`,

output: `
var X = function X() {
this.m = 5;
this.y = 4;};
`
},

{
description: 'transpiles a class declaration with class fields with comments',

input: `
class X {
constructor() {}
m = 5;
// comment
y = 4;
}
`,

output: `
var X = function X() {
this.m = 5;
this.y = 4;};

// comment

`
},

{
description: 'transpiles a subclass with class fields and super calls',

input: `
class Foo extends Bar {
constructor ( x ) {
super( x );
this.y = 'z';
}

baz ( a, b, c ) {
super.baz( a, b, c );
}

fab = 0
}`,

output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo ( x ) {
this.fab = 0;
Bar.call( this, x );
this.y = 'z';
}

if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;

Foo.prototype.baz = function baz ( a, b, c ) {
Bar.prototype.baz.call( this, a, b, c );
};



return Foo;
}(Bar));`
},

{
description: 'transpiles a subclass',

Expand Down