UNPKG

16.3 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4
5var _assign = require("babel-runtime/core-js/object/assign");
6
7var _assign2 = _interopRequireDefault(_assign);
8
9var _getIterator2 = require("babel-runtime/core-js/get-iterator");
10
11var _getIterator3 = _interopRequireDefault(_getIterator2);
12
13var _stringify = require("babel-runtime/core-js/json/stringify");
14
15var _stringify2 = _interopRequireDefault(_stringify);
16
17var _weakSet = require("babel-runtime/core-js/weak-set");
18
19var _weakSet2 = _interopRequireDefault(_weakSet);
20
21var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
22
23var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
24
25var _find = require("lodash/find");
26
27var _find2 = _interopRequireDefault(_find);
28
29var _findLast = require("lodash/findLast");
30
31var _findLast2 = _interopRequireDefault(_findLast);
32
33var _isInteger = require("lodash/isInteger");
34
35var _isInteger2 = _interopRequireDefault(_isInteger);
36
37var _repeat = require("lodash/repeat");
38
39var _repeat2 = _interopRequireDefault(_repeat);
40
41var _buffer = require("./buffer");
42
43var _buffer2 = _interopRequireDefault(_buffer);
44
45var _node = require("./node");
46
47var n = _interopRequireWildcard(_node);
48
49var _whitespace = require("./whitespace");
50
51var _whitespace2 = _interopRequireDefault(_whitespace);
52
53var _babelTypes = require("babel-types");
54
55var t = _interopRequireWildcard(_babelTypes);
56
57function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
58
59function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
60
61var SCIENTIFIC_NOTATION = /e/i;
62var ZERO_DECIMAL_INTEGER = /\.0+$/;
63var NON_DECIMAL_LITERAL = /^0[box]/;
64
65var Printer = function () {
66 function Printer(format, map, tokens) {
67 (0, _classCallCheck3.default)(this, Printer);
68 this.inForStatementInitCounter = 0;
69 this._printStack = [];
70 this._indent = 0;
71 this._insideAux = false;
72 this._printedCommentStarts = {};
73 this._parenPushNewlineState = null;
74 this._printAuxAfterOnNextUserNode = false;
75 this._printedComments = new _weakSet2.default();
76 this._endsWithInteger = false;
77 this._endsWithWord = false;
78
79 this.format = format || {};
80 this._buf = new _buffer2.default(map);
81 this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null;
82 }
83
84 Printer.prototype.generate = function generate(ast) {
85 this.print(ast);
86 this._maybeAddAuxComment();
87
88 return this._buf.get();
89 };
90
91 Printer.prototype.indent = function indent() {
92 if (this.format.compact || this.format.concise) return;
93
94 this._indent++;
95 };
96
97 Printer.prototype.dedent = function dedent() {
98 if (this.format.compact || this.format.concise) return;
99
100 this._indent--;
101 };
102
103 Printer.prototype.semicolon = function semicolon() {
104 var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
105
106 this._maybeAddAuxComment();
107 this._append(";", !force);
108 };
109
110 Printer.prototype.rightBrace = function rightBrace() {
111 if (this.format.minified) {
112 this._buf.removeLastSemicolon();
113 }
114 this.token("}");
115 };
116
117 Printer.prototype.space = function space() {
118 var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
119
120 if (this.format.compact) return;
121
122 if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) {
123 this._space();
124 }
125 };
126
127 Printer.prototype.word = function word(str) {
128 if (this._endsWithWord) this._space();
129
130 this._maybeAddAuxComment();
131 this._append(str);
132
133 this._endsWithWord = true;
134 };
135
136 Printer.prototype.number = function number(str) {
137 this.word(str);
138
139 this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== ".";
140 };
141
142 Printer.prototype.token = function token(str) {
143 if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) {
144 this._space();
145 }
146
147 this._maybeAddAuxComment();
148 this._append(str);
149 };
150
151 Printer.prototype.newline = function newline(i) {
152 if (this.format.retainLines || this.format.compact) return;
153
154 if (this.format.concise) {
155 this.space();
156 return;
157 }
158
159 if (this.endsWith("\n\n")) return;
160
161 if (typeof i !== "number") i = 1;
162
163 i = Math.min(2, i);
164 if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
165 if (i <= 0) return;
166
167 for (var j = 0; j < i; j++) {
168 this._newline();
169 }
170 };
171
172 Printer.prototype.endsWith = function endsWith(str) {
173 return this._buf.endsWith(str);
174 };
175
176 Printer.prototype.removeTrailingNewline = function removeTrailingNewline() {
177 this._buf.removeTrailingNewline();
178 };
179
180 Printer.prototype.source = function source(prop, loc) {
181 this._catchUp(prop, loc);
182
183 this._buf.source(prop, loc);
184 };
185
186 Printer.prototype.withSource = function withSource(prop, loc, cb) {
187 this._catchUp(prop, loc);
188
189 this._buf.withSource(prop, loc, cb);
190 };
191
192 Printer.prototype._space = function _space() {
193 this._append(" ", true);
194 };
195
196 Printer.prototype._newline = function _newline() {
197 this._append("\n", true);
198 };
199
200 Printer.prototype._append = function _append(str) {
201 var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
202
203 this._maybeAddParen(str);
204 this._maybeIndent(str);
205
206 if (queue) this._buf.queue(str);else this._buf.append(str);
207
208 this._endsWithWord = false;
209 this._endsWithInteger = false;
210 };
211
212 Printer.prototype._maybeIndent = function _maybeIndent(str) {
213 if (this._indent && this.endsWith("\n") && str[0] !== "\n") {
214 this._buf.queue(this._getIndent());
215 }
216 };
217
218 Printer.prototype._maybeAddParen = function _maybeAddParen(str) {
219 var parenPushNewlineState = this._parenPushNewlineState;
220 if (!parenPushNewlineState) return;
221 this._parenPushNewlineState = null;
222
223 var i = void 0;
224 for (i = 0; i < str.length && str[i] === " "; i++) {
225 continue;
226 }if (i === str.length) return;
227
228 var cha = str[i];
229 if (cha === "\n" || cha === "/") {
230 this.token("(");
231 this.indent();
232 parenPushNewlineState.printed = true;
233 }
234 };
235
236 Printer.prototype._catchUp = function _catchUp(prop, loc) {
237 if (!this.format.retainLines) return;
238
239 var pos = loc ? loc[prop] : null;
240 if (pos && pos.line !== null) {
241 var count = pos.line - this._buf.getCurrentLine();
242
243 for (var i = 0; i < count; i++) {
244 this._newline();
245 }
246 }
247 };
248
249 Printer.prototype._getIndent = function _getIndent() {
250 return (0, _repeat2.default)(this.format.indent.style, this._indent);
251 };
252
253 Printer.prototype.startTerminatorless = function startTerminatorless() {
254 return this._parenPushNewlineState = {
255 printed: false
256 };
257 };
258
259 Printer.prototype.endTerminatorless = function endTerminatorless(state) {
260 if (state.printed) {
261 this.dedent();
262 this.newline();
263 this.token(")");
264 }
265 };
266
267 Printer.prototype.print = function print(node, parent) {
268 var _this = this;
269
270 if (!node) return;
271
272 var oldConcise = this.format.concise;
273 if (node._compact) {
274 this.format.concise = true;
275 }
276
277 var printMethod = this[node.type];
278 if (!printMethod) {
279 throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name));
280 }
281
282 this._printStack.push(node);
283
284 var oldInAux = this._insideAux;
285 this._insideAux = !node.loc;
286 this._maybeAddAuxComment(this._insideAux && !oldInAux);
287
288 var needsParens = n.needsParens(node, parent, this._printStack);
289 if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) {
290 needsParens = true;
291 }
292 if (needsParens) this.token("(");
293
294 this._printLeadingComments(node, parent);
295
296 var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc;
297 this.withSource("start", loc, function () {
298 _this[node.type](node, parent);
299 });
300
301 this._printTrailingComments(node, parent);
302
303 if (needsParens) this.token(")");
304
305 this._printStack.pop();
306
307 this.format.concise = oldConcise;
308 this._insideAux = oldInAux;
309 };
310
311 Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) {
312 if (enteredPositionlessNode) this._printAuxBeforeComment();
313 if (!this._insideAux) this._printAuxAfterComment();
314 };
315
316 Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() {
317 if (this._printAuxAfterOnNextUserNode) return;
318 this._printAuxAfterOnNextUserNode = true;
319
320 var comment = this.format.auxiliaryCommentBefore;
321 if (comment) {
322 this._printComment({
323 type: "CommentBlock",
324 value: comment
325 });
326 }
327 };
328
329 Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() {
330 if (!this._printAuxAfterOnNextUserNode) return;
331 this._printAuxAfterOnNextUserNode = false;
332
333 var comment = this.format.auxiliaryCommentAfter;
334 if (comment) {
335 this._printComment({
336 type: "CommentBlock",
337 value: comment
338 });
339 }
340 };
341
342 Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
343 var extra = node.extra;
344 if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
345 return extra.raw;
346 }
347 };
348
349 Printer.prototype.printJoin = function printJoin(nodes, parent) {
350 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
351
352 if (!nodes || !nodes.length) return;
353
354 if (opts.indent) this.indent();
355
356 var newlineOpts = {
357 addNewlines: opts.addNewlines
358 };
359
360 for (var i = 0; i < nodes.length; i++) {
361 var node = nodes[i];
362 if (!node) continue;
363
364 if (opts.statement) this._printNewline(true, node, parent, newlineOpts);
365
366 this.print(node, parent);
367
368 if (opts.iterator) {
369 opts.iterator(node, i);
370 }
371
372 if (opts.separator && i < nodes.length - 1) {
373 opts.separator.call(this);
374 }
375
376 if (opts.statement) this._printNewline(false, node, parent, newlineOpts);
377 }
378
379 if (opts.indent) this.dedent();
380 };
381
382 Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
383 var indent = !!node.leadingComments;
384 if (indent) this.indent();
385 this.print(node, parent);
386 if (indent) this.dedent();
387 };
388
389 Printer.prototype.printBlock = function printBlock(parent) {
390 var node = parent.body;
391
392 if (!t.isEmptyStatement(node)) {
393 this.space();
394 }
395
396 this.print(node, parent);
397 };
398
399 Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) {
400 this._printComments(this._getComments(false, node, parent));
401 };
402
403 Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) {
404 this._printComments(this._getComments(true, node, parent));
405 };
406
407 Printer.prototype.printInnerComments = function printInnerComments(node) {
408 var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
409
410 if (!node.innerComments) return;
411 if (indent) this.indent();
412 this._printComments(node.innerComments);
413 if (indent) this.dedent();
414 };
415
416 Printer.prototype.printSequence = function printSequence(nodes, parent) {
417 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
418
419 opts.statement = true;
420 return this.printJoin(nodes, parent, opts);
421 };
422
423 Printer.prototype.printList = function printList(items, parent) {
424 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
425
426 if (opts.separator == null) {
427 opts.separator = commaSeparator;
428 }
429
430 return this.printJoin(items, parent, opts);
431 };
432
433 Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
434 var _this2 = this;
435
436 if (this.format.retainLines || this.format.compact) return;
437
438 if (this.format.concise) {
439 this.space();
440 return;
441 }
442
443 var lines = 0;
444
445 if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) {
446 if (leading) {
447 var _comments = node.leadingComments;
448 var _comment = _comments && (0, _find2.default)(_comments, function (comment) {
449 return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
450 });
451
452 lines = this._whitespace.getNewlinesBefore(_comment || node);
453 } else {
454 var _comments2 = node.trailingComments;
455 var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) {
456 return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
457 });
458
459 lines = this._whitespace.getNewlinesAfter(_comment2 || node);
460 }
461 } else {
462 if (!leading) lines++;
463 if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
464
465 var needs = n.needsWhitespaceAfter;
466 if (leading) needs = n.needsWhitespaceBefore;
467 if (needs(node, parent)) lines++;
468
469 if (!this._buf.hasContent()) lines = 0;
470 }
471
472 this.newline(lines);
473 };
474
475 Printer.prototype._getComments = function _getComments(leading, node) {
476 return node && (leading ? node.leadingComments : node.trailingComments) || [];
477 };
478
479 Printer.prototype._printComment = function _printComment(comment) {
480 var _this3 = this;
481
482 if (!this.format.shouldPrintComment(comment.value)) return;
483
484 if (comment.ignore) return;
485
486 if (this._printedComments.has(comment)) return;
487 this._printedComments.add(comment);
488
489 if (comment.start != null) {
490 if (this._printedCommentStarts[comment.start]) return;
491 this._printedCommentStarts[comment.start] = true;
492 }
493
494 this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0);
495
496 if (!this.endsWith("[") && !this.endsWith("{")) this.space();
497
498 var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/";
499
500 if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
501 var offset = comment.loc && comment.loc.start.column;
502 if (offset) {
503 var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
504 val = val.replace(newlineRegex, "\n");
505 }
506
507 var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn());
508 val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize));
509 }
510
511 this.withSource("start", comment.loc, function () {
512 _this3._append(val);
513 });
514
515 this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0));
516 };
517
518 Printer.prototype._printComments = function _printComments(comments) {
519 if (!comments || !comments.length) return;
520
521 for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
522 var _ref;
523
524 if (_isArray) {
525 if (_i >= _iterator.length) break;
526 _ref = _iterator[_i++];
527 } else {
528 _i = _iterator.next();
529 if (_i.done) break;
530 _ref = _i.value;
531 }
532
533 var _comment3 = _ref;
534
535 this._printComment(_comment3);
536 }
537 };
538
539 return Printer;
540}();
541
542exports.default = Printer;
543
544
545function commaSeparator() {
546 this.token(",");
547 this.space();
548}
549
550var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
551for (var _i2 = 0; _i2 < _arr.length; _i2++) {
552 var generator = _arr[_i2];
553 (0, _assign2.default)(Printer.prototype, generator);
554}
555module.exports = exports["default"];
\No newline at end of file