Commit ddbc9c2b by Marijn Haverbeke

Avoid giving names to methods when they shadow free variables

Issue #166
parent e1293ce3
Pipeline #5444254 passed with stage
in 1 minute 24 seconds
......@@ -140,7 +140,8 @@ export default class ClassBody extends Node {
code.insertRight( method.start, lhs );
const rhs = ( isAccessor ? `.${method.kind}` : '' ) + ` = function` + ( method.value.generator ? '* ' : ' ' ) + ( method.computed || isAccessor || !namedFunctions ? '' : `${methodName} ` );
const funcName = method.computed || isAccessor || !namedFunctions || method.value.body.scope.references[methodName] ? '' : `${methodName} `
const rhs = ( isAccessor ? `.${method.kind}` : '' ) + ` = function` + ( method.value.generator ? '* ' : ' ' ) + funcName;
code.remove( c, method.value.start );
code.insertRight( method.value.start, rhs );
code.insertLeft( method.end, ';' );
......
......@@ -12,7 +12,9 @@ export default class Property extends Node {
if ( this.key.type === 'Literal' && typeof this.key.value === 'number' ) {
name = "";
} else if ( this.key.type === 'Identifier' ) {
if ( reserved[ this.key.name ] || ! /^[a-z_$][a-z0-9_$]*$/i.test( this.key.name ) ) {
if ( reserved[ this.key.name ] ||
! /^[a-z_$][a-z0-9_$]*$/i.test( this.key.name ) ||
this.value.body.scope.references[this.key.name] ) {
name = this.findScope( true ).createIdentifier( this.key.name );
} else {
name = this.key.name;
......
......@@ -1181,6 +1181,23 @@ module.exports = [
`
},
{
description: "don't shadow variables with function names (#166)",
input: `
class X {
foo() { return foo }
bar() {}
}
`,
output: `
var X = function X () {};
X.prototype.foo = function () { return foo };
X.prototype.bar = function bar () {};
`
},
// TODO more tests. e.g. getters and setters.
// 'super.*' is not allowed before super()
];
......@@ -109,4 +109,21 @@ module.exports = [
var obj$1; }
`
},
{
description: 'avoids shadowing free variables with method names (#166)',
input: `
let x = {
foo() { return foo },
bar() {}
}
`,
output: `
var x = {
foo: function foo$1() { return foo },
bar: function bar() {}
}
`
},
];
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment