diff --git a/packages/babel-cli/test/fixtures/babel-external-helpers/--whitelist/stdout.txt b/packages/babel-cli/test/fixtures/babel-external-helpers/--whitelist/stdout.txt index d75b52e29f44..0c43dda166bf 100644 --- a/packages/babel-cli/test/fixtures/babel-external-helpers/--whitelist/stdout.txt +++ b/packages/babel-cli/test/fixtures/babel-external-helpers/--whitelist/stdout.txt @@ -1,6 +1,5 @@ (function (global) { var babelHelpers = global.babelHelpers = {}; - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; @@ -10,7 +9,6 @@ Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); @@ -19,6 +17,5 @@ }); return Constructor; } - babelHelpers.createClass = _createClass; })(typeof global === "undefined" ? self : global); diff --git a/packages/babel-cli/test/fixtures/babel/filename default comments/out-files/script2.js b/packages/babel-cli/test/fixtures/babel/filename default comments/out-files/script2.js index 944f80d6dd46..a9835a969d04 100644 --- a/packages/babel-cli/test/fixtures/babel/filename default comments/out-files/script2.js +++ b/packages/babel-cli/test/fixtures/babel/filename default comments/out-files/script2.js @@ -3,6 +3,9 @@ /* Test comment */ + arr.map(function (x) { return x * MULTIPLIER; -}); // END OF FILE +}); + +// END OF FILE \ No newline at end of file diff --git a/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js b/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js index baa5463236ad..b57b9e9ece3a 100644 --- a/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js +++ b/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js @@ -2,7 +2,9 @@ (function () { return 42; -}); // some comments +}); + +// some comments "use strict"; arr.map(function (x) { diff --git a/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js.map b/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js.map index 92ee347fe7c0..7ecd5f9a573c 100644 --- a/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js.map +++ b/packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps/out-files/script3.js.map @@ -1 +1 @@ -{"version":3,"file":"script3.js","names":["arr","map","x","MULTIPLIER"],"sources":["script.js","script2.js"],"sourcesContent":["(() => 42)\n\n// some comments","arr.map(x => x * MULTIPLIER);"],"mappings":";;AAAA,CAAC;EAAA,OAAM,EAAE;AAAA,GAAC,CAEV;;;ACFAA,GAAG,CAACC,GAAG,CAAC,UAAAC,CAAC;EAAA,OAAIA,CAAC,GAAGC,UAAU;AAAA,EAAC"} \ No newline at end of file +{"version":3,"file":"script3.js","names":["arr","map","x","MULTIPLIER"],"sources":["script.js","script2.js"],"sourcesContent":["(() => 42)\n\n// some comments","arr.map(x => x * MULTIPLIER);"],"mappings":";;AAAA,CAAC;EAAA,OAAM,EAAE;AAAA;;AAET;;;ACFAA,GAAG,CAACC,GAAG,CAAC,UAAAC,CAAC;EAAA,OAAIA,CAAC,GAAGC,UAAU;AAAA,EAAC"} \ No newline at end of file diff --git a/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js b/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js index d830585672ce..5cdb02af4d79 100644 --- a/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js +++ b/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js @@ -2,8 +2,10 @@ (function () { return 42; -}); // some comments -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sInNvdXJjZXMiOlsic2NyaXB0LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIigoKSA9PiA0MilcblxuLy8gc29tZSBjb21tZW50cyJdLCJtYXBwaW5ncyI6Ijs7QUFBQSxDQUFDO0VBQUEsT0FBTSxFQUFFO0FBQUEsR0FBQyxDQUVWIn0= +}); + +// some comments +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sInNvdXJjZXMiOlsic2NyaXB0LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIigoKSA9PiA0MilcblxuLy8gc29tZSBjb21tZW50cyJdLCJtYXBwaW5ncyI6Ijs7QUFBQSxDQUFDO0VBQUEsT0FBTSxFQUFFO0FBQUE7O0FBRVQifQ== "use strict"; arr.map(function (x) { diff --git a/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js.map b/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js.map index 3a8f49a36f66..a6ece43c10ff 100644 --- a/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js.map +++ b/packages/babel-cli/test/fixtures/babel/filenames-sourcemap-config-both/out-files/script3.js.map @@ -1 +1 @@ -{"version":3,"file":"script3.js","names":["arr","map","x","MULTIPLIER"],"sources":["script.js","script2.js"],"sourcesContent":["(() => 42)\n\n// some comments","arr.map(x => x * MULTIPLIER);"],"mappings":";;AAAA,CAAC;EAAA,OAAM,EAAE;AAAA,GAAC,CAEV;;;;ACFAA,GAAG,CAACC,GAAG,CAAC,UAAAC,CAAC;EAAA,OAAIA,CAAC,GAAGC,UAAU;AAAA,EAAC"} \ No newline at end of file +{"version":3,"file":"script3.js","names":["arr","map","x","MULTIPLIER"],"sources":["script.js","script2.js"],"sourcesContent":["(() => 42)\n\n// some comments","arr.map(x => x * MULTIPLIER);"],"mappings":";;AAAA,CAAC;EAAA,OAAM,EAAE;AAAA;;AAET;;;;ACFAA,GAAG,CAACC,GAAG,CAAC,UAAAC,CAAC;EAAA,OAAIA,CAAC,GAAGC,UAAU;AAAA,EAAC"} \ No newline at end of file diff --git a/packages/babel-core/test/api.js b/packages/babel-core/test/api.js index 8528e39a204c..dd974edeb5dd 100644 --- a/packages/babel-core/test/api.js +++ b/packages/babel-core/test/api.js @@ -625,7 +625,6 @@ describe("api", function () { ' throw new TypeError("Cannot call a class as a function");', " }", "}", - "", "let Foo = function Foo() {", " _classCallCheck(this, Foo);", "};", @@ -636,7 +635,7 @@ describe("api", function () { expect( originalPositionFor(consumer, { - line: 7, + line: 6, column: 4, }), ).toEqual({ @@ -710,7 +709,7 @@ describe("api", function () { ], }).then(function (result) { expect(result.code).toBe( - "/*before*/\nstart;\n\n/*after*/\nclass Foo {}\n\n/*before*/\nend;\n\n/*after*/", + "/*before*/\nstart;\n/*after*/\nclass Foo {}\n/*before*/\nend;\n/*after*/", ); }); }); diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-1130/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-1130/output.js index 415b39a812db..98980bfac743 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-1130/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-1130/output.js @@ -1,7 +1,6 @@ function A() { var a; } - function B() { var a; } diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-1155/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-1155/output.js index 44031949c78d..8e1c4b00564c 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-1155/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-1155/output.js @@ -2,19 +2,14 @@ var Foo = /*#__PURE__*/function (_Bar) { "use strict"; babelHelpers.inherits(Foo, _Bar); - var _super = babelHelpers.createSuper(Foo); - function Foo(options) { babelHelpers.classCallCheck(this, Foo); var parentOptions = {}; - parentOptions.init = function () { this; }; - return _super.call(this, parentOptions); } - return babelHelpers.createClass(Foo); }(Bar); diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-1169/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-1169/output.js index 910053ac4d12..b17dd6848797 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-1169/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-1169/output.js @@ -1,12 +1,10 @@ function foo() { var input = ['a', 'b', 'c']; var output = {}; - for (var _i = 0, _input = input; _i < _input.length; _i++) { var c = _input[_i]; var name = c; output[name] = name; } - return output; } diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-1199/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-1199/output.js index 7d278a3a8cbf..17e31293b44a 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-1199/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-1199/output.js @@ -1,7 +1,5 @@ const bug = 1; - function foo() {} - function bar() { var bug; bug = 2; diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-2364/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-2364/output.js index c1079c01cbbf..ed21d7382e33 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-2364/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-2364/output.js @@ -1,7 +1,6 @@ function wrapper(fn) { return function () { var _arguments = arguments; - var _loop = function () { var val = fn(..._arguments); return { @@ -10,10 +9,8 @@ function wrapper(fn) { }) }; }; - while (someCondition) { var _ret = _loop(); - if (typeof _ret === "object") return _ret.v; } }; diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-2765/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-2765/output.js index 8bcda9018e61..5b1e732e210e 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-2765/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-2765/output.js @@ -1,32 +1,26 @@ function f() { var _this = this; - let g = /*#__PURE__*/function () { var _ref = babelHelpers.asyncToGenerator(function* () { _this; }); - return function g() { return _ref.apply(this, arguments); }; }(); } - class Class { m() { var _this2 = this; - return babelHelpers.asyncToGenerator(function* () { var c = /*#__PURE__*/function () { var _ref2 = babelHelpers.asyncToGenerator(function* (b) { _this2; }); - return function c(_x) { return _ref2.apply(this, arguments); }; }(); })(); } - } diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js index fb14f76cc0c0..95cf1ea90be7 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js @@ -4,12 +4,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; - var Foo = /*#__PURE__*/function () { function Foo() { babelHelpers.classCallCheck(this, Foo); } - babelHelpers.createClass(Foo, [{ key: "bar", value: function () { @@ -20,7 +18,6 @@ var Foo = /*#__PURE__*/function () { switch (_context.prev = _context.next) { case 0: baz = 0; - case 1: case "end": return _context.stop(); @@ -28,27 +25,21 @@ var Foo = /*#__PURE__*/function () { } }, _callee); })); - function bar() { return _bar.apply(this, arguments); } - return bar; }() }]); return Foo; }(); - exports["default"] = Foo; - function foo() { return _foo.apply(this, arguments); } - function _foo() { _foo = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee3() { var bar, _bar2; - return babelHelpers.regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { @@ -61,7 +52,6 @@ function _foo() { switch (_context2.prev = _context2.next) { case 0: baz = {}; - case 1: case "end": return _context2.stop(); @@ -71,11 +61,9 @@ function _foo() { })); return _bar2.apply(this, arguments); }; - bar = function _bar3() { return _bar2.apply(this, arguments); }; - case 2: case "end": return _context3.stop(); diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/options.json b/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/options.json index d68815a31ec8..e385ec6bb8ed 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/options.json +++ b/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/options.json @@ -1,3 +1,4 @@ { - "plugins": ["transform-arrow-functions", "transform-function-name"] + "plugins": ["transform-arrow-functions", "transform-function-name"], + "sourceMap": true } diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/source-mappings.json b/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/source-mappings.json deleted file mode 100644 index a1d1d31e4a0c..000000000000 --- a/packages/babel-core/test/fixtures/transformation/source-maps/arrow-function/source-mappings.json +++ /dev/null @@ -1,10 +0,0 @@ -[{ - "original": { - "line": 1, - "column": 14 - }, - "generated": { - "line": 2, - "column": 10 - } -}] diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/class/options.json b/packages/babel-core/test/fixtures/transformation/source-maps/class/options.json index 5d03380e6f36..cdb1dea8e931 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/class/options.json +++ b/packages/babel-core/test/fixtures/transformation/source-maps/class/options.json @@ -1,3 +1,4 @@ { - "plugins": ["transform-classes", "transform-block-scoping"] + "plugins": ["transform-classes", "transform-block-scoping"], + "sourceMap": true } diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/class/output.js b/packages/babel-core/test/fixtures/transformation/source-maps/class/output.js index 8f75c22d4d81..f133bd6baa62 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/class/output.js +++ b/packages/babel-core/test/fixtures/transformation/source-maps/class/output.js @@ -4,7 +4,6 @@ var Test = /*#__PURE__*/function () { function Test() { babelHelpers.classCallCheck(this, Test); } - babelHelpers.createClass(Test, [{ key: "bar", get: function () { @@ -13,6 +12,5 @@ var Test = /*#__PURE__*/function () { }]); return Test; }(); - var test = new Test(); test.bar; diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/class/source-mappings.json b/packages/babel-core/test/fixtures/transformation/source-maps/class/source-mappings.json deleted file mode 100644 index c00fd6e9bcf5..000000000000 --- a/packages/babel-core/test/fixtures/transformation/source-maps/class/source-mappings.json +++ /dev/null @@ -1,10 +0,0 @@ -[{ - "original": { - "line": 3, - "column": 10 - }, - "generated": { - "line": 11, - "column": 15 - } -}] \ No newline at end of file diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/comment-inside-string/output.js b/packages/babel-core/test/fixtures/transformation/source-maps/comment-inside-string/output.js index 9188ec5abc3b..375e735ff2db 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/comment-inside-string/output.js +++ b/packages/babel-core/test/fixtures/transformation/source-maps/comment-inside-string/output.js @@ -1,5 +1,6 @@ // https://github.com/babel/babel/issues/9790 -const comment = `//# sourceMappingURL=${path.basename(sourceMapFilename)}`; // https://github.com/babel/babel/issues/9956 +const comment = `//# sourceMappingURL=${path.basename(sourceMapFilename)}`; +// https://github.com/babel/babel/issues/9956 this.shadowRoot.innerHTML = ``; diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/options.json b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/options.json index 81e5ce12436d..0875db7e2b86 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/options.json +++ b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/options.json @@ -1,3 +1,4 @@ { - "plugins": ["transform-modules-commonjs"] + "plugins": ["transform-modules-commonjs"], + "sourceMap": true } diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/output.js b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/output.js index 5abbe8e6bc44..104079e3405f 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/output.js +++ b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/output.js @@ -91,13 +91,11 @@ exports.default = void 0; // var _default = { name: 'HelloWorld', - data() { return { msg: 'Welcome to Your Vue.js App' }; } - }; // // // @@ -116,5 +114,4 @@ var _default = { // // // - exports.default = _default; diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/source-mappings.json b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/source-mappings.json deleted file mode 100644 index f41b80a82318..000000000000 --- a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-complex/source-mappings.json +++ /dev/null @@ -1,72 +0,0 @@ -[ - { - "generated": { - "line": 92, - "column": 15 - }, - "original": { - "line": 87, - "column": 0 - } - }, - { - "generated": { - "line": 93, - "column": 2 - }, - "original": { - "line": 88, - "column": 0 - } - }, - { - "generated": { - "line": 95, - "column": 9 - }, - "original": { - "line": 89, - "column": 0 - } - }, - { - "generated": { - "line": 96, - "column": 4 - }, - "original": { - "line": 90, - "column": 0 - } - }, - { - "generated": { - "line": 97, - "column": 6 - }, - "original": { - "line": 91, - "column": 0 - } - }, - { - "generated": { - "line": 98, - "column": 4 - }, - "original": { - "line": 92, - "column": 0 - } - }, - { - "generated": { - "line": 99, - "column": 2 - }, - "original": { - "line": 93, - "column": 0 - } - } -] diff --git a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-multiple-output-sources/output.js b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-multiple-output-sources/output.js index 4d0b018046c9..8c62e1f98b61 100644 --- a/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-multiple-output-sources/output.js +++ b/packages/babel-core/test/fixtures/transformation/source-maps/input-source-map-multiple-output-sources/output.js @@ -1,5 +1,4 @@ "bar"; - function foo(bar) { throw new Error('Intentional.'); } diff --git a/packages/babel-generator/src/buffer.ts b/packages/babel-generator/src/buffer.ts index 219a814092c4..9e5acb44821c 100644 --- a/packages/babel-generator/src/buffer.ts +++ b/packages/babel-generator/src/buffer.ts @@ -303,6 +303,25 @@ export default class Buffer { return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last; } + /** + * This will only detect at most 1 newline after a call to `flush()`, + * but this has not been found so far, and an accurate count can be achieved if needed later. + */ + getNewlineCount(): number { + const queueCursor = this._queueCursor; + let count = 0; + if (queueCursor === 0) return this._last === charcodes.lineFeed ? 1 : 0; + for (let i = queueCursor - 1; i >= 0; i--) { + if (this._queue[i].char !== charcodes.lineFeed) { + break; + } + count++; + } + return count === queueCursor && this._last === charcodes.lineFeed + ? count + 1 + : count; + } + /** * check if current _last + queue ends with newline, return the character before newline * @@ -419,15 +438,16 @@ export default class Buffer { getCurrentColumn(): number { const queue = this._queue; + const queueCursor = this._queueCursor; let lastIndex = -1; let len = 0; - for (let i = 0; i < this._queueCursor; i++) { + for (let i = 0; i < queueCursor; i++) { const item = queue[i]; if (item.char === charcodes.lineFeed) { - lastIndex = i; - len += item.repeat; + lastIndex = len; } + len += item.repeat; } return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex; diff --git a/packages/babel-generator/src/generators/base.ts b/packages/babel-generator/src/generators/base.ts index 7bf482ca908a..951d23584341 100644 --- a/packages/babel-generator/src/generators/base.ts +++ b/packages/babel-generator/src/generators/base.ts @@ -1,6 +1,5 @@ import type Printer from "../printer"; import type * as t from "@babel/types"; -import * as charCodes from "charcodes"; export function File(this: Printer, node: t.File) { if (node.program) { @@ -15,8 +14,16 @@ export function File(this: Printer, node: t.File) { export function Program(this: Printer, node: t.Program) { this.printInnerComments(node, false); - this.printSequence(node.directives, node); - if (node.directives && node.directives.length) this.newline(); + const directivesLen = node.directives?.length; + if (directivesLen) { + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, node, { + trailingCommentsLineOffset: newline, + }); + if (!node.directives[directivesLen - 1].trailingComments?.length) { + this.newline(newline); + } + } this.printSequence(node.body, node); } @@ -25,21 +32,22 @@ export function BlockStatement(this: Printer, node: t.BlockStatement) { this.token("{"); this.printInnerComments(node); - const hasDirectives = node.directives?.length; - - if (node.body.length || hasDirectives) { - this.newline(); - - this.printSequence(node.directives, node, { indent: true }); - if (hasDirectives) this.newline(); - - this.printSequence(node.body, node, { indent: true }); - this.removeTrailingNewline(); - - if (!this.endsWith(charCodes.lineFeed)) this.newline(); + const directivesLen = node.directives?.length; + if (directivesLen) { + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, node, { + indent: true, + trailingCommentsLineOffset: newline, + }); + if (!node.directives[directivesLen - 1].trailingComments?.length) { + this.newline(newline); + } } + this.printSequence(node.body, node, { indent: true }); + this.sourceWithOffset("end", node.loc, 0, -1); + this.rightBrace(); } @@ -81,7 +89,8 @@ export function InterpreterDirective( this: Printer, node: t.InterpreterDirective, ) { - this.token(`#!${node.value}\n`, true); + this.token(`#!${node.value}`); + this.newline(1, true); } export function Placeholder(this: Printer, node: t.Placeholder) { diff --git a/packages/babel-generator/src/generators/flow.ts b/packages/babel-generator/src/generators/flow.ts index 7d037bbf321a..563d158d5327 100644 --- a/packages/babel-generator/src/generators/flow.ts +++ b/packages/babel-generator/src/generators/flow.ts @@ -596,6 +596,8 @@ export function ObjectTypeAnnotation( ]; if (props.length) { + this.newline(); + this.space(); this.printJoin(props, node, { diff --git a/packages/babel-generator/src/generators/statements.ts b/packages/babel-generator/src/generators/statements.ts index 64d9c777a316..da67affc209b 100644 --- a/packages/babel-generator/src/generators/statements.ts +++ b/packages/babel-generator/src/generators/statements.ts @@ -248,24 +248,6 @@ export function DebuggerStatement(this: Printer) { this.semicolon(); } -function variableDeclarationIndent(this: Printer) { - // "let " or "var " indentation. - this.token(","); - this.newline(); - if (this.endsWith(charCodes.lineFeed)) { - for (let i = 0; i < 4; i++) this.space(true); - } -} - -function constDeclarationIndent(this: Printer) { - // "const " indentation. - this.token(","); - this.newline(); - if (this.endsWith(charCodes.lineFeed)) { - for (let i = 0; i < 6; i++) this.space(true); - } -} - export function VariableDeclaration( this: Printer, node: t.VariableDeclaration, @@ -303,17 +285,15 @@ export function VariableDeclaration( // bar = "foo"; // - let separator; - if (hasInits) { - separator = - node.kind === "const" - ? constDeclarationIndent - : variableDeclarationIndent; - } - - // - - this.printList(node.declarations, node, { separator }); + this.printList(node.declarations, node, { + separator: hasInits + ? function (this: Printer) { + this.token(","); + this.newline(); + } + : undefined, + indent: node.declarations.length > 1 ? true : false, + }); if (isFor(parent)) { // don't give semicolons to these nodes since they'll be inserted in the parent generator diff --git a/packages/babel-generator/src/printer.ts b/packages/babel-generator/src/printer.ts index c7fff0844ce6..70cf22cf6721 100644 --- a/packages/babel-generator/src/printer.ts +++ b/packages/babel-generator/src/printer.ts @@ -17,7 +17,20 @@ const ZERO_DECIMAL_INTEGER = /\.0+$/; const NON_DECIMAL_LITERAL = /^0[box]/; const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; -const { needsParens, needsWhitespaceAfter, needsWhitespaceBefore } = n; +const { needsParens } = n; + +const enum COMMENT_TYPE { + LEADING, + INNER, + TRAILING, +} + +const enum COMMENT_SKIP_NEWLINE { + DEFAULT, + SKIP_ALL, + SKIP_LEADING, + SKIP_TRAILING, +} export type Format = { shouldPrintComment: (comment: string) => boolean; @@ -49,11 +62,13 @@ export type Format = { interface AddNewlinesOptions { addNewlines(leading: boolean, node: t.Node): number; + nextNodeStartLine: number; } interface PrintSequenceOptions extends Partial { statement?: boolean; indent?: boolean; + trailingCommentsLineOffset?: number; } interface PrintListOptions { @@ -90,6 +105,7 @@ class Printer { _printedComments = new Set(); _endsWithInteger = false; _endsWithWord = false; + _lastCommentLine = 0; generate(ast: t.Node) { this.print(ast); @@ -239,31 +255,31 @@ class Printer { /** * Add a newline (or many newlines), maintaining formatting. + * This function checks the number of newlines in the queue and subtracts them. + * It currently has some limitations. + * @see {Buffer#getNewlineCount} */ + newline(i: number = 1, force?: boolean): void { + if (i <= 0) return; - newline(i: number = 1): void { - if (this.format.retainLines || this.format.compact) return; + if (!force) { + if (this.format.retainLines || this.format.compact) return; - if (this.format.concise) { - this.space(); - return; + if (this.format.concise) { + this.space(); + return; + } } - const charBeforeNewline = this.endsWithCharAndNewline(); - // never allow more than two lines - if (charBeforeNewline === charCodes.lineFeed) return; + if (i > 2) i = 2; // Max two lines - if ( - charBeforeNewline === charCodes.leftCurlyBrace || - charBeforeNewline === charCodes.colon - ) { - i--; - } - if (i <= 0) return; + i -= this._buf.getNewlineCount(); for (let j = 0; j < i; j++) { this._newline(); } + + return; } endsWith(char: number): boolean { @@ -372,6 +388,17 @@ class Printer { } } + _shouldIndent(firstChar: number) { + // we've got a newline before us so prepend on the indentation + if ( + this._indent && + firstChar !== charCodes.lineFeed && + this.endsWith(charCodes.lineFeed) + ) { + return true; + } + } + _maybeAddParenChar(char: number): void { // see startTerminatorless() instance method const parenPushNewlineState = this._parenPushNewlineState; @@ -539,7 +566,14 @@ class Printer { } } - print(node: t.Node | null, parent?: t.Node, noLineTerminator?: boolean) { + print( + node: t.Node | null, + parent?: t.Node, + noLineTerminator?: boolean, + // trailingCommentsLineOffset also used to check if called from printJoin + // it will be ignored if `noLineTerminator||this._noLineTerminator` + trailingCommentsLineOffset?: number, + ) { if (!node) return; const nodeType = node.type; @@ -577,7 +611,7 @@ class Printer { this._insideAux = node.loc == undefined; this._maybeAddAuxComment(this._insideAux && !oldInAux); - let shouldPrintParens: boolean; + let shouldPrintParens = false; if ( format.retainFunctionParens && nodeType === "FunctionExpression" && @@ -590,6 +624,8 @@ class Printer { } if (shouldPrintParens) this.token("("); + this._lastCommentLine = 0; + this._printLeadingComments(node); const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; @@ -601,7 +637,7 @@ class Printer { this._printTrailingComments(node); this._noLineTerminator = false; } else { - this._printTrailingComments(node); + this._printTrailingComments(node, trailingCommentsLineOffset); } if (shouldPrintParens) this.token(")"); @@ -624,10 +660,13 @@ class Printer { const comment = this.format.auxiliaryCommentBefore; if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment, - }); + this._printComment( + { + type: "CommentBlock", + value: comment, + }, + COMMENT_SKIP_NEWLINE.DEFAULT, + ); } } @@ -637,10 +676,13 @@ class Printer { const comment = this.format.auxiliaryCommentAfter; if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment, - }); + this._printComment( + { + type: "CommentBlock", + value: comment, + }, + COMMENT_SKIP_NEWLINE.DEFAULT, + ); } } @@ -676,26 +718,34 @@ class Printer { const newlineOpts: AddNewlinesOptions = { addNewlines: opts.addNewlines, + nextNodeStartLine: 0, }; + const separator = opts.separator ? opts.separator.bind(this) : null; + const len = nodes.length; for (let i = 0; i < len; i++) { const node = nodes[i]; if (!node) continue; - if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + if (opts.statement) this._printNewline(i === 0, newlineOpts); - this.print(node, parent); + this.print(node, parent, undefined, opts.trailingCommentsLineOffset || 0); - if (opts.iterator) { - opts.iterator(node, i); - } + opts.iterator?.(node, i); - if (opts.separator && i < len - 1) { - opts.separator.call(this); - } + if (i < len - 1) separator?.(); + + if (opts.statement) { + if (i + 1 === len) { + this.newline(1); + } else { + const nextNode = nodes[i + 1]; + newlineOpts.nextNodeStartLine = nextNode.loc?.start.line || 0; - if (opts.statement) this._printNewline(false, node, parent, newlineOpts); + this._printNewline(true, newlineOpts); + } + } } if (opts.indent) this.dedent(); @@ -718,22 +768,22 @@ class Printer { this.print(node, parent); } - _printTrailingComments(node: t.Node) { - this._printComments(this._getComments(false, node)); + _printTrailingComments(node: t.Node, lineOffset?: number) { + const comments = this._getComments(false, node); + if (!comments?.length) return; + this._printComments(COMMENT_TYPE.TRAILING, comments, node, lineOffset); } _printLeadingComments(node: t.Node) { - this._printComments( - this._getComments(true, node), - // Don't add leading/trailing new lines to #__PURE__ annotations - true, - ); + const comments = this._getComments(true, node); + if (!comments?.length) return; + this._printComments(COMMENT_TYPE.LEADING, comments, node); } printInnerComments(node: t.Node, indent = true) { if (!node.innerComments?.length) return; if (indent) this.indent(); - this._printComments(node.innerComments); + this._printComments(COMMENT_TYPE.INNER, node.innerComments, node); if (indent) this.dedent(); } @@ -754,12 +804,7 @@ class Printer { return this.printJoin(items, parent, opts); } - _printNewline( - leading: boolean, - node: t.Node, - parent: t.Node, - opts: AddNewlinesOptions, - ) { + _printNewline(newLine: boolean, opts: AddNewlinesOptions) { // Fast path since 'this.newline' does nothing when not tracking lines. if (this.format.retainLines || this.format.compact) return; @@ -770,17 +815,36 @@ class Printer { return; } - let lines = 0; + if (!newLine) { + return; + } + + const startLine = opts.nextNodeStartLine; + const lastCommentLine = this._lastCommentLine; + if (startLine > 0 && lastCommentLine > 0) { + const offset = startLine - lastCommentLine; + if (offset >= 0) { + this.newline(offset || 1); + return; + } + } + // don't add newlines at the beginning of the file if (this._buf.hasContent()) { - if (!leading) lines++; // always include at least a single line after - if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + // Here is the logic of the original line wrapping according to the node layout, we are not using it now. + // We currently add at most one newline to each node in the list, ignoring `opts.addNewlines`. - const needs = leading ? needsWhitespaceBefore : needsWhitespaceAfter; - if (needs(node, parent)) lines++; - } + // let lines = 0; + // if (!leading) lines++; // always include at least a single line after + // if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + + // const needs = leading ? needsWhitespaceBefore : needsWhitespaceAfter; + // if (needs(node, parent)) lines++; - this.newline(Math.min(2, lines)); + // this.newline(Math.min(2, lines)); + + this.newline(1); + } } _getComments(leading: boolean, node: t.Node) { @@ -791,7 +855,7 @@ class Printer { ); } - _printComment(comment: t.Comment, skipNewLines?: boolean) { + _printComment(comment: t.Comment, skipNewLines: COMMENT_SKIP_NEWLINE) { // Some plugins (such as flow-strip-types) use this to mark comments as removed using the AST-root 'comments' property, // where they can't manually mutate the AST node comment lists. if (comment.ignore) return; @@ -807,9 +871,17 @@ class Printer { // Add a newline before and after a block comment, unless explicitly // disallowed const printNewLines = - isBlockComment && !skipNewLines && !this._noLineTerminator; + isBlockComment && + skipNewLines !== COMMENT_SKIP_NEWLINE.SKIP_ALL && + !this._noLineTerminator; - if (printNewLines && this._buf.hasContent()) this.newline(1); + if ( + printNewLines && + this._buf.hasContent() && + skipNewLines !== COMMENT_SKIP_NEWLINE.SKIP_LEADING + ) { + this.newline(1); + } const lastCharCode = this.getLastChar(); if ( @@ -820,7 +892,6 @@ class Printer { } let val; - let maybeNewline = false; if (isBlockComment) { val = `/*${comment.value}*/`; if (this.format.indent.adjustMultilineComment) { @@ -830,17 +901,18 @@ class Printer { val = val.replace(newlineRegex, "\n"); } - const indentSize = Math.max( - this._getIndent(), - this.format.retainLines ? 0 : this._buf.getCurrentColumn(), - ); - val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); + let indentSize = this.format.retainLines + ? 0 + : this._buf.getCurrentColumn(); + + if (this._shouldIndent(charCodes.slash) || this.format.retainLines) { + indentSize += this._getIndent(); + } - maybeNewline = true; + val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); } } else if (!this._noLineTerminator) { - val = `//${comment.value}\n`; - maybeNewline = true; + val = `//${comment.value}`; } else { val = `/*${comment.value}*/`; } @@ -849,30 +921,116 @@ class Printer { if (this.endsWith(charCodes.slash)) this._space(); this.source("start", comment.loc); - this._append(val, maybeNewline); + this._append(val, isBlockComment); - if (printNewLines) this.newline(1); + if (!isBlockComment && !this._noLineTerminator) { + this.newline(1, true); + } + + if (printNewLines && skipNewLines !== COMMENT_SKIP_NEWLINE.SKIP_TRAILING) { + this.newline(1); + } } _printComments( - comments?: readonly t.Comment[], - inlinePureAnnotation?: boolean, + type: COMMENT_TYPE, + comments: readonly t.Comment[], + node: t.Node, + lineOffset: number = 0, ) { - if (!comments?.length) return; + { + const nodeLoc = node.loc; + const len = comments.length; + let hasLoc = !!nodeLoc; + const nodeStartLine = hasLoc ? nodeLoc.start.line : 0; + const nodeEndLine = hasLoc ? nodeLoc.end.line : 0; + let lastLine = 0; + let leadingCommentNewline = 0; + + for (let i = 0; i < len; i++) { + const comment = comments[i]; + + if (hasLoc && "loc" in comment && !this._printedComments.has(comment)) { + const commentStartLine = comment.loc.start.line; + const commentEndLine = comment.loc.end.line; + if (type === COMMENT_TYPE.LEADING) { + let offset = 0; + if (i === 0) { + // Because currently we cannot handle blank lines before leading comments, + // we always wrap before and after multi-line comments. + if ( + this._buf.hasContent() && + (comment.type === "CommentLine" || + commentStartLine != commentEndLine) + ) { + offset = leadingCommentNewline = 1; + } + } else { + offset = commentStartLine - lastLine; + } + lastLine = commentEndLine; + + this.newline(offset); + this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL); + + if (i + 1 === len) { + this.newline( + Math.max(nodeStartLine - lastLine, leadingCommentNewline), + ); + lastLine = nodeStartLine; + } + } else if (type === COMMENT_TYPE.INNER) { + const offset = + commentStartLine - (i === 0 ? nodeStartLine : lastLine); + lastLine = commentEndLine; + + this.newline(offset); + this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL); + + if (i + 1 === len) { + this.newline(Math.min(1, nodeEndLine - lastLine)); // TODO: Improve here when inner comments processing is stronger + lastLine = nodeEndLine; + } + } else { + const offset = + commentStartLine - + (i === 0 ? nodeEndLine - lineOffset : lastLine); + lastLine = commentEndLine; + + this.newline(offset); + this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL); + } + } else { + hasLoc = false; + + if (len === 1) { + this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL); + } else if ( + type === COMMENT_TYPE.INNER && + !(node.type === "ObjectExpression" && node.properties.length > 1) && + node.type !== "ClassBody" + ) { + // class X { + // /*:: a: number*/ + // /*:: b: ?string*/ + // } + + this._printComment( + comment, + i === 0 + ? COMMENT_SKIP_NEWLINE.SKIP_LEADING + : i === len - 1 + ? COMMENT_SKIP_NEWLINE.SKIP_TRAILING + : COMMENT_SKIP_NEWLINE.DEFAULT, + ); + } else { + this._printComment(comment, COMMENT_SKIP_NEWLINE.DEFAULT); + } + } + } - if ( - inlinePureAnnotation && - comments.length === 1 && - PURE_ANNOTATION_RE.test(comments[0].value) - ) { - this._printComment( - comments[0], - // Keep newlines if the comment marks a standalone call - this._buf.hasContent() && !this.endsWith(charCodes.lineFeed), - ); - } else { - for (const comment of comments) { - this._printComment(comment); + if (type === COMMENT_TYPE.TRAILING && hasLoc && lastLine) { + this._lastCommentLine = lastLine; } } } diff --git a/packages/babel-generator/test/arrow-functions.js b/packages/babel-generator/test/arrow-functions.js index 42d17fdc0025..ec9cdc3c4b2b 100644 --- a/packages/babel-generator/test/arrow-functions.js +++ b/packages/babel-generator/test/arrow-functions.js @@ -28,23 +28,18 @@ describe("parameter parentheses", () => { const output = generate(ast, { auxiliaryCommentBefore: "BEFORE" }).code; expect(output).toMatchInlineSnapshot(` "() => {}; - ( /*BEFORE*/ a) => {}; - ( /*BEFORE*/ a, /*BEFORE*/ b) => {}; - async () => {}; - async ( /*BEFORE*/ a) => {}; - async ( /*BEFORE*/ a, @@ -58,23 +53,18 @@ describe("parameter parentheses", () => { const output = generate(ast, { auxiliaryCommentAfter: "AFTER" }).code; expect(output).toMatchInlineSnapshot(` "() => {}; - (a /*AFTER*/ ) => {}; - (a /*AFTER*/ , b /*AFTER*/ ) => {}; - async () => {}; - async (a /*AFTER*/ ) => {}; - async (a /*AFTER*/ , b @@ -88,15 +78,10 @@ describe("parameter parentheses", () => { const output = generate(ast).code; expect(output).toMatchInlineSnapshot(` "() => {}; - a => {}; - (a, b) => {}; - async () => {}; - async a => {}; - async (a, b) => {};" `); }); @@ -106,15 +91,10 @@ describe("parameter parentheses", () => { const output = generate(ast).code; expect(output).toMatchInlineSnapshot(` "() => {}; - a => {}; - (a, b) => {}; - async () => {}; - async a => {}; - async (a, b) => {};" `); }); diff --git a/packages/babel-generator/test/fixtures/auto-indentation/hard-tab/output.js b/packages/babel-generator/test/fixtures/auto-indentation/hard-tab/output.js index b2a374caae06..ea37070d534c 100644 --- a/packages/babel-generator/test/fixtures/auto-indentation/hard-tab/output.js +++ b/packages/babel-generator/test/fixtures/auto-indentation/hard-tab/output.js @@ -1,6 +1,5 @@ function foo() { bar(); - if (foo) { bar(); } diff --git a/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-2/output.js b/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-2/output.js index b2a374caae06..ea37070d534c 100644 --- a/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-2/output.js +++ b/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-2/output.js @@ -1,6 +1,5 @@ function foo() { bar(); - if (foo) { bar(); } diff --git a/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-4/output.js b/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-4/output.js index b2a374caae06..ea37070d534c 100644 --- a/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-4/output.js +++ b/packages/babel-generator/test/fixtures/auto-indentation/soft-tab-4/output.js @@ -1,6 +1,5 @@ function foo() { bar(); - if (foo) { bar(); } diff --git a/packages/babel-generator/test/fixtures/auto-string/jsx/output.js b/packages/babel-generator/test/fixtures/auto-string/jsx/output.js index f29a06c003c6..d59d26919bad 100644 --- a/packages/babel-generator/test/fixtures/auto-string/jsx/output.js +++ b/packages/babel-generator/test/fixtures/auto-string/jsx/output.js @@ -5,5 +5,4 @@ React.createClass({ render() { return ; } - }); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/2-space-multi-comment-with-space/output.js b/packages/babel-generator/test/fixtures/comments/2-space-multi-comment-with-space/output.js index 29f1735b8a5d..6b25f89e2e53 100644 --- a/packages/babel-generator/test/fixtures/comments/2-space-multi-comment-with-space/output.js +++ b/packages/babel-generator/test/fixtures/comments/2-space-multi-comment-with-space/output.js @@ -2,5 +2,6 @@ function test() { /* * this is comment */ + var i = 20; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/async-arrow-single-param-with-comments/output.js b/packages/babel-generator/test/fixtures/comments/async-arrow-single-param-with-comments/output.js index e952f5d6f0ef..addc834ee0ed 100644 --- a/packages/babel-generator/test/fixtures/comments/async-arrow-single-param-with-comments/output.js +++ b/packages/babel-generator/test/fixtures/comments/async-arrow-single-param-with-comments/output.js @@ -1,13 +1,3 @@ -async ( -/** @type {any} */ -arg) => {}; - -async (arg -/* trailing */ -) => {}; - -async ( -/** @type {any} */ -arg -/* trailing */ -) => {}; \ No newline at end of file +async ( /** @type {any} */arg) => {}; +async (arg /* trailing */) => {}; +async ( /** @type {any} */arg /* trailing */) => {}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/comment-only-with-space/output.js b/packages/babel-generator/test/fixtures/comments/comment-only-with-space/output.js index 355757ad180d..a012a70682d2 100644 --- a/packages/babel-generator/test/fixtures/comments/comment-only-with-space/output.js +++ b/packages/babel-generator/test/fixtures/comments/comment-only-with-space/output.js @@ -1,3 +1,4 @@ + // from #23 /**/ diff --git a/packages/babel-generator/test/fixtures/comments/comment-only/output.js b/packages/babel-generator/test/fixtures/comments/comment-only/output.js index 355757ad180d..0560460f82ca 100644 --- a/packages/babel-generator/test/fixtures/comments/comment-only/output.js +++ b/packages/babel-generator/test/fixtures/comments/comment-only/output.js @@ -1,6 +1,4 @@ // from #23 - /**/ - /* */ \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/input.js b/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/input.js index 0c0c0272a580..90f6d68a1ba4 100644 --- a/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/input.js +++ b/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/input.js @@ -6,5 +6,8 @@ var test = { [/* * Inside bracket init */ - "b"]:"2" + "b"]:"2", + [/** + * Multi-line + */"c"]:"3", }, ok = 42; diff --git a/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/output.js b/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/output.js index 7d61aafdbc0e..ad40bba45ae9 100644 --- a/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/output.js +++ b/packages/babel-generator/test/fixtures/comments/computed-property-comments-2/output.js @@ -1,12 +1,17 @@ var test = { - /** - * Before bracket init - */ - ["a"]: "1", - [ - /* - * Inside bracket init - */ - "b"]: "2" -}, - ok = 42; \ No newline at end of file + /** + * Before bracket init + */ + ["a"]: "1", + [ + /* + * Inside bracket init + */ + "b"]: "2", + [ + /** + * Multi-line + */ + "c"]: "3" + }, + ok = 42; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/computed-property-comments/output.js b/packages/babel-generator/test/fixtures/comments/computed-property-comments/output.js index b0458bffb524..3eaa205ad6f0 100644 --- a/packages/babel-generator/test/fixtures/comments/computed-property-comments/output.js +++ b/packages/babel-generator/test/fixtures/comments/computed-property-comments/output.js @@ -11,12 +11,13 @@ var test = { ["c" /* * After bracket key - */ - ]: "3", + */]: "3", // Before bracket, line comment ["d"]: "4", - [// Inside bracket, line comment + [ + // Inside bracket, line comment "e"]: "5", - ["f" // After bracket, line comment + ["f" + // After bracket, line comment ]: "6" }; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/create-parenthesized-expressions/output.js b/packages/babel-generator/test/fixtures/comments/create-parenthesized-expressions/output.js index b78500e8017f..4788666f9a94 100644 --- a/packages/babel-generator/test/fixtures/comments/create-parenthesized-expressions/output.js +++ b/packages/babel-generator/test/fixtures/comments/create-parenthesized-expressions/output.js @@ -1,10 +1,9 @@ // One (1); -/* Two */ +/* Two */ (2); -( // Three -3); ( -/* Four */ -4); \ No newline at end of file +// Three +3); +( /* Four */4); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/function-block-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/function-block-line-comment/output.js index 7498613eaa86..db20654d464b 100644 --- a/packages/babel-generator/test/fixtures/comments/function-block-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/function-block-line-comment/output.js @@ -3,9 +3,7 @@ !{ get 42() {} // , - foo: 42 }; - (function () {} // ); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/if-block-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/if-block-line-comment/output.js index 5b9355b6ed11..efe502601fea 100644 --- a/packages/babel-generator/test/fixtures/comments/if-block-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/if-block-line-comment/output.js @@ -1,4 +1,5 @@ -if (cond) // Leading to if-block +if (cond) + // Leading to if-block { print("hello"); } // Trailing to if-block \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/if-empty-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/if-empty-line-comment/output.js index 4982b7d9326c..fc298a57b3bb 100644 --- a/packages/babel-generator/test/fixtures/comments/if-empty-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/if-empty-line-comment/output.js @@ -1,2 +1,3 @@ -if (cond) // Leading to EmptyStatement +if (cond) + // Leading to EmptyStatement ; // Trailing to EmptyStatement \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/if-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/if-line-comment/output.js index 8bf9f319fb94..81f3c0a4183e 100644 --- a/packages/babel-generator/test/fixtures/comments/if-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/if-line-comment/output.js @@ -2,6 +2,6 @@ function test() { // Leading if statement if (cond) { print("hello"); - } // Trailing if-block statement - + } + // Trailing if-block statement } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/module-expression-inner-comment/output.js b/packages/babel-generator/test/fixtures/comments/module-expression-inner-comment/output.js index a232445de6be..2580ab90d79b 100644 --- a/packages/babel-generator/test/fixtures/comments/module-expression-inner-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/module-expression-inner-comment/output.js @@ -1,3 +1 @@ -module /* 1 */ { - /* 2 */ -}; \ No newline at end of file +module /* 1 */ {/* 2 */}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/newlines/input.js b/packages/babel-generator/test/fixtures/comments/newlines/input.js new file mode 100644 index 000000000000..f2d4cf0b94ea --- /dev/null +++ b/packages/babel-generator/test/fixtures/comments/newlines/input.js @@ -0,0 +1,99 @@ +a; + +// my comment +b; + +c; +// my comment + +d; + + +/** + * Hello + * @param {*} params + */ +function fn(params) { + +} + +/** + * Hello + * @param {*} params + */ + +function fn2(params) { + +} + +x; // my comment +x; + +x; // my comment + +x; + +x; /* */ +x; + +x; /* */ + +x; + +x; /* my comment1 */ +x; /* my comment2 */ + +x; // my comment3 +x; // my comment4 + +x; // my comment5 + +// my comment6 +// my comment7 + +/* my comment8 */ + +/* my comment9 */ + + +/** */ +var a=1; + +function name(params) { + //a + //b + + //c + + /** */ ///aaa + + /** */ /** */ +} + +function name2(params) { + /**123 */ +} + +function name3(params) { + "strict";/**123 *//**/a();b(); +} + +function name4(params) { + "strict"; + + /**123 */ + /**/ + a(); + b(); +} + +a();/** *//**/b();c(); +/** */a();b();c(); +class X { + /*:: a: number*/ + /*:: b: ?string*/ +} +label2: for (const a of [1, 2, 3]) { + break; /*Block comment written + in multiple lines */label2; +} diff --git a/packages/babel-generator/test/fixtures/comments/newlines/output.js b/packages/babel-generator/test/fixtures/comments/newlines/output.js new file mode 100644 index 000000000000..1f8f223b83bb --- /dev/null +++ b/packages/babel-generator/test/fixtures/comments/newlines/output.js @@ -0,0 +1,92 @@ +a; + +// my comment +b; +c; +// my comment + +d; + +/** + * Hello + * @param {*} params + */ +function fn(params) {} + +/** + * Hello + * @param {*} params + */ + +function fn2(params) {} +x; // my comment +x; +x; // my comment + +x; +x; /* */ +x; +x; /* */ + +x; +x; /* my comment1 */ +x; /* my comment2 */ + +x; // my comment3 +x; // my comment4 + +x; // my comment5 + +// my comment6 +// my comment7 + +/* my comment8 */ + +/* my comment9 */ + +/** */ +var a = 1; +function name(params) { + //a + //b + + //c + + /** */ ///aaa + + /** */ /** */ +} +function name2(params) { + /**123 */ +} +function name3(params) { + "strict"; + + /**123 */ /**/ + a(); + b(); +} +function name4(params) { + "strict"; + + /**123 */ + /**/ + a(); + b(); +} +a(); /** */ /**/ +b(); +c(); +/** */ +a(); +b(); +c(); +class X { + /*:: a: number*/ + /*:: b: ?string*/ +} +label2: for (const a of [1, 2, 3]) { + break; /*Block comment written + in multiple lines */ + label2; +} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/object_comments/output.js b/packages/babel-generator/test/fixtures/comments/object_comments/output.js index b87ebb82a99b..1a65285e33c1 100644 --- a/packages/babel-generator/test/fixtures/comments/object_comments/output.js +++ b/packages/babel-generator/test/fixtures/comments/object_comments/output.js @@ -3,7 +3,6 @@ var test = { * Test 2 */ a: "1", - /* * Test 1 */ diff --git a/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-line-comment/output.js index e7be0de1dca2..b21d7d5f5ebf 100644 --- a/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-line-comment/output.js @@ -19,7 +19,10 @@ // 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. -function test() {} // Copyright (C) 2012 Yusuke Suzuki + +function test() {} + +// Copyright (C) 2012 Yusuke Suzuki // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: diff --git a/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-multi-comment/output.js b/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-multi-comment/output.js index eba73f985291..231e7a553e09 100644 --- a/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-multi-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/simple-a-lot-of-multi-comment/output.js @@ -21,7 +21,9 @@ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + function test() {} + /* Copyright (C) 2012 Yusuke Suzuki diff --git a/packages/babel-generator/test/fixtures/comments/simple-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/simple-line-comment/output.js index f9c7d1a9d874..743b2814f4b8 100644 --- a/packages/babel-generator/test/fixtures/comments/simple-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/simple-line-comment/output.js @@ -1,2 +1,3 @@ // Leading -var i = 20; // Trailing \ No newline at end of file +var i = 20; +// Trailing \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/simple-multi-comment/output.js b/packages/babel-generator/test/fixtures/comments/simple-multi-comment/output.js index 0c2c82751766..3fc380a40446 100644 --- a/packages/babel-generator/test/fixtures/comments/simple-multi-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/simple-multi-comment/output.js @@ -8,6 +8,7 @@ function test() { * Leading comment 2 * */ + var i = 20; /* * Trailing comment diff --git a/packages/babel-generator/test/fixtures/comments/try-block-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/try-block-line-comment/output.js index e5a5c95b720e..c9b0601fbe25 100644 --- a/packages/babel-generator/test/fixtures/comments/try-block-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/try-block-line-comment/output.js @@ -1,9 +1,7 @@ try {} // finally {} - try {} catch (e) {} // finally {} - { try {} catch (e) {} // finally {} diff --git a/packages/babel-generator/test/fixtures/comments/variable-declarator-line-comment/output.js b/packages/babel-generator/test/fixtures/comments/variable-declarator-line-comment/output.js index 3f7a0ccffa55..add1fe35497b 100644 --- a/packages/babel-generator/test/fixtures/comments/variable-declarator-line-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/variable-declarator-line-comment/output.js @@ -1,8 +1,9 @@ function test() { - var // Leading to VariableDeclarator - // Leading to VariableDeclarator - i = 20, - // Leading to VariableDeclarator - // Leading to VariableDeclarator - j = 20; + var + // Leading to VariableDeclarator + // Leading to VariableDeclarator + i = 20, + // Leading to VariableDeclarator + // Leading to VariableDeclarator + j = 20; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/variable-declarator-multi-comment/output.js b/packages/babel-generator/test/fixtures/comments/variable-declarator-multi-comment/output.js index 6fd160503b8a..9df5de692288 100644 --- a/packages/babel-generator/test/fixtures/comments/variable-declarator-multi-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/variable-declarator-multi-comment/output.js @@ -1,14 +1,13 @@ function test() { var - /* - * Leading to VariableDeclarator - * Leading to VariableDeclarator - */ - i = 20, - - /* - * Leading to VariableDeclarator - * Leading to VariableDeclarator - */ - j = 20; + /* + * Leading to VariableDeclarator + * Leading to VariableDeclarator + */ + i = 20, + /* + * Leading to VariableDeclarator + * Leading to VariableDeclarator + */ + j = 20; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/comments/variable-declarator-trailing-comment/output.js b/packages/babel-generator/test/fixtures/comments/variable-declarator-trailing-comment/output.js index b4884e775742..9347d91a23d5 100644 --- a/packages/babel-generator/test/fixtures/comments/variable-declarator-trailing-comment/output.js +++ b/packages/babel-generator/test/fixtures/comments/variable-declarator-trailing-comment/output.js @@ -1,20 +1,19 @@ { - var t = 20; - /* - * This is trailing comment - */ + var t = 20; /* + * This is trailing comment + */ } + { - var tt = 20; - /* - * This is trailing comment - */ + var tt = 20; /* + * This is trailing comment + */ } + { { - var t = 20; - /* - * This is trailing comment - */ + var t = 20; /* + * This is trailing comment + */ } } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/decorators/accessor-with-retainlines/output.js b/packages/babel-generator/test/fixtures/decorators/accessor-with-retainlines/output.js index 95f37461cd8d..c97fe830da73 100644 --- a/packages/babel-generator/test/fixtures/decorators/accessor-with-retainlines/output.js +++ b/packages/babel-generator/test/fixtures/decorators/accessor-with-retainlines/output.js @@ -1,8 +1,6 @@ class C { @dec get a() {} - @dec set a(v) {} - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/decorators/async-method-with-retainlines/output.js b/packages/babel-generator/test/fixtures/decorators/async-method-with-retainlines/output.js index e6bc0b905ee6..7bed5cb999fd 100644 --- a/packages/babel-generator/test/fixtures/decorators/async-method-with-retainlines/output.js +++ b/packages/babel-generator/test/fixtures/decorators/async-method-with-retainlines/output.js @@ -1,8 +1,6 @@ class C { @dec async a() {} - @dec async *a(v) {} - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression-createParenthesizedExpression/output.js b/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression-createParenthesizedExpression/output.js index 05b8e9379125..52904724295a 100644 --- a/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression-createParenthesizedExpression/output.js +++ b/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression-createParenthesizedExpression/output.js @@ -1,6 +1,5 @@ class C extends class {} { #x; - constructor() { class ShouldPreserveParens { @(decs[0]) @@ -12,19 +11,16 @@ class C extends class {} { @(new DecFactory()) p; } - class ShouldNotAddParens { @decs @decs.one @decs.two() p; } - class ShouldAddParens { @((decs[three])()) p; } - class WillPreserveParens { @(decs) @(decs.one) @@ -32,5 +28,4 @@ class C extends class {} { p; } } - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression/output.js b/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression/output.js index 2c2780aee874..dc7cb80ec211 100644 --- a/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression/output.js +++ b/packages/babel-generator/test/fixtures/decorators/decorator-parenthesized-expression/output.js @@ -1,6 +1,5 @@ class C extends class {} { #x; - constructor() { class ShouldPreserveParens { @(decs[0]) @@ -12,19 +11,16 @@ class C extends class {} { @(new DecFactory()) p; } - class ShouldNotAddParens { @decs @decs.one @decs.two() p; } - class ShouldAddParens { @(decs[three]()) p; } - class ShouldRemoveParens { @decs @decs.one @@ -32,5 +28,4 @@ class C extends class {} { p; } } - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/async-generator/output.js b/packages/babel-generator/test/fixtures/edgecase/async-generator/output.js index f66336927cc1..79b8075b7210 100644 --- a/packages/babel-generator/test/fixtures/edgecase/async-generator/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/async-generator/output.js @@ -1,30 +1,18 @@ function a() {} - function* b() {} - async function c() {} - async function* d() {} - var e = function () {}; - var f = function* () {}; - var g = async function () {}; - var h = async function* () {}; - class A { a() {} - *b() {} - async c() {} - async *d() {} - - e = () => {}; // f = () =>* {}; - - g = async () => {}; // h = async () =>* {}; - + e = () => {}; + // f = () =>* {}; + g = async () => {}; + // h = async () =>* {}; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/for-async-of/output.js b/packages/babel-generator/test/fixtures/edgecase/for-async-of/output.js index 99c5ce9e1754..2aa0146d8caa 100644 --- a/packages/babel-generator/test/fixtures/edgecase/for-async-of/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/for-async-of/output.js @@ -1,9 +1,5 @@ for ((async) of []); - for ((async) of async) async; - for ((async) of []); - for (async.x of []); - for (async in []); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/for-await-async-of/output.js b/packages/babel-generator/test/fixtures/edgecase/for-await-async-of/output.js index 10a77c0134fb..a847a2361999 100644 --- a/packages/babel-generator/test/fixtures/edgecase/for-await-async-of/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/for-await-async-of/output.js @@ -1,11 +1,7 @@ async function f() { for await ((async) of []); - for await ((async) of async) async; - for await ((async) of []); - for await (async.x of []); - for await ((async) of []); } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/for-in-no-in/output.js b/packages/babel-generator/test/fixtures/edgecase/for-in-no-in/output.js index feda9f2353a7..d55e687667af 100644 --- a/packages/babel-generator/test/fixtures/edgecase/for-in-no-in/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/for-in-no-in/output.js @@ -5,13 +5,8 @@ //for (var i = 10 + (10 in []) in []); //for (var i = 10 + 10 in [] in []); for (var i = (1 in []);;); - for ((1 in []);;); - for (1 * (1 in []);;); - for (1 * (1 + 1 in []);;); - for (1 * (1 + 1 in []);;); - for (1 * (1 + (1 in []));;); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/for-loop-in/output.js b/packages/babel-generator/test/fixtures/edgecase/for-loop-in/output.js index 47ac98285a55..87f44f9c1cbe 100644 --- a/packages/babel-generator/test/fixtures/edgecase/for-loop-in/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/for-loop-in/output.js @@ -1,5 +1,4 @@ for ((a in b) ? a : b; i;); - for (function () { for (;;); } && (a in b);;); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/edgecase/let-identifier/output.js b/packages/babel-generator/test/fixtures/edgecase/let-identifier/output.js index 62d41eff3059..49bcd41ff24a 100644 --- a/packages/babel-generator/test/fixtures/edgecase/let-identifier/output.js +++ b/packages/babel-generator/test/fixtures/edgecase/let-identifier/output.js @@ -3,44 +3,29 @@ let; (let)[x]; (let)[x]; a[let[x]]; -/* ForStatement */ +/* ForStatement */ for (let;;); - for ((let)[x];;); - for ((let)[x];;); - for (a[let[x]];;); -/* ForInStatement */ - +/* ForInStatement */ for (let in {}); - for ((let)[x] in {}); - for ((let)[x] in {}); - for (a[let[x]] in {}); -/* ForOfStatement { await: false } */ - +/* ForOfStatement { await: false } */ for ((let) of []); - for ((let) of []); - for ((let)[x] of []); - for (a[let] of []); -/* ForOfStatement { await: true } */ - +/* ForOfStatement { await: true } */ async () => { for await ((let) of []); - for await ((let) of []); - for await ((let)[x] of []); - for await (a[let] of []); }; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/arrow-functions/output.js b/packages/babel-generator/test/fixtures/flow/arrow-functions/output.js index d132971e4bcf..8f32e99220cc 100644 --- a/packages/babel-generator/test/fixtures/flow/arrow-functions/output.js +++ b/packages/babel-generator/test/fixtures/flow/arrow-functions/output.js @@ -1,15 +1,8 @@ const bar1 = (x: number): string => {}; - const bar2 = (x?) => {}; - const bar3 = (x?: string) => {}; - const bar4 = x => {}; - const bar5 = (x): string => {}; - const bar6 = (x: number) => {}; - const bar7 = (x) => {}; - -const bar8 = (x: T): ((T) => T[]) => y => [x, y]; +const bar8 = (x: T): ((T) => T[]) => y => [x, y]; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/def-site-variance/output.js b/packages/babel-generator/test/fixtures/flow/def-site-variance/output.js index 66dd195d22e1..fa2d8128b237 100644 --- a/packages/babel-generator/test/fixtures/flow/def-site-variance/output.js +++ b/packages/babel-generator/test/fixtures/flow/def-site-variance/output.js @@ -1,7 +1,5 @@ class C1<+T, -U> {} - function f<+T, -U>() {} - type T<+T, -U> = {}; type T2 = { +p: T @@ -39,11 +37,9 @@ declare class I { declare class I { -[k: K]: V } - class C2 { +p: T = e; } - class C3 { -p: T = e; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/implements/output.js b/packages/babel-generator/test/fixtures/flow/implements/output.js index b1bd305e650a..94881cde4c40 100644 --- a/packages/babel-generator/test/fixtures/flow/implements/output.js +++ b/packages/babel-generator/test/fixtures/flow/implements/output.js @@ -1,7 +1,5 @@ class A1 implements B {} - class A2 implements B, C {} - declare class A3 implements B {} declare class A4 mixins B implements C {} declare class A5 implements B, C {} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/interfaces-module-and-script/output.js b/packages/babel-generator/test/fixtures/flow/interfaces-module-and-script/output.js index ef7fce8a5087..12928227cae8 100644 --- a/packages/babel-generator/test/fixtures/flow/interfaces-module-and-script/output.js +++ b/packages/babel-generator/test/fixtures/flow/interfaces-module-and-script/output.js @@ -8,11 +8,7 @@ interface Dictionary { length: number, [index: string]: string, } - class Foo1 implements Bar {} - class Foo2 extends Bar implements Bat, Man {} - class Foo3 extends class Bar implements Bat {} {} - class Foo4 extends class Bar implements Bat {} implements Man {} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/object-literal-types/output.js b/packages/babel-generator/test/fixtures/flow/object-literal-types/output.js index 2a3769b1abd5..1f14e27f3246 100644 --- a/packages/babel-generator/test/fixtures/flow/object-literal-types/output.js +++ b/packages/babel-generator/test/fixtures/flow/object-literal-types/output.js @@ -1,18 +1,22 @@ type U = {}; type V = {}; -type T1 = { ...U +type T1 = { + ...U }; -type T2 = { ...U, +type T2 = { + ...U, ...V, }; type T3 = { p: V, ...U, }; -type T4 = { ...U, +type T4 = { + ...U, p: V, }; -type T5 = { ...{} | { +type T5 = { + ...{} | { p: V } }; @@ -46,4 +50,4 @@ type T13 = { foo: number, bar: string, ... -}; +}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/predicates/output.js b/packages/babel-generator/test/fixtures/flow/predicates/output.js index f78e494bce29..f264f57a24c7 100644 --- a/packages/babel-generator/test/fixtures/flow/predicates/output.js +++ b/packages/babel-generator/test/fixtures/flow/predicates/output.js @@ -1,17 +1,12 @@ declare function foo(x: mixed): boolean %checks(x !== null); declare function my_filter>(v: Array, cb: P): Array<$Refine>; declare function f2(x: mixed): string %checks(Array.isArray(x)); - function foo(x: mixed): %checks { return typeof x === "string"; } - function is_string(x): boolean %checks { return typeof x === "string"; } - var f = (x: mixed): %checks => typeof x === "string"; - const foo2 = (x: mixed): boolean %checks => typeof x === "string"; - (x): %checks => x !== null; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/string-literal-types/output.js b/packages/babel-generator/test/fixtures/flow/string-literal-types/output.js index 523469a5c34f..4dcbc6108e8d 100644 --- a/packages/babel-generator/test/fixtures/flow/string-literal-types/output.js +++ b/packages/babel-generator/test/fixtures/flow/string-literal-types/output.js @@ -1,3 +1,2 @@ function createElement1(tagName: "div"): HTMLDivElement {} - function createElement2(tagName: 'div'): HTMLDivElement {} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/this-param/output.js b/packages/babel-generator/test/fixtures/flow/this-param/output.js index 6f10af88264b..52c782a7e189 100644 --- a/packages/babel-generator/test/fixtures/flow/this-param/output.js +++ b/packages/babel-generator/test/fixtures/flow/this-param/output.js @@ -1,13 +1,8 @@ function one(this: number) {} - function two(this: number, a) {} - function three(this: number, ...a) {} - function four(this: number, a, b, ...c) {} - function five(this: T) {} - type six = (this: number) => void; type seven = (this: number, a: number) => void; type eight = (this: number, ...a: any) => void; @@ -28,29 +23,17 @@ declare class Fifteen { m3(this: string, ...a: any): void, m4(this: T): void, } - class Sixteen { m1(this: number) {} - m2(this: number, a) {} - m3(this: number, ...a) {} - m4(this: number, a, b, ...c) {} - m5(this: T) {} - } - let seventeen = { m1(this: number) {}, - m2(this: number, a) {}, - m3(this: number, ...a) {}, - m4(this: number, a, b, ...c) {}, - m5(this: T) {} - }; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/this-types/output.js b/packages/babel-generator/test/fixtures/flow/this-types/output.js index e9f5c2c53988..ea79331c848f 100644 --- a/packages/babel-generator/test/fixtures/flow/this-types/output.js +++ b/packages/babel-generator/test/fixtures/flow/this-types/output.js @@ -2,5 +2,4 @@ class Foo { bar(): this { return this; } - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/type-annotations/output.js b/packages/babel-generator/test/fixtures/flow/type-annotations/output.js index 71548b99c5ab..a2fd9d08b5d9 100644 --- a/packages/babel-generator/test/fixtures/flow/type-annotations/output.js +++ b/packages/babel-generator/test/fixtures/flow/type-annotations/output.js @@ -1,87 +1,53 @@ function foo1(numVal: any) {} - function foo2(numVal: number) {} - function foo3(numVal: number, strVal: string) {} - function foo4(numVal: number, untypedVal) {} - function foo5(untypedVal, numVal: number) {} - function foo6(nullableNum: ?number) {} - function foo7(callback: () => void) {} - function foo8(callback: () => number) {} - function foo9(callback: (_: boolean) => number) {} - function foo10(callback: (_1: boolean, _2: string) => number) {} - function foo11(callback: (_1: boolean, ...foo: Array) => number) {} - function foo12(): number {} - function foo13(): () => void {} - function foo14(): (_: boolean) => number {} - function foo15(): (_?: boolean) => number {} - function foo16(): {} {} - function foo17() {} - function foo18() {} - function foo19() {} - a1 = function () {}; - a2 = { set fooProp(value: number) {} - }; a3 = { set fooProp(value: number): void {} - }; a4 = { get fooProp(): number {} - }; a5 = { id(x: T): T {} - }; a6 = { *id(x: T): T {} - }; a7 = { async id(x: T): T {} - }; a8 = { 123(x: T): T {} - }; - class Foo1 { set fooProp(value: number) {} - } - class Foo2 { set fooProp(value: number): void {} - } - class Foo3 { get fooProp(): number {} - } - var numVal1: number; var numVal2: empty; var numVal3: mixed; @@ -137,49 +103,34 @@ var a13: { var a14: Array = [1, 2, 3]; a13 = class Foo {}; a14 = class Foo extends Bar {}; - class Foo4 {} - class Foo5 extends Bar {} - class Foo6 extends mixin(Bar) {} - class Foo7 { bar(): number { return 42; } - } - class Foo8 { "bar"() {} - } - function foo20(requiredParam, optParam?) {} - class Foo9 { prop1: string; prop2: number; } - class Foo10 { static prop1: string; prop2: number; } - class Foo11 { #prop1: string; prop2: number; } - var x1: number | string = 4; - class Array { concat(items: number | string) {} - } - var x2: () => number | (() => string) = fn; var x3: typeof Y = Y; var x4: typeof Y | number = Y; @@ -198,21 +149,15 @@ var { x6: "hello" }; var [x7]: Array = ["hello"]; - function foo21({ x }: { x: string }) {} - function foo22([x]: Array) {} - function foo23(...rest: Array) {} - (function (...rest: Array) {}); - (...rest: Array) => rest; - var a15: Map>; var a16: Map>; var a17: number[]; @@ -288,10 +233,7 @@ var a33: {| var a34: {| id(x: T): T |}; - function foo27(numVal: number = 2) {} - function foo28(numVal?: number = 2) {} - export type * from "foo"; const foo29: symbol = Symbol(); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/flow/type-parameters/output.js b/packages/babel-generator/test/fixtures/flow/type-parameters/output.js index 768f82b1feaf..7b35c2f7f5c9 100644 --- a/packages/babel-generator/test/fixtures/flow/type-parameters/output.js +++ b/packages/babel-generator/test/fixtures/flow/type-parameters/output.js @@ -3,23 +3,14 @@ type A2 = T; type A3 = T; type A4 = T; type A5 = T; - class A6 {} - class A7 {} - class A8 {} - class A9 {} - (class A10 {}); - (class A11 {}); - (class A12 {}); - (class A13 {}); - declare class A14 {} declare class A15 {} declare class A16 {} diff --git a/packages/babel-generator/test/fixtures/flow/typeapp-call/output.js b/packages/babel-generator/test/fixtures/flow/typeapp-call/output.js index 6db174c9ad20..d1ab1f56efc8 100644 --- a/packages/babel-generator/test/fixtures/flow/typeapp-call/output.js +++ b/packages/babel-generator/test/fixtures/flow/typeapp-call/output.js @@ -5,11 +5,8 @@ new C(); f(e); o[e](); f(x)(y); - async () => {}; - async (): T => {}; - new C(e); f < T > [e]; new C(); diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/arrow-function/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/arrow-function/output.js index f9712059e262..3b7a28fbd9ca 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/arrow-function/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/arrow-function/output.js @@ -1,15 +1,10 @@ e => { print("hello world"); }; - (e1, e2, e3) => { print("hello world"); }; - e => e; - (e1, e2, e3) => e; - e => {}; - e => 20 + 20; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/class-declaration/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/class-declaration/output.js index d7707cf2d87c..ca8a15c58ef6 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/class-declaration/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/class-declaration/output.js @@ -1,47 +1,26 @@ class Test {} - class Derived extends Super {} - class StaticMethods { static n1() {} - static get get1() {} - static set set1(value) {} - static *gen1() {} - } - class Methods { n2() {} - get get2() {} - set set2(value) {} - *gen1() {} - } - class ComputedStaticMethods { static [n1]() {} - static get [get1]() {} - static set [set1](value) {} - static *[gen1]() {} - } - class ComputedMethods { [n2]() {} - get [get2]() {} - set [set2](value) {} - *[gen1]() {} - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/class-expression/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/class-expression/output.js index 0424ccf67f20..0eb9f5002948 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/class-expression/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/class-expression/output.js @@ -1,49 +1,27 @@ (class Test {}); - (class Derived extends Super {}); - (class StaticMethods { static n1() {} - static get get1() {} - static set set1(value) {} - static *gen1() {} - }); - (class Methods { n2() {} - get get2() {} - set set2(value) {} - *gen1() {} - }); - (class ComputedStaticMethods { static [n1]() {} - static get [get1]() {} - static set [set1](value) {} - static *[gen1]() {} - }); - (class ComputedMethods { [n2]() {} - get [get2]() {} - set [set2](value) {} - *[gen1]() {} - }); - (class {}); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/computed-property/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/computed-property/output.js index 7411f526f3e5..a1f475dbc8ce 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/computed-property/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/computed-property/output.js @@ -1,16 +1,12 @@ var object1 = { get [Symbol.create]() {}, - set [set()](value) {} - }; var object2 = { *[generator()]() {} - }; var object3 = { *[generator()]() {} - }; var object4 = { [Symbol.xxx]: "hello", diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/default-parameter/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/default-parameter/output.js index 4df711115488..20e3a212dbf6 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/default-parameter/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/default-parameter/output.js @@ -1,9 +1,5 @@ function a(p = 20) {} - function b(p, q = 30) {} - function c(p, q = 30, ...r) {} - (p = 20) => {}; - (p = 20, ...q) => {}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/destructuring-assignment/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/destructuring-assignment/output.js index 65da4d30e45d..c2332832d82d 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/destructuring-assignment/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/destructuring-assignment/output.js @@ -1,13 +1,10 @@ function t1({ responseText: responseText }) {} - function t2({ responseText }) {} - function t3([a, b]) {} - var [i1, j1, k1] = array; var { i2, diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/for-of-statement/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/for-of-statement/output.js index 2e6a54af6867..0afd2b2e6fb0 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/for-of-statement/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/for-of-statement/output.js @@ -1,5 +1,4 @@ function test() { for (var i of array) {} - for (let i of array) {} } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/import-with-break/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/import-with-break/output.js index 69b3df1e5492..781134650c14 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/import-with-break/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/import-with-break/output.js @@ -1,5 +1,4 @@ import foo from "foo"; - foo: { break foo; -} +} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/spread-element/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/spread-element/output.js index 070fa55a1f3d..9bcaf362f39c 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/spread-element/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/spread-element/output.js @@ -1,6 +1,4 @@ var [a1, b1, ...rest1] = array; const [a2, b2, ...rest2] = array; - function a([a1, b1, ...rest1]) {} - ([a1, b1, ...rest1]) => {}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/templates-indentation/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/templates-indentation/output.js index 070c6ca4e0ce..b36d173bcb83 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/templates-indentation/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/templates-indentation/output.js @@ -3,7 +3,6 @@ function multilineTemplate() { ${'the energy motron'} ${'...or whatever'}`; } - { const foo = `spam and eggs!`; diff --git a/packages/babel-generator/test/fixtures/harmony-edgecase/yield-precedence/output.js b/packages/babel-generator/test/fixtures/harmony-edgecase/yield-precedence/output.js index ef5eff9ebc11..68ab52b6da9a 100644 --- a/packages/babel-generator/test/fixtures/harmony-edgecase/yield-precedence/output.js +++ b/packages/babel-generator/test/fixtures/harmony-edgecase/yield-precedence/output.js @@ -1,6 +1,6 @@ function* foo() { var a = yield wat(), - b = 2; + b = 2; var c = yield a = b; yield a, yield b; yield a = b; diff --git a/packages/babel-generator/test/fixtures/jsx/comments/output.js b/packages/babel-generator/test/fixtures/jsx/comments/output.js index 96506461ea34..b5b99cd551fc 100644 --- a/packages/babel-generator/test/fixtures/jsx/comments/output.js +++ b/packages/babel-generator/test/fixtures/jsx/comments/output.js @@ -3,15 +3,11 @@ class Demo extends React.Component { super(props); this.state = {}; } - render() { return
- { - /*
I am a jsx comment!!
*/ - } + {/*
I am a jsx comment!!
*/}
; } - } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/misc/placeholders/output.js b/packages/babel-generator/test/fixtures/misc/placeholders/output.js index 82ad54ecc61e..9c605cb0ceb3 100644 --- a/packages/babel-generator/test/fixtures/misc/placeholders/output.js +++ b/packages/babel-generator/test/fixtures/misc/placeholders/output.js @@ -1,8 +1,5 @@ var %%a%% = %%b%%; %%c%%; - class %%d%% {} - class A %%e%% - function %%f%%(...%%g%%) %%h%% \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/output.js b/packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/output.js index 2a969b86aa00..f23c0d00ace2 100644 --- a/packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/output.js @@ -2,11 +2,8 @@ var foo = arr.map(v => ({ x: v.bar, y: v.bar * 2 })); - var fn = () => ({}).key; - var fn2 = () => ({}); - var fn3 = () => ({ a } = {}); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/async-arrow-function/output.js b/packages/babel-generator/test/fixtures/parentheses/async-arrow-function/output.js index 9dd55c5ad596..bf33d2ca48fc 100644 --- a/packages/babel-generator/test/fixtures/parentheses/async-arrow-function/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/async-arrow-function/output.js @@ -1,8 +1,8 @@ -const x = async ( // some comment +const x = async ( +// some comment a) => { return foo(await a); }; - function foo(a) { return a; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/await-expression/output.js b/packages/babel-generator/test/fixtures/parentheses/await-expression/output.js index e864e993947d..82ed647a34a7 100644 --- a/packages/babel-generator/test/fixtures/parentheses/await-expression/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/await-expression/output.js @@ -8,7 +8,6 @@ async function foo() { await await 1; await (a || b); } - async function a(b) { (await xhr({ url: "views/test.html" diff --git a/packages/babel-generator/test/fixtures/parentheses/break-statement/output.js b/packages/babel-generator/test/fixtures/parentheses/break-statement/output.js index feb3df1d70c7..9a4d69150761 100644 --- a/packages/babel-generator/test/fixtures/parentheses/break-statement/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/break-statement/output.js @@ -1,17 +1,12 @@ label1: for (const a of [1, 2, 3]) { break /*Block comment written in single line */label1; } - label2: for (const a of [1, 2, 3]) { - break; - /*Block comment written - in multiple lines */ - + break; /*Block comment written + in multiple lines */ label2; } - label2: for (const a of [1, 2, 3]) { break; //foo - label2; } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/class-extends/output.js b/packages/babel-generator/test/fixtures/parentheses/class-extends/output.js index 11b2ee978828..6af6ca993187 100644 --- a/packages/babel-generator/test/fixtures/parentheses/class-extends/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/class-extends/output.js @@ -1,35 +1,20 @@ class A1 extends (() => {}) {} - class A2 extends (B = C) {} - class A3 extends (B || C) {} - class A4 extends (B + C) {} - class A5 extends B() {} - class A6 extends class {} {} - class A7 extends (B ? C : D) {} - class A8 extends new B() {} - class A9 extends (B, C) {} - class A10 extends {} {} - class A11 extends B.C {} - class A12 extends function () {} {} - class A13 extends (void B) {} - class A14 extends (++B) {} - async function f1() { class A15 extends (await C) {} } - function* f2() { class A16 extends (yield 1) {} -} +} \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/identifier-lhs/output.js b/packages/babel-generator/test/fixtures/parentheses/identifier-lhs/output.js index 164de06f999a..5673f394e9a8 100644 --- a/packages/babel-generator/test/fixtures/parentheses/identifier-lhs/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/identifier-lhs/output.js @@ -1,13 +1,7 @@ var f, g, h; - (f) = function () {}; - (f) = class {}; - g = function () {}; - g = class {}; - h = function noParen() {}; - h = class noParen {}; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/sequence-expressions/output.js b/packages/babel-generator/test/fixtures/parentheses/sequence-expressions/output.js index fb44cc02d81b..4d1b68487ec4 100644 --- a/packages/babel-generator/test/fixtures/parentheses/sequence-expressions/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/sequence-expressions/output.js @@ -1,14 +1,9 @@ function foo() { return a, b; } - if (a, b, c) d(); throw a, b, c; - switch (a, b, c) {} - for (a in b, c); - while (a, b, c); - !function () {}(), a(); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/tagged-template-expression/output.js b/packages/babel-generator/test/fixtures/parentheses/tagged-template-expression/output.js index bc4371fbdf61..a406da8acc7a 100644 --- a/packages/babel-generator/test/fixtures/parentheses/tagged-template-expression/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/tagged-template-expression/output.js @@ -1,7 +1,6 @@ (() => {})``; (function () {})``; (a ? b : c)``; - function* fn() { (yield)`foo`; (yield f)`foo`; diff --git a/packages/babel-generator/test/fixtures/parentheses/terminator-break/output.js b/packages/babel-generator/test/fixtures/parentheses/terminator-break/output.js index 7ec6459a0d85..ecf5bf6338fc 100644 --- a/packages/babel-generator/test/fixtures/parentheses/terminator-break/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/terminator-break/output.js @@ -1,11 +1,12 @@ function foo1() { - return (// foobar + return ( + // foobar "bar" ); } - function foo2() { - return (// foobar + return ( + // foobar "bar" ); } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/parentheses/yield-expression/output.js b/packages/babel-generator/test/fixtures/parentheses/yield-expression/output.js index fbf1bce8e507..f6821d12e13f 100644 --- a/packages/babel-generator/test/fixtures/parentheses/yield-expression/output.js +++ b/packages/babel-generator/test/fixtures/parentheses/yield-expression/output.js @@ -7,14 +7,12 @@ function* foo() { yield 1 ? 2 : 3; yield yield 1; } - function* a(b) { (yield xhr({ url: "views/test.html" })).data; (yield replay())?.data; } - (async function* () { await (yield 1); }); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/regression/comment-before-parentheses-return-arg/output.js b/packages/babel-generator/test/fixtures/regression/comment-before-parentheses-return-arg/output.js index 24a35efbd7b6..c209aa70959c 100644 --- a/packages/babel-generator/test/fixtures/regression/comment-before-parentheses-return-arg/output.js +++ b/packages/babel-generator/test/fixtures/regression/comment-before-parentheses-return-arg/output.js @@ -1,13 +1,7 @@ function assertElement(assertFn, shouldBeElement, opt_message) { - return ( - /** @type {!Ele ment} */ + return (/** @type {!Ele ment} */ assertType_(assertFn, shouldBeElement, isElement(shouldBeElement), 'Element expected', opt_message) ); } - -const slot = -/** @type {!HTMLSlotElement} */ -e.target; -assertElement( -/** @type {Element} */ -el); \ No newline at end of file +const slot = /** @type {!HTMLSlotElement} */e.target; +assertElement( /** @type {Element} */el); \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/regression/comments-with-_noLineTerminator/output.js b/packages/babel-generator/test/fixtures/regression/comments-with-_noLineTerminator/output.js index 8a370e8fae05..93606e9ec252 100644 --- a/packages/babel-generator/test/fixtures/regression/comments-with-_noLineTerminator/output.js +++ b/packages/babel-generator/test/fixtures/regression/comments-with-_noLineTerminator/output.js @@ -6,5 +6,4 @@ const test = (): { foo: "bar" }; }; - export default test; \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/output.js b/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/output.js index 8ce10b0ba345..4761f0f97a2c 100644 --- a/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/output.js +++ b/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/output.js @@ -1,13 +1,11 @@ class Foo { static {} } - class A1 { static { foo; } } - class A2 { static { foo; diff --git a/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/source-map.json b/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/source-map.json index c5131632aeed..eea76718e703 100644 --- a/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/source-map.json +++ b/packages/babel-generator/test/fixtures/sourcemaps/ClassBody-StaticBlock/source-map.json @@ -13,5 +13,5 @@ "sourcesContent": [ "class Foo {\n static {}\n}\n\nclass A1 {\n static{\n foo;\n }\n}\n\nclass A2 {\n static {\n foo;bar;\n }\n}" ], - "mappings": "AAAA,MAAMA,GAAG,CAAC;EACR;AACF;;AAEA,MAAMC,EAAE,CAAC;EACP;IACEC,GAAG;EACL;AACF;;AAEA,MAAMC,EAAE,CAAC;EACP;IACED,GAAG;IAACE,GAAG;EACT;AACF" + "mappings": "AAAA,MAAMA,GAAG,CAAC;EACR;AACF;AAEA,MAAMC,EAAE,CAAC;EACP;IACEC,GAAG;EACL;AACF;AAEA,MAAMC,EAAE,CAAC;EACP;IACED,GAAG;IAACE,GAAG;EACT;AACF" } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/output.js b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/output.js index 9fdbf2c3f072..068e07af5029 100644 --- a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/output.js +++ b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/output.js @@ -1,4 +1,5 @@ // From packages\babel-cli\src\babel\watcher.ts + import { createRequire } from "module"; import path from "path"; import type { WatchOptions, FSWatcher } from "chokidar"; @@ -31,11 +32,9 @@ export function enable({ } export function startWatcher() { hasStarted = true; - for (const dep of watchQueue) { watcher.add(dep); } - watchQueue.clear(); watcher.on("ready", () => { console.log("The watcher is ready."); @@ -45,13 +44,13 @@ export function watch(filename: string): void { if (!isWatchMode) { throw new Error("Internal Babel error: .watch called when not in watch mode."); } - if (!hasStarted) { watchQueue.add(path.resolve(filename)); } else { watcher.add(path.resolve(filename)); } } + /** * Call @param callback whenever a dependency (source file)/ * external dependency (non-source file) changes. @@ -59,12 +58,10 @@ export function watch(filename: string): void { * Handles mapping external dependencies to their corresponding * dependencies. */ - export function onFilesChange(callback: (filenames: string[], event: string, cause: string) => void): void { if (!isWatchMode) { throw new Error("Internal Babel error: .onFilesChange called when not in watch mode."); } - watcher.on("all", (event, filename) => { if (event !== "change" && event !== "add") return; const absoluteFile = path.resolve(filename); @@ -72,12 +69,12 @@ export function onFilesChange(callback: (filenames: string[], event: string, cau }); } export function updateExternalDependencies(filename: string, dependencies: Set) { - if (!isWatchMode) return; // Use absolute paths + if (!isWatchMode) return; + // Use absolute paths const absFilename = path.resolve(filename); const absDependencies = new Set(Array.from(dependencies, dep => path.resolve(dep))); const deps = fileToDeps.get(absFilename); - if (deps) { for (const dep of deps) { if (!absDependencies.has(dep)) { @@ -85,33 +82,25 @@ export function updateExternalDependencies(filename: string, dependencies: Set); deps.delete(filename); - if (deps.size === 0) { depToFiles.delete(dep); - if (!hasStarted) { watchQueue.delete(dep); } else { @@ -119,21 +108,16 @@ function removeFileDependency(filename: string, dep: string) { } } } - function unwatchFile(filename: string) { const deps = fileToDeps.get(filename); if (!deps) return; - for (const dep of deps) { removeFileDependency(filename, dep); } - fileToDeps.delete(filename); } - function requireChokidar(): any { const require = createRequire(import.meta.url); - try { return process.env.BABEL_8_BREAKING ? require("chokidar") : parseInt(process.versions.node) >= 8 ? require("chokidar") : require("@nicolo-ribaudo/chokidar-2"); } catch (err) { diff --git a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/source-map.json b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/source-map.json index 541ebd4329e8..7b69685247d6 100644 --- a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/source-map.json +++ b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file1/source-map.json @@ -74,5 +74,5 @@ "sourcesContent": [ "// From packages\\babel-cli\\src\\babel\\watcher.ts\n\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport type { WatchOptions, FSWatcher } from \"chokidar\";\n\nconst fileToDeps = new Map>();\nconst depToFiles = new Map>();\n\nlet isWatchMode = false;\nlet watcher: FSWatcher;\nconst watchQueue = new Set();\nlet hasStarted = false;\n\nexport function enable({ enableGlobbing }: { enableGlobbing: boolean }) {\n isWatchMode = true;\n\n const { FSWatcher } = requireChokidar();\n\n const options: WatchOptions = {\n disableGlobbing: !enableGlobbing,\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 50,\n pollInterval: 10,\n },\n };\n watcher = new FSWatcher(options);\n\n watcher.on(\"unlink\", unwatchFile);\n}\n\nexport function startWatcher() {\n hasStarted = true;\n\n for (const dep of watchQueue) {\n watcher.add(dep);\n }\n watchQueue.clear();\n\n watcher.on(\"ready\", () => {\n console.log(\"The watcher is ready.\");\n });\n}\n\nexport function watch(filename: string): void {\n if (!isWatchMode) {\n throw new Error(\n \"Internal Babel error: .watch called when not in watch mode.\",\n );\n }\n\n if (!hasStarted) {\n watchQueue.add(path.resolve(filename));\n } else {\n watcher.add(path.resolve(filename));\n }\n}\n\n/**\n * Call @param callback whenever a dependency (source file)/\n * external dependency (non-source file) changes.\n *\n * Handles mapping external dependencies to their corresponding\n * dependencies.\n */\nexport function onFilesChange(\n callback: (filenames: string[], event: string, cause: string) => void,\n): void {\n if (!isWatchMode) {\n throw new Error(\n \"Internal Babel error: .onFilesChange called when not in watch mode.\",\n );\n }\n\n watcher.on(\"all\", (event, filename) => {\n if (event !== \"change\" && event !== \"add\") return;\n\n const absoluteFile = path.resolve(filename);\n callback(\n [absoluteFile, ...(depToFiles.get(absoluteFile) ?? [])],\n event,\n absoluteFile,\n );\n });\n}\n\nexport function updateExternalDependencies(\n filename: string,\n dependencies: Set,\n) {\n if (!isWatchMode) return;\n\n // Use absolute paths\n const absFilename = path.resolve(filename);\n const absDependencies = new Set(\n Array.from(dependencies, dep => path.resolve(dep)),\n );\n\n const deps = fileToDeps.get(absFilename);\n if (deps) {\n for (const dep of deps) {\n if (!absDependencies.has(dep)) {\n removeFileDependency(absFilename, dep);\n }\n }\n }\n for (const dep of absDependencies) {\n let deps = depToFiles.get(dep);\n if (!deps) {\n depToFiles.set(dep, (deps = new Set()));\n\n if (!hasStarted) {\n watchQueue.add(dep);\n } else {\n watcher.add(dep);\n }\n }\n\n deps.add(absFilename);\n }\n\n fileToDeps.set(absFilename, absDependencies);\n}\n\nfunction removeFileDependency(filename: string, dep: string) {\n const deps = depToFiles.get(dep) as Set;\n deps.delete(filename);\n\n if (deps.size === 0) {\n depToFiles.delete(dep);\n\n if (!hasStarted) {\n watchQueue.delete(dep);\n } else {\n watcher.unwatch(dep);\n }\n }\n}\n\nfunction unwatchFile(filename: string) {\n const deps = fileToDeps.get(filename);\n if (!deps) return;\n\n for (const dep of deps) {\n removeFileDependency(filename, dep);\n }\n fileToDeps.delete(filename);\n}\n\nfunction requireChokidar(): any {\n const require = createRequire(import.meta.url);\n\n try {\n return process.env.BABEL_8_BREAKING\n ? require(\"chokidar\")\n : parseInt(process.versions.node) >= 8\n ? require(\"chokidar\")\n : require(\"@nicolo-ribaudo/chokidar-2\");\n } catch (err) {\n console.error(\n \"The optional dependency chokidar failed to install and is required for \" +\n \"--watch. Chokidar is likely not supported on your platform.\",\n );\n throw err;\n }\n}" ], - "mappings": "AAAA;AAEA,SAASA,aAAa,QAAQ,QAAQ;AACtC,OAAOC,IAAI,MAAM,MAAM;AACvB,cAAcC,YAAY,EAAEC,SAAS,QAAQ,UAAU;AAEvD,MAAMC,UAAU,GAAG,IAAIC,GAAG,CAAC,MAAM,EAAEC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE;AACjD,MAAMC,UAAU,GAAG,IAAIF,GAAG,CAAC,MAAM,EAAEC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE;AAEjD,IAAIE,WAAW,GAAG,KAAK;AACvB,IAAIC,OAAO,EAAEN,SAAS;AACtB,MAAMO,UAAU,GAAG,IAAIJ,GAAG,CAAC,MAAM,CAAC,EAAE;AACpC,IAAIK,UAAU,GAAG,KAAK;AAEtB,OAAO,SAASC,MAAM,CAA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AAU,CAAC,GACnBO,QAAQ,CAACH,OAAO,CAACI,QAAQ,CAACC,IAAI,CAAC,IAAI,CAAC,GACpCT,OAAO,CAAC,UAAU,CAAC,GACnBA,OAAO,CAAC,4BAA4B,CAAC;EAC3C,CAAC,CAAC,OAAOU,GAAG,EAAE;IACZpC,OAAO,CAACqC,KAAK,CACX,yEAAyE,GACvE,6DAA6D,CAChE;IACD,MAAMD,GAAG;EACX;AACF" } \ No newline at end of file diff --git a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file2/output.js b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file2/output.js index 92d500f7e95d..af068a1f65b6 100644 --- a/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file2/output.js +++ b/packages/babel-generator/test/fixtures/sourcemaps/real-world-babel-file2/output.js @@ -1,4 +1,5 @@ // From packages\babel-generator\src\printer.ts + import Buffer from "./buffer"; import type { Loc } from "./buffer"; import * as n from "./node"; @@ -38,12 +39,10 @@ export type Format = { * For use with the Hack-style pipe operator. * Changes what token is used for pipe bodies’ topic references. */ - topicToken?: PipelineOperatorPluginOptions["topicToken"]; /** * @deprecated Removed in Babel 8 */ - decoratorsBeforeExport?: boolean; }; interface AddNewlinesOptions { @@ -61,7 +60,6 @@ interface PrintListOptions { type PrintJoinOptions = PrintListOptions & PrintSequenceOptions & { iterator?: (node: t.Node, index: number) => void; }; - class Printer { constructor(format: Format, map: SourceMap) { this.format = format; @@ -69,7 +67,6 @@ class Printer { this._indentChar = format.indent.style.charCodeAt(0); this._indentRepeat = format.indent.style.length; } - declare format: Format; inForStatementInitCounter: number = 0; declare _buf: Buffer; @@ -86,261 +83,218 @@ class Printer { _printedComments = new Set(); _endsWithInteger = false; _endsWithWord = false; - generate(ast: t.Node) { this.print(ast); - this._maybeAddAuxComment(); - return this._buf.get(); } + /** * Increment indent size. */ - indent(): void { if (this.format.compact || this.format.concise) return; this._indent++; } + /** * Decrement indent size. */ - dedent(): void { if (this.format.compact || this.format.concise) return; this._indent--; } + /** * Add a semicolon to the buffer. */ - semicolon(force: boolean = false): void { this._maybeAddAuxComment(); - if (force) { this._appendChar(charCodes.semicolon); } else { this._queue(charCodes.semicolon); } } + /** * Add a right brace to the buffer. */ - rightBrace(): void { if (this.format.minified) { this._buf.removeLastSemicolon(); } - this.token("}"); } + /** * Add a space to the buffer unless it is compact. */ - space(force: boolean = false): void { if (this.format.compact) return; - if (force) { this._space(); } else if (this._buf.hasContent()) { const lastCp = this.getLastChar(); - if (lastCp !== charCodes.space && lastCp !== charCodes.lineFeed) { this._space(); } } } + /** * Writes a token that can't be safely parsed without taking whitespace into account. */ - word(str: string): void { // prevent concatenating words and creating // comment out of division and regex if (this._endsWithWord || str.charCodeAt(0) === charCodes.slash && this.endsWith(charCodes.slash)) { this._space(); } - this._maybeAddAuxComment(); - this._append(str, false); - this._endsWithWord = true; } + /** * Writes a number token so that we can validate if it is an integer. */ - number(str: string): void { - this.word(str); // Integer tokens need special handling because they cannot have '.'s inserted - // immediately after them. + this.word(str); + // Integer tokens need special handling because they cannot have '.'s inserted + // immediately after them. this._endsWithInteger = Number.isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== charCodes.dot; } + /** * Writes a simple token. */ - token(str: string, maybeNewline = false): void { // space is mandatory to avoid outputting