Skip to content
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

add support for optional chaining #412

Merged
Merged
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
39 changes: 30 additions & 9 deletions escodegen.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,12 @@
Await: 14,
Unary: 14,
Postfix: 15,
Call: 16,
New: 17,
TaggedTemplate: 18,
Member: 19,
Primary: 20
OptionalChaining: 16,
Call: 17,
New: 18,
TaggedTemplate: 19,
Member: 20,
Primary: 21
};

BinaryPrecedence = {
Expand Down Expand Up @@ -1871,8 +1872,14 @@

CallExpression: function (expr, precedence, flags) {
var result, i, iz;

// F_ALLOW_UNPARATH_NEW becomes false.
result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];

if (expr.optional) {
result.push('?.');
}

result.push('(');
for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
Expand All @@ -1885,9 +1892,20 @@
if (!(flags & F_ALLOW_CALL)) {
return ['(', result, ')'];
}

return parenthesize(result, Precedence.Call, precedence);
},

ChainExpression: function (expr, precedence, flags) {
if (Precedence.OptionalChaining < precedence) {
flags |= F_ALLOW_CALL;
}

var result = this.generateExpression(expr.expression, Precedence.OptionalChaining, flags);

return parenthesize(result, Precedence.OptionalChaining, precedence);
},

NewExpression: function (expr, precedence, flags) {
var result, length, i, iz, itemFlags;
length = expr['arguments'].length;
Expand Down Expand Up @@ -1922,11 +1940,15 @@
result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];

if (expr.computed) {
if (expr.optional) {
result.push('?.');
}

result.push('[');
result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
result.push(']');
} else {
if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
if (!expr.optional && expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
fragment = toSourceNodeWhenNeeded(result).toString();
// When the following conditions are all true,
// 1. No floating point
Expand All @@ -1943,7 +1965,7 @@
result.push(' ');
}
}
result.push('.');
result.push(expr.optional ? '?.' : '.');
sanex3339 marked this conversation as resolved.
Show resolved Hide resolved
result.push(generateIdentifier(expr.property));
}

Expand Down Expand Up @@ -2457,8 +2479,7 @@
this.generateExpression(expr.source, Precedence.Assignment, E_TTT),
')'
], Precedence.Call, precedence);
},

}
};

merge(CodeGenerator.prototype, CodeGenerator.Expression);
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"url": "http://github.com/estools/escodegen.git"
},
"dependencies": {
"estraverse": "^4.2.0",
"estraverse": "^5.2.0",
"esutils": "^2.0.2",
"esprima": "^4.0.1",
"optionator": "^0.8.1"
Expand All @@ -39,10 +39,11 @@
"source-map": "~0.6.1"
},
"devDependencies": {
"acorn": "^7.1.0",
"acorn": "^7.3.1",
"bluebird": "^3.4.7",
"bower-registry-client": "^1.0.0",
"chai": "^3.5.0",
"chai": "^4.2.0",
"chai-exclude": "^2.0.2",
"commonjs-everywhere": "^0.9.7",
"gulp": "^3.8.10",
"gulp-eslint": "^3.0.1",
Expand Down
95 changes: 95 additions & 0 deletions test/compare-acorn-es2020.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

'use strict';

var fs = require('fs'),
acorn = require('acorn'),
escodegen = require('./loader'),
chai = require('chai'),
chaiExclude = require('chai-exclude'),
expect = chai.expect;

chai.use(chaiExclude);

function test(code, expected) {
var tree, actual, actualTree, options;

options = {
ranges: false,
locations: false,
ecmaVersion: 11
};

tree = acorn.parse(code, options);

// for UNIX text comment
actual = escodegen.generate(tree);
actualTree = acorn.parse(actual, options);

expect(actual).to.be.equal(expected);
expect(tree).excludingEvery(['start', 'end']).to.deep.equal(actualTree);
}

function testMin(code, expected) {
var tree, actual, actualTree, options;

options = {
ranges: false,
locations: false,
ecmaVersion: 11
};

tree = acorn.parse(code, options);

// for UNIX text comment
actual = escodegen.generate(tree, {
format: escodegen.FORMAT_MINIFY,
raw: false
}).replace(/[\n\r]$/, '') + '\n';
actualTree = acorn.parse(actual, options);

expect(actual).to.be.equal(expected);
expect(tree).excludingEvery(['start', 'end']).to.deep.equal(actualTree);
michaelficarra marked this conversation as resolved.
Show resolved Hide resolved
}

describe('compare acorn es2020 test', function () {
fs.readdirSync(__dirname + '/compare-acorn-es2020').sort().forEach(function(file) {
var code, expected, exp, min;
if (/\.js$/.test(file) && !/expected\.js$/.test(file) && !/expected\.min\.js$/.test(file)) {
it(file, function () {
exp = file.replace(/\.js$/, '.expected.js');
min = file.replace(/\.js$/, '.expected.min.js');
code = fs.readFileSync(__dirname + '/compare-acorn-es2020/' + file, 'utf-8');
expected = fs.readFileSync(__dirname + '/compare-acorn-es2020/' + exp, 'utf-8');
test(code, expected);
if (fs.existsSync(__dirname + '/compare-acorn-es2020/' + min)) {
expected = fs.readFileSync(__dirname + '/compare-acorn-es2020/' + min, 'utf-8');
testMin(code, expected);
}
});
}
});
});
/* vim: set sw=4 ts=4 et tw=80 : */
47 changes: 47 additions & 0 deletions test/compare-acorn-es2020/optional-chaining.expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
obj.aaa.bbb;
obj.aaa?.bbb;
obj?.aaa.bbb;
obj?.aaa?.bbb;
obj.aaa.bbb;
obj.aaa?.bbb;
(obj?.aaa).bbb;
(obj?.aaa)?.bbb;
(obj?.aaa).bbb.ccc.ddd;
((obj?.aaa).bbb?.ccc).ddd;
(obj?.aaa)?.bbb;
obj[aaa][bbb];
obj[aaa]?.[bbb];
obj?.[aaa][bbb];
obj?.[aaa]?.[bbb];
obj[aaa][bbb];
obj[aaa]?.[bbb];
(obj?.[aaa])[bbb];
(obj?.[aaa])?.[bbb];
obj[aaa][bbb][ccc][ddd];
((obj?.[aaa])[bbb]?.[ccc])[ddd];
1?.a;
obj()();
obj()?.();
obj?.()();
obj?.()?.();
obj()();
obj()?.();
(obj?.())();
(obj?.())?.();
obj()()()();
((obj?.())()?.())();
(a?.b)();
a?.b();
a?.b?.();
(a?.b)?.();
a?.().b;
(a?.()).b;
a?.b.c();
(a?.b.c)();
a.b?.().c;
(a.b?.()).c;
(a.b?.())?.c;
new (a?.b().c)();
new (a?.b())();
new (a?.b().c)();
new (a?.b())();
michaelficarra marked this conversation as resolved.
Show resolved Hide resolved

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

47 changes: 47 additions & 0 deletions test/compare-acorn-es2020/optional-chaining.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
obj.aaa.bbb;
obj.aaa?.bbb;
obj?.aaa.bbb;
obj?.aaa?.bbb;
(obj.aaa).bbb;
(obj.aaa)?.bbb;
(obj?.aaa).bbb;
(obj?.aaa)?.bbb;
((obj?.aaa).bbb.ccc).ddd;
((obj?.aaa).bbb?.ccc).ddd;
(obj?.aaa)?.bbb;
obj[aaa][bbb];
obj[aaa]?.[bbb];
obj?.[aaa][bbb];
obj?.[aaa]?.[bbb];
(obj[aaa])[bbb];
(obj[aaa])?.[bbb];
(obj?.[aaa])[bbb];
(obj?.[aaa])?.[bbb];
((obj[aaa])[bbb][ccc])[ddd];
((obj?.[aaa])[bbb]?.[ccc])[ddd];
1?.a;
obj()();
obj()?.();
obj?.()();
obj?.()?.();
(obj())();
(obj())?.();
(obj?.())();
(obj?.())?.();
((obj())()())();
((obj?.())()?.())();
(a?.b)();
a?.b();
a?.b?.();
(a?.b)?.();
a?.().b;
(a?.()).b;
a?.b.c();
(a?.b.c)();
a.b?.().c;
(a.b?.()).c;
(a.b?.())?.c;
new (a?.b().c);
new (a?.b());
new (a?.b().c)();
new (a?.b())();