Debian Codegraph @

core/formatter.cpp

raw
1 /*
2 Copyright 2015 Google Inc. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 #include <algorithm>
18 #include <set>
19 #include <typeinfo>
20
21 #include "formatter.h"
22 #include "lexer.h"
23 #include "pass.h"
24 #include "string_utils.h"
25 #include "unicode.h"
26
27 namespace jsonnet::internal {
28
29 static std::string unparse_id(const Identifier *id)
30 {
31 return encode_utf8(id->name);
32 }
33
34 /** If left recursive, return the left hand side, else return nullptr. */
35 static AST *left_recursive(AST *ast_)
36 {
37 if (auto *ast = dynamic_cast<Apply *>(ast_))
38 return ast->target;
39 if (auto *ast = dynamic_cast<ApplyBrace *>(ast_))
40 return ast->left;
41 if (auto *ast = dynamic_cast<Binary *>(ast_))
42 return ast->left;
43 if (auto *ast = dynamic_cast<Index *>(ast_))
44 return ast->target;
45 if (auto *ast = dynamic_cast<InSuper *>(ast_))
46 return ast->element;
47 return nullptr;
48 }
49 static const AST *left_recursive(const AST *ast_)
50 {
51 return left_recursive(const_cast<AST *>(ast_));
52 }
53
54 /** The transitive closure of left_recursive). */
55 static AST *left_recursive_deep(AST *ast_)
56 {
57 AST *last = ast_;
58 AST *left = left_recursive(ast_);
59
60 while (left != nullptr) {
61 last = left;
62 left = left_recursive(last);
63 }
64 return last;
65 }
66
67 /** Pretty-print fodder.
68 *
69 * \param fodder The fodder to print
70 * \param space_before Whether a space should be printed before any other output.
71 * \param separate_token If the last fodder was an interstitial, whether a space should follow it.
72 * \param final Whether fodder is the last one in
73 */
74 void fodder_fill(std::ostream &o, const Fodder &fodder, bool space_before, bool separate_token, bool final)
75 {
76 unsigned last_indent = 0;
77 size_t index = 0;
78 for (const auto &fod : fodder) {
79 bool skip_trailing = final && (index == (fodder.size() - 1));
80 switch (fod.kind) {
81 case FodderElement::LINE_END:
82 if (fod.comment.size() > 0)
83 o << " " << fod.comment[0];
84 o << '\n';
85 if (!skip_trailing) {
86 o << std::string(fod.blanks, '\n');
87 o << std::string(fod.indent, ' ');
88 }
89 last_indent = fod.indent;
90 space_before = false;
91 break;
92
93 case FodderElement::INTERSTITIAL:
94 if (space_before)
95 o << ' ';
96 o << fod.comment[0];
97 space_before = true;
98 break;
99
100 case FodderElement::PARAGRAPH: {
101 bool first = true;
102 for (const std::string &l : fod.comment) {
103 // Do not indent empty lines (note: first line is never empty).
104 if (l.length() > 0) {
105 // First line is already indented by previous fod.
106 if (!first)
107 o << std::string(last_indent, ' ');
108 o << l;
109 }
110 o << '\n';
111 first = false;
112 }
113 if (!skip_trailing) {
114 o << std::string(fod.blanks, '\n');
115 o << std::string(fod.indent, ' ');
116 }
117 last_indent = fod.indent;
118 space_before = false;
119 } break;
120 }
121 ++index;
122 }
123 if (separate_token && space_before)
124 o << ' ';
125 }
126
127 /** A model of fodder_fill that just keeps track of the column counter. */
128 static void fodder_count(unsigned &column, const Fodder &fodder, bool space_before,
129 bool separate_token)
130 {
131 for (const auto &fod : fodder) {
132 switch (fod.kind) {
133 case FodderElement::PARAGRAPH:
134 case FodderElement::LINE_END:
135 column = fod.indent;
136 space_before = false;
137 break;
138
139 case FodderElement::INTERSTITIAL:
140 if (space_before)
141 column++;
142 column += fod.comment[0].length();
143 space_before = true;
144 break;
145 }
146 }
147 if (separate_token && space_before)
148 column++;
149 }
150
151 class Unparser {
152 public:
153 private:
154 std::ostream &o;
155 FmtOpts opts;
156
157 public:
158 Unparser(std::ostream &o, const FmtOpts &opts) : o(o), opts(opts) {}
159
160 void unparseSpecs(const std::vector<ComprehensionSpec> &specs)
161 {
162 for (const auto &spec : specs) {
163 fill(spec.openFodder, true, true);
164 switch (spec.kind) {
165 case ComprehensionSpec::FOR:
166 o << "for";
167 fill(spec.varFodder, true, true);
168 o << unparse_id(spec.var);
169 fill(spec.inFodder, true, true);
170 o << "in";
171 unparse(spec.expr, true);
172 break;
173 case ComprehensionSpec::IF:
174 o << "if";
175 unparse(spec.expr, true);
176 break;
177 }
178 }
179 }
180
181 void fill(const Fodder &fodder, bool space_before, bool separate_token)
182 {
183 fodder_fill(o, fodder, space_before, separate_token, false);
184 }
185
186 void fill_final(const Fodder &fodder, bool space_before, bool separate_token)
187 {
188 fodder_fill(o, fodder, space_before, separate_token, true);
189 }
190
191 void unparseParams(const Fodder &fodder_l, const ArgParams &params, bool trailing_comma,
192 const Fodder &fodder_r)
193 {
194 fill(fodder_l, false, false);
195 o << "(";
196 bool first = true;
197 for (const auto &param : params) {
198 if (!first)
199 o << ",";
200 fill(param.idFodder, !first, true);
201 o << unparse_id(param.id);
202 if (param.expr != nullptr) {
203 // default arg, no spacing: x=e
204 fill(param.eqFodder, false, false);
205 o << "=";
206 unparse(param.expr, false);
207 }
208 fill(param.commaFodder, false, false);
209 first = false;
210 }
211 if (trailing_comma)
212 o << ",";
213 fill(fodder_r, false, false);
214 o << ")";
215 }
216
217 void unparseFieldParams(const ObjectField &field)
218 {
219 if (field.methodSugar) {
220 unparseParams(field.fodderL, field.params, field.trailingComma, field.fodderR);
221 }
222 }
223
224 void unparseFields(const ObjectFields &fields, bool space_before)
225 {
226 bool first = true;
227 for (const auto &field : fields) {
228 if (!first)
229 o << ',';
230
231 switch (field.kind) {
232 case ObjectField::LOCAL: {
233 fill(field.fodder1, !first || space_before, true);
234 o << "local";
235 fill(field.fodder2, true, true);
236 o << unparse_id(field.id);
237 unparseFieldParams(field);
238 fill(field.opFodder, true, true);
239 o << "=";
240 unparse(field.expr2, true);
241 } break;
242
243 case ObjectField::FIELD_ID:
244 case ObjectField::FIELD_STR:
245 case ObjectField::FIELD_EXPR: {
246 if (field.kind == ObjectField::FIELD_ID) {
247 fill(field.fodder1, !first || space_before, true);
248 o << unparse_id(field.id);
249
250 } else if (field.kind == ObjectField::FIELD_STR) {
251 unparse(field.expr1, !first || space_before);
252
253 } else if (field.kind == ObjectField::FIELD_EXPR) {
254 fill(field.fodder1, !first || space_before, true);
255 o << "[";
256 unparse(field.expr1, false);
257 fill(field.fodder2, false, false);
258 o << "]";
259 }
260 unparseFieldParams(field);
261
262 fill(field.opFodder, false, false);
263
264 if (field.superSugar)
265 o << "+";
266 switch (field.hide) {
267 case ObjectField::INHERIT: o << ":"; break;
268 case ObjectField::HIDDEN: o << "::"; break;
269 case ObjectField::VISIBLE: o << ":::"; break;
270 }
271 unparse(field.expr2, true);
272
273 } break;
274
275 case ObjectField::ASSERT: {
276 fill(field.fodder1, !first || space_before, true);
277 o << "assert";
278 unparse(field.expr2, true);
279 if (field.expr3 != nullptr) {
280 fill(field.opFodder, true, true);
281 o << ":";
282 unparse(field.expr3, true);
283 }
284 } break;
285 }
286
287 first = false;
288 fill(field.commaFodder, false, false);
289 }
290 }
291
292 /** Unparse the given AST.
293 *
294 * \param ast_ The AST to be unparsed.
295 *
296 * \param precedence The precedence of the enclosing AST. If this is greater than the current
297 * precedence, parens are not needed.
298 */
299 void unparse(const AST *ast_, bool space_before)
300 {
301 bool separate_token = !left_recursive(ast_);
302
303 fill(ast_->openFodder, space_before, separate_token);
304
305 if (auto *ast = dynamic_cast<const Apply *>(ast_)) {
306 unparse(ast->target, space_before);
307 fill(ast->fodderL, false, false);
308 o << "(";
309 bool first = true;
310 for (const auto &arg : ast->args) {
311 if (!first)
312 o << ',';
313 bool space = !first;
314 if (arg.id != nullptr) {
315 fill(arg.idFodder, space, true);
316 o << unparse_id(arg.id);
317 space = false;
318 o << "=";
319 }
320 unparse(arg.expr, space);
321 fill(arg.commaFodder, false, false);
322 first = false;
323 }
324 if (ast->trailingComma)
325 o << ",";
326 fill(ast->fodderR, false, false);
327 o << ")";
328 if (ast->tailstrict) {
329 fill(ast->tailstrictFodder, true, true);
330 o << "tailstrict";
331 }
332
333 } else if (auto *ast = dynamic_cast<const ApplyBrace *>(ast_)) {
334 unparse(ast->left, space_before);
335 unparse(ast->right, true);
336
337 } else if (auto *ast = dynamic_cast<const Array *>(ast_)) {
338 o << "[";
339 bool first = true;
340 for (const auto &element : ast->elements) {
341 if (!first)
342 o << ',';
343 unparse(element.expr, !first || opts.padArrays);
344 fill(element.commaFodder, false, false);
345 first = false;
346 }
347 if (ast->trailingComma)
348 o << ",";
349 fill(ast->closeFodder, ast->elements.size() > 0, opts.padArrays);
350 o << "]";
351
352 } else if (auto *ast = dynamic_cast<const ArrayComprehension *>(ast_)) {
353 o << "[";
354 unparse(ast->body, opts.padArrays);
355 fill(ast->commaFodder, false, false);
356 if (ast->trailingComma)
357 o << ",";
358 unparseSpecs(ast->specs);
359 fill(ast->closeFodder, true, opts.padArrays);
360 o << "]";
361
362 } else if (auto *ast = dynamic_cast<const Assert *>(ast_)) {
363 o << "assert";
364 unparse(ast->cond, true);
365 if (ast->message != nullptr) {
366 fill(ast->colonFodder, true, true);
367 o << ":";
368 unparse(ast->message, true);
369 }
370 fill(ast->semicolonFodder, false, false);
371 o << ";";
372 unparse(ast->rest, true);
373
374 } else if (auto *ast = dynamic_cast<const Binary *>(ast_)) {
375 unparse(ast->left, space_before);
376 fill(ast->opFodder, true, true);
377 o << bop_string(ast->op);
378 // The - 1 is for left associativity.
379 unparse(ast->right, true);
380
381 } else if (auto *ast = dynamic_cast<const BuiltinFunction *>(ast_)) {
382 o << "/* builtin " << ast->body->name << " */ null";
383
384 } else if (auto *ast = dynamic_cast<const Conditional *>(ast_)) {
385 o << "if";
386 unparse(ast->cond, true);
387 fill(ast->thenFodder, true, true);
388 o << "then";
389 if (ast->branchFalse != nullptr) {
390 unparse(ast->branchTrue, true);
391 fill(ast->elseFodder, true, true);
392 o << "else";
393 unparse(ast->branchFalse, true);
394 } else {
395 unparse(ast->branchTrue, true);
396 }
397
398 } else if (dynamic_cast<const Dollar *>(ast_)) {
399 o << "$";
400
401 } else if (auto *ast = dynamic_cast<const Error *>(ast_)) {
402 o << "error";
403 unparse(ast->expr, true);
404
405 } else if (auto *ast = dynamic_cast<const Function *>(ast_)) {
406 o << "function";
407 unparseParams(
408 ast->parenLeftFodder, ast->params, ast->trailingComma, ast->parenRightFodder);
409 unparse(ast->body, true);
410
411 } else if (auto *ast = dynamic_cast<const Import *>(ast_)) {
412 o << "import";
413 unparse(ast->file, true);
414
415 } else if (auto *ast = dynamic_cast<const Importstr *>(ast_)) {
416 o << "importstr";
417 unparse(ast->file, true);
418
419 } else if (auto *ast = dynamic_cast<const Importbin *>(ast_)) {
420 o << "importbin";
421 unparse(ast->file, true);
422
423 } else if (auto *ast = dynamic_cast<const InSuper *>(ast_)) {
424 unparse(ast->element, true);
425 fill(ast->inFodder, true, true);
426 o << "in";
427 fill(ast->superFodder, true, true);
428 o << "super";
429
430 } else if (auto *ast = dynamic_cast<const Index *>(ast_)) {
431 unparse(ast->target, space_before);
432 fill(ast->dotFodder, false, false);
433 if (ast->id != nullptr) {
434 o << ".";
435 fill(ast->idFodder, false, false);
436 o << unparse_id(ast->id);
437 } else {
438 o << "[";
439 if (ast->isSlice) {
440 if (ast->index != nullptr) {
441 unparse(ast->index, false);
442 }
443 fill(ast->endColonFodder, false, false);
444 o << ":";
445 if (ast->end != nullptr) {
446 unparse(ast->end, false);
447 }
448 if (ast->step != nullptr || ast->stepColonFodder.size() > 0) {
449 fill(ast->stepColonFodder, false, false);
450 o << ":";
451 if (ast->step != nullptr) {
452 unparse(ast->step, false);
453 }
454 }
455 } else {
456 unparse(ast->index, false);
457 }
458 fill(ast->idFodder, false, false);
459 o << "]";
460 }
461
462 } else if (auto *ast = dynamic_cast<const Local *>(ast_)) {
463 o << "local";
464 assert(ast->binds.size() > 0);
465 bool first = true;
466 for (const auto &bind : ast->binds) {
467 if (!first)
468 o << ",";
469 first = false;
470 fill(bind.varFodder, true, true);
471 o << unparse_id(bind.var);
472 if (bind.functionSugar) {
473 unparseParams(bind.parenLeftFodder,
474 bind.params,
475 bind.trailingComma,
476 bind.parenRightFodder);
477 }
478 fill(bind.opFodder, true, true);
479 o << "=";
480 unparse(bind.body, true);
481 fill(bind.closeFodder, false, false);
482 }
483 o << ";";
484 unparse(ast->body, true);
485
486 } else if (auto *ast = dynamic_cast<const LiteralBoolean *>(ast_)) {
487 o << (ast->value ? "true" : "false");
488
489 } else if (auto *ast = dynamic_cast<const LiteralNumber *>(ast_)) {
490 o << ast->originalString;
491
492 } else if (auto *ast = dynamic_cast<const LiteralString *>(ast_)) {
493 assert(ast->tokenKind != LiteralString::RAW_DESUGARED);
494 if (ast->tokenKind == LiteralString::DOUBLE) {
495 o << "\"";
496 o << encode_utf8(ast->value);
497 o << "\"";
498 } else if (ast->tokenKind == LiteralString::SINGLE) {
499 o << "'";
500 o << encode_utf8(ast->value);
501 o << "'";
502 } else if (ast->tokenKind == LiteralString::BLOCK) {
503 o << "|||";
504 if (ast->value.back() != U'\n') {
505 o << "-";
506 }
507 o << "\n";
508 if (ast->value.c_str()[0] != U'\n')
509 o << ast->blockIndent;
510 for (const char32_t *cp = ast->value.c_str(); *cp != U'\0'; ++cp) {
511 // Formatter always outputs in unix mode.
512 if (*cp == '\r') continue;
513 std::string utf8;
514 encode_utf8(*cp, utf8);
515 o << utf8;
516 if (*cp == U'\n' && *(cp + 1) != U'\n' && *(cp + 1) != U'\0') {
517 o << ast->blockIndent;
518 }
519 }
520 if (ast->value.back() != U'\n') {
521 o << "\n";
522 }
523 o << ast->blockTermIndent << "|||";
524 } else if (ast->tokenKind == LiteralString::VERBATIM_DOUBLE) {
525 o << "@\"";
526 for (const char32_t *cp = ast->value.c_str(); *cp != U'\0'; ++cp) {
527 if (*cp == U'"') {
528 o << "\"\"";
529 } else {
530 std::string utf8;
531 encode_utf8(*cp, utf8);
532 o << utf8;
533 }
534 }
535 o << "\"";
536 } else if (ast->tokenKind == LiteralString::VERBATIM_SINGLE) {
537 o << "@'";
538 for (const char32_t *cp = ast->value.c_str(); *cp != U'\0'; ++cp) {
539 if (*cp == U'\'') {
540 o << "''";
541 } else {
542 std::string utf8;
543 encode_utf8(*cp, utf8);
544 o << utf8;
545 }
546 }
547 o << "'";
548 }
549
550 } else if (dynamic_cast<const LiteralNull *>(ast_)) {
551 o << "null";
552
553 } else if (auto *ast = dynamic_cast<const Object *>(ast_)) {
554 o << "{";
555 unparseFields(ast->fields, opts.padObjects);
556 if (ast->trailingComma)
557 o << ",";
558 fill(ast->closeFodder, ast->fields.size() > 0, opts.padObjects);
559 o << "}";
560
561 } else if (auto *ast = dynamic_cast<const DesugaredObject *>(ast_)) {
562 o << "{";
563 for (AST *assert : ast->asserts) {
564 o << "assert";
565 unparse(assert, true);
566 o << ",";
567 }
568 for (auto &field : ast->fields) {
569 o << "[";
570 unparse(field.name, false);
571 o << "]";
572 switch (field.hide) {
573 case ObjectField::INHERIT: o << ":"; break;
574 case ObjectField::HIDDEN: o << "::"; break;
575 case ObjectField::VISIBLE: o << ":::"; break;
576 }
577 unparse(field.body, true);
578 o << ",";
579 }
580 o << "}";
581
582 } else if (auto *ast = dynamic_cast<const ObjectComprehension *>(ast_)) {
583 o << "{";
584 unparseFields(ast->fields, opts.padObjects);
585 if (ast->trailingComma)
586 o << ",";
587 unparseSpecs(ast->specs);
588 fill(ast->closeFodder, true, opts.padObjects);
589 o << "}";
590
591 } else if (auto *ast = dynamic_cast<const ObjectComprehensionSimple *>(ast_)) {
592 o << "{[";
593 unparse(ast->field, false);
594 o << "]:";
595 unparse(ast->value, true);
596 o << " for " << unparse_id(ast->id) << " in";
597 unparse(ast->array, true);
598 o << "}";
599
600 } else if (auto *ast = dynamic_cast<const Parens *>(ast_)) {
601 o << "(";
602 unparse(ast->expr, false);
603 fill(ast->closeFodder, false, false);
604 o << ")";
605
606 } else if (dynamic_cast<const Self *>(ast_)) {
607 o << "self";
608
609 } else if (auto *ast = dynamic_cast<const SuperIndex *>(ast_)) {
610 o << "super";
611 fill(ast->dotFodder, false, false);
612 if (ast->id != nullptr) {
613 o << ".";
614 fill(ast->idFodder, false, false);
615 o << unparse_id(ast->id);
616 } else {
617 o << "[";
618 unparse(ast->index, false);
619 fill(ast->idFodder, false, false);
620 o << "]";
621 }
622
623 } else if (auto *ast = dynamic_cast<const Unary *>(ast_)) {
624 o << uop_string(ast->op);
625 unparse(ast->expr, false);
626
627 } else if (auto *ast = dynamic_cast<const Var *>(ast_)) {
628 o << encode_utf8(ast->id->name);
629
630 } else {
631 std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_ << std::endl;
632 std::abort();
633 }
634 }
635 };
636
637 /********************************************************************************
638 * The rest of this file contains transformations on the ASTs before unparsing. *
639 ********************************************************************************/
640
641 /** A generic Pass that does nothing but can be extended to easily define real passes.
642 */
643 class FmtPass : public CompilerPass {
644 protected:
645 FmtOpts opts;
646
647 public:
648 FmtPass(Allocator &alloc, const FmtOpts &opts) : CompilerPass(alloc), opts(opts) {}
649 };
650
651 class EnforceStringStyle : public FmtPass {
652 using FmtPass::visit;
653
654 public:
655 EnforceStringStyle(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
656 void visit(LiteralString *lit)
657 {
658 assert(lit->tokenKind != LiteralString::RAW_DESUGARED);
659 if (lit->tokenKind == LiteralString::BLOCK)
660 return;
661 if (lit->tokenKind == LiteralString::VERBATIM_DOUBLE)
662 return;
663 if (lit->tokenKind == LiteralString::VERBATIM_SINGLE)
664 return;
665 UString canonical = jsonnet_string_unescape(lit->location, lit->value);
666 unsigned num_single = 0, num_double = 0;
667 for (char32_t c : canonical) {
668 if (c == '\'')
669 num_single++;
670 if (c == '"')
671 num_double++;
672 }
673 if (num_single > 0 && num_double > 0)
674 return; // Don't change it.
675 bool use_single = opts.stringStyle == 's';
676 if (num_single > 0)
677 use_single = false;
678 if (num_double > 0)
679 use_single = true;
680
681 // Change it.
682 lit->value = jsonnet_string_escape(canonical, use_single);
683 lit->tokenKind = use_single ? LiteralString::SINGLE : LiteralString::DOUBLE;
684 }
685 };
686
687 class EnforceCommentStyle : public FmtPass {
688 public:
689 bool firstFodder;
690 EnforceCommentStyle(Allocator &alloc, const FmtOpts &opts)
691 : FmtPass(alloc, opts), firstFodder(true)
692 {
693 }
694 /** Change the comment to match the given style, but don't break she-bang.
695 *
696 * If preserve_hash is true, do not touch a comment that starts with #!.
697 */
698 void fixComment(std::string &s, bool preserve_hash)
699 {
700 if (opts.commentStyle == 'h' && s[0] == '/') {
701 s = "#" + s.substr(2);
702 }
703 if (opts.commentStyle == 's' && s[0] == '#') {
704 if (preserve_hash && s[1] == '!')
705 return;
706 s = "//" + s.substr(1);
707 }
708 }
709 void fodder(Fodder &fodder)
710 {
711 for (auto &f : fodder) {
712 switch (f.kind) {
713 case FodderElement::LINE_END:
714 case FodderElement::PARAGRAPH:
715 if (f.comment.size() == 1) {
716 fixComment(f.comment[0], firstFodder);
717 }
718 break;
719
720 case FodderElement::INTERSTITIAL: break;
721 }
722 firstFodder = false;
723 }
724 }
725 };
726
727 class EnforceMaximumBlankLines : public FmtPass {
728 public:
729 EnforceMaximumBlankLines(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
730 void fodderElement(FodderElement &f)
731 {
732 if (f.kind != FodderElement::INTERSTITIAL)
733 if (f.blanks > opts.maxBlankLines)
734 f.blanks = opts.maxBlankLines;
735 }
736 };
737
738 class StripComments : public FmtPass {
739 public:
740 StripComments(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
741 void fodder(Fodder &fodder)
742 {
743 Fodder copy = fodder;
744 fodder.clear();
745 for (auto &f : copy) {
746 if (f.kind == FodderElement::LINE_END)
747 fodder.push_back(f);
748 }
749 }
750 };
751
752 class StripEverything : public FmtPass {
753 public:
754 StripEverything(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
755 void fodder(Fodder &fodder)
756 {
757 fodder.clear();
758 }
759 };
760
761 class StripAllButComments : public FmtPass {
762 public:
763 StripAllButComments(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
764 Fodder comments;
765 void fodder(Fodder &fodder)
766 {
767 for (auto &f : fodder) {
768 if (f.kind == FodderElement::PARAGRAPH) {
769 comments.emplace_back(FodderElement::PARAGRAPH, 0, 0, f.comment);
770 } else if (f.kind == FodderElement::INTERSTITIAL) {
771 comments.push_back(f);
772 comments.emplace_back(FodderElement::LINE_END, 0, 0, std::vector<std::string>{});
773 }
774 }
775 fodder.clear();
776 }
777 virtual void file(AST *&body, Fodder &final_fodder)
778 {
779 expr(body);
780 fodder(final_fodder);
781 body = alloc.make<LiteralNull>(body->location, comments);
782 final_fodder.clear();
783 }
784 };
785
786 /** These cases are infix so we descend on the left to find the fodder. */
787 static Fodder &open_fodder(AST *ast_)
788 {
789 return left_recursive_deep(ast_)->openFodder;
790 }
791
792 /** Strip blank lines from the top of the file. */
793 void remove_initial_newlines(AST *ast)
794 {
795 Fodder &f = open_fodder(ast);
796 while (f.size() > 0 && f[0].kind == FodderElement::LINE_END)
797 f.erase(f.begin());
798 }
799
800 void remove_extra_trailing_newlines(Fodder &final_fodder) {
801 if (!final_fodder.empty()) {
802 final_fodder.back().blanks = 0;
803 }
804 }
805
806 bool contains_newline(const Fodder &fodder)
807 {
808 for (const auto &f : fodder) {
809 if (f.kind != FodderElement::INTERSTITIAL)
810 return true;
811 }
812 return false;
813 }
814
815 /* Commas should appear at the end of an object/array only if the closing token is on a new line. */
816 class FixTrailingCommas : public FmtPass {
817 using FmtPass::visit;
818
819 public:
820 FixTrailingCommas(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
821 Fodder comments;
822
823 // Generalized fix that works across a range of ASTs.
824 void fix_comma(Fodder &last_comma_fodder, bool &trailing_comma, Fodder &close_fodder)
825 {
826 bool need_comma = contains_newline(close_fodder) || contains_newline(last_comma_fodder);
827 if (trailing_comma) {
828 if (!need_comma) {
829 // Remove it but keep fodder.
830 trailing_comma = false;
831 fodder_move_front(close_fodder, last_comma_fodder);
832 } else if (contains_newline(last_comma_fodder)) {
833 // The comma is needed but currently is separated by a newline.
834 fodder_move_front(close_fodder, last_comma_fodder);
835 }
836 } else {
837 if (need_comma) {
838 // There was no comma, but there was a newline before the ] so add a comma.
839 trailing_comma = true;
840 }
841 }
842 }
843
844 void remove_comma(Fodder &last_comma_fodder, bool &trailing_comma, Fodder &close_fodder)
845 {
846 if (trailing_comma) {
847 // Remove it but keep fodder.
848 trailing_comma = false;
849 close_fodder = concat_fodder(last_comma_fodder, close_fodder);
850 last_comma_fodder.clear();
851 }
852 }
853
854 void visit(Array *expr)
855 {
856 if (expr->elements.size() == 0) {
857 // No comma present and none can be added.
858 return;
859 }
860
861 fix_comma(expr->elements.back().commaFodder, expr->trailingComma, expr->closeFodder);
862 FmtPass::visit(expr);
863 }
864
865 void visit(ArrayComprehension *expr)
866 {
867 remove_comma(expr->commaFodder, expr->trailingComma, expr->specs[0].openFodder);
868 FmtPass::visit(expr);
869 }
870
871 void visit(Object *expr)
872 {
873 if (expr->fields.size() == 0) {
874 // No comma present and none can be added.
875 return;
876 }
877
878 fix_comma(expr->fields.back().commaFodder, expr->trailingComma, expr->closeFodder);
879 FmtPass::visit(expr);
880 }
881
882 void visit(ObjectComprehension *expr)
883 {
884 remove_comma(expr->fields.back().commaFodder, expr->trailingComma, expr->closeFodder);
885 FmtPass::visit(expr);
886 }
887 };
888
889 /* Remove nested parens. */
890 class FixParens : public FmtPass {
891 using FmtPass::visit;
892
893 public:
894 FixParens(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
895 void visit(Parens *expr)
896 {
897 if (auto *body = dynamic_cast<Parens *>(expr->expr)) {
898 // Deal with fodder.
899 expr->expr = body->expr;
900 fodder_move_front(open_fodder(body->expr), body->openFodder);
901 fodder_move_front(expr->closeFodder, body->closeFodder);
902 }
903 FmtPass::visit(expr);
904 }
905 };
906
907 /* Ensure ApplyBrace syntax sugar is used in the case of A + { }. */
908 class FixPlusObject : public FmtPass {
909 using FmtPass::visit;
910
911 public:
912 FixPlusObject(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
913 void visitExpr(AST *&expr)
914 {
915 if (auto *bin_op = dynamic_cast<Binary *>(expr)) {
916 // Could relax this to allow more ASTs on the LHS but this seems OK for now.
917 if (dynamic_cast<Var *>(bin_op->left) || dynamic_cast<Index *>(bin_op->left)) {
918 if (AST *rhs = dynamic_cast<Object *>(bin_op->right)) {
919 if (bin_op->op == BOP_PLUS) {
920 fodder_move_front(rhs->openFodder, bin_op->opFodder);
921 expr = alloc.make<ApplyBrace>(
922 bin_op->location, bin_op->openFodder, bin_op->left, rhs);
923 }
924 }
925 }
926 }
927 FmtPass::visitExpr(expr);
928 }
929 };
930
931 /* Remove final colon in slices. */
932 class NoRedundantSliceColon : public FmtPass {
933 using FmtPass::visit;
934
935 public:
936 NoRedundantSliceColon(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
937
938 void visit(Index *expr)
939 {
940 if (expr->isSlice) {
941 if (expr->step == nullptr) {
942 if (expr->stepColonFodder.size() > 0) {
943 fodder_move_front(expr->idFodder, expr->stepColonFodder);
944 }
945 }
946 }
947 FmtPass::visit(expr);
948 }
949 };
950
951 /* Ensure syntax sugar is used where possible. */
952 class PrettyFieldNames : public FmtPass {
953 using FmtPass::visit;
954
955 public:
956 PrettyFieldNames(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
957
958 bool isIdentifier(const UString &str)
959 {
960 // Identifiers cannot be zero-length.
961 if (str.length() == 0) return false;
962
963 bool first = true;
964 for (char32_t c : str) {
965 if (!first && c >= '0' && c <= '9')
966 continue;
967 first = false;
968 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_'))
969 continue;
970 return false;
971 }
972 // Filter out keywords.
973 if (lex_get_keyword_kind(encode_utf8(str)) != Token::IDENTIFIER)
974 return false;
975 return true;
976 }
977
978 void visit(Index *expr)
979 {
980 if (!expr->isSlice && expr->index != nullptr) {
981 // Maybe we can use an id instead.
982 if (auto *lit = dynamic_cast<LiteralString *>(expr->index)) {
983 if (isIdentifier(lit->value)) {
984 expr->id = alloc.makeIdentifier(lit->value);
985 expr->idFodder = lit->openFodder;
986 expr->index = nullptr;
987 }
988 }
989 }
990 FmtPass::visit(expr);
991 }
992
993 void visit(Object *expr)
994 {
995 for (auto &field : expr->fields) {
996 // First try ["foo"] -> "foo".
997 if (field.kind == ObjectField::FIELD_EXPR) {
998 if (auto *field_expr = dynamic_cast<LiteralString *>(field.expr1)) {
999 field.kind = ObjectField::FIELD_STR;
1000 fodder_move_front(field_expr->openFodder, field.fodder1);
1001 if (field.methodSugar) {
1002 fodder_move_front(field.fodderL, field.fodder2);
1003 } else {
1004 fodder_move_front(field.opFodder, field.fodder2);
1005 }
1006 }
1007 }
1008 // Then try "foo" -> foo.
1009 if (field.kind == ObjectField::FIELD_STR) {
1010 if (auto *lit = dynamic_cast<LiteralString *>(field.expr1)) {
1011 if (isIdentifier(lit->value)) {
1012 field.kind = ObjectField::FIELD_ID;
1013 field.id = alloc.makeIdentifier(lit->value);
1014 field.fodder1 = lit->openFodder;
1015 field.expr1 = nullptr;
1016 }
1017 }
1018 }
1019 }
1020 FmtPass::visit(expr);
1021 }
1022 };
1023
1024 /// Add newlines inside complex structures (arrays, objects etc.).
1025 ///
1026 /// The main principle is that a structure can either be:
1027 /// * expanded and contain newlines in all the designated places
1028 /// * unexpanded and contain newlines in none of the designated places
1029 ///
1030 /// It only looks shallowly at the AST nodes, so there may be some newlines deeper that
1031 /// don't affect expanding. For example:
1032 /// [{
1033 /// 'a': 'b',
1034 /// 'c': 'd',
1035 /// }]
1036 /// The outer array can stay unexpanded, because there are no newlines between
1037 /// the square brackets and the braces.
1038 class FixNewlines : public FmtPass {
1039 using FmtPass::visit;
1040
1041 bool shouldExpand(const Array *array)
1042 {
1043 for (const auto &elem : array->elements) {
1044 if (countNewlines(open_fodder(elem.expr)) > 0) {
1045 return true;
1046 }
1047 }
1048 if (countNewlines(array->closeFodder) > 0) {
1049 return true;
1050 }
1051 return false;
1052 }
1053
1054 void expand(Array *array)
1055 {
1056 for (auto &elem : array->elements) {
1057 ensureCleanNewline(open_fodder(elem.expr));
1058 }
1059 ensureCleanNewline(array->closeFodder);
1060 }
1061
1062 Fodder &objectFieldOpenFodder(ObjectField &field)
1063 {
1064 if (field.kind == ObjectField::Kind::FIELD_STR) {
1065 return field.expr1->openFodder;
1066 }
1067 return field.fodder1;
1068 }
1069
1070 bool shouldExpand(Object *object)
1071 {
1072 for (auto &field : object->fields) {
1073 if (countNewlines(objectFieldOpenFodder(field)) > 0) {
1074 return true;
1075 }
1076 }
1077 if (countNewlines(object->closeFodder) > 0) {
1078 return true;
1079 }
1080 return false;
1081 }
1082
1083 void expand(Object *object)
1084 {
1085 for (auto &field : object->fields) {
1086 ensureCleanNewline(objectFieldOpenFodder(field));
1087 }
1088 ensureCleanNewline(object->closeFodder);
1089 }
1090
1091 bool shouldExpand(Local *local)
1092 {
1093 for (auto &bind : local->binds) {
1094 if (countNewlines(bind.varFodder) > 0) {
1095 return true;
1096 }
1097 }
1098 return false;
1099 }
1100
1101 void expand(Local *local)
1102 {
1103 bool first = true;
1104 for (auto &bind : local->binds) {
1105 if (!first) {
1106 ensureCleanNewline(bind.varFodder);
1107 }
1108 first = false;
1109 }
1110 }
1111
1112 bool shouldExpand(ArrayComprehension *comp)
1113 {
1114 if (countNewlines(open_fodder(comp->body)) > 0) {
1115 return true;
1116 }
1117 for (auto &spec : comp->specs) {
1118 if (countNewlines(spec.openFodder) > 0) {
1119 return true;
1120 }
1121 }
1122 if (countNewlines(comp->closeFodder) > 0) {
1123 return true;
1124 }
1125 return false;
1126 }
1127
1128 void expand(ArrayComprehension *comp)
1129 {
1130 ensureCleanNewline(open_fodder(comp->body));
1131 for (auto &spec : comp->specs) {
1132 ensureCleanNewline(spec.openFodder);
1133 }
1134 ensureCleanNewline(comp->closeFodder);
1135 }
1136
1137 bool shouldExpand(ObjectComprehension *comp)
1138 {
1139 for (auto &field : comp->fields) {
1140 if (countNewlines(objectFieldOpenFodder(field)) > 0) {
1141 return true;
1142 }
1143 }
1144 for (auto &spec : comp->specs) {
1145 if (countNewlines(spec.openFodder) > 0) {
1146 return true;
1147 }
1148 }
1149 if (countNewlines(comp->closeFodder) > 0) {
1150 return true;
1151 }
1152 return false;
1153 }
1154
1155 void expand(ObjectComprehension *comp)
1156 {
1157 for (auto &field : comp->fields) {
1158 ensureCleanNewline(objectFieldOpenFodder(field));
1159 }
1160 for (auto &spec : comp->specs) {
1161 ensureCleanNewline(spec.openFodder);
1162 }
1163 ensureCleanNewline(comp->closeFodder);
1164 }
1165
1166 bool shouldExpand(Parens *parens)
1167 {
1168 return countNewlines(open_fodder(parens->expr)) > 0 ||
1169 countNewlines(parens->closeFodder) > 0;
1170 }
1171
1172 void expand(Parens *parens)
1173 {
1174 ensureCleanNewline(open_fodder(parens->expr));
1175 ensureCleanNewline(parens->closeFodder);
1176 }
1177
1178 Fodder &argParamOpenFodder(ArgParam &param)
1179 {
1180 if (param.id != nullptr) {
1181 return param.idFodder;
1182 } else if (param.expr != nullptr) {
1183 return open_fodder(param.expr);
1184 } else {
1185 std::cerr << "Invalid ArgParam" << std::endl;
1186 abort();
1187 }
1188 }
1189
1190 // Example:
1191 // f(1, 2,
1192 // 3)
1193 // Should be expanded to:
1194 // f(1,
1195 // 2,
1196 // 3)
1197 bool shouldExpandBetween(ArgParams &params)
1198 {
1199 bool first = true;
1200 for (auto &param : params) {
1201 if (!first && countNewlines(argParamOpenFodder(param)) > 0) {
1202 return true;
1203 }
1204 first = false;
1205 }
1206 return false;
1207 }
1208
1209 void expandBetween(ArgParams &params)
1210 {
1211 bool first = true;
1212 for (auto &param : params) {
1213 if (!first) {
1214 ensureCleanNewline(argParamOpenFodder(param));
1215 }
1216 first = false;
1217 }
1218 }
1219
1220 // Example:
1221 // foo(
1222 // 1, 2, 3)
1223 // Should be expanded to:
1224 // foo(
1225 // 1, 2, 3
1226 // )
1227 bool shouldExpandNearParens(ArgParams &params, Fodder &fodder_r)
1228 {
1229 if (params.empty()) {
1230 return false;
1231 }
1232 auto &argFodder = argParamOpenFodder(params.front());
1233 return countNewlines(fodder_r) > 0 || countNewlines(argFodder) > 0;
1234 }
1235
1236 void expandNearParens(ArgParams &params, Fodder &fodder_r)
1237 {
1238 if (!params.empty()) {
1239 ensureCleanNewline(argParamOpenFodder(params.front()));
1240 }
1241 ensureCleanNewline(fodder_r);
1242 }
1243
1244 public:
1245 FixNewlines(Allocator &alloc, const FmtOpts &opts) : FmtPass(alloc, opts) {}
1246
1247 template <class T>
1248 void simpleExpandingVisit(T *expr)
1249 {
1250 if (shouldExpand(expr)) {
1251 expand(expr);
1252 }
1253 FmtPass::visit(expr);
1254 }
1255
1256 void visit(Array *array)
1257 {
1258 simpleExpandingVisit(array);
1259 }
1260
1261 void visit(Object *object)
1262 {
1263 simpleExpandingVisit(object);
1264 }
1265
1266 void visit(Local *local)
1267 {
1268 simpleExpandingVisit(local);
1269 }
1270
1271 void visit(ArrayComprehension *comp)
1272 {
1273 simpleExpandingVisit(comp);
1274 }
1275
1276 void visit(ObjectComprehension *comp)
1277 {
1278 simpleExpandingVisit(comp);
1279 }
1280
1281 void visit(Parens *parens)
1282 {
1283 simpleExpandingVisit(parens);
1284 }
1285
1286 void params(Fodder &fodder_l, ArgParams &params, Fodder &fodder_r)
1287 {
1288 if (shouldExpandBetween(params)) {
1289 expandBetween(params);
1290 }
1291
1292 if (shouldExpandNearParens(params, fodder_r)) {
1293 expandNearParens(params, fodder_r);
1294 }
1295
1296 FmtPass::params(fodder_l, params, fodder_r);
1297 }
1298 };
1299
1300 class FixIndentation {
1301 FmtOpts opts;
1302 unsigned column;
1303
1304 public:
1305 FixIndentation(const FmtOpts &opts) : opts(opts), column(0) {}
1306
1307 /* Set the indentation on the fodder elements, adjust column counter as if it was printed.
1308 * \param fodder The fodder to pretend to print.
1309 * \param space_before Whether a space should be printed before any other output.
1310 * \param separate_token If the last fodder was an interstitial, whether a space should follow
1311 * it.
1312 * \param all_but_last_indent New indentation value for all but final fodder element.
1313 * \param last_indent New indentation value for the final fodder element.
1314 */
1315 void fill(Fodder &fodder, bool space_before, bool separate_token, unsigned all_but_last_indent,
1316 unsigned last_indent)
1317 {
1318 setIndents(fodder, all_but_last_indent, last_indent);
1319 fodder_count(column, fodder, space_before, separate_token);
1320 }
1321
1322 void fill(Fodder &fodder, bool space_before, bool separate_token, unsigned indent)
1323 {
1324 fill(fodder, space_before, separate_token, indent, indent);
1325 }
1326
1327 /* This struct is the representation of the indentation level. The field lineUp is what is
1328 * generally used to indent after a new line. The field base is used to help derive a new
1329 * Indent struct when the indentation level increases. lineUp is generally > base.
1330 *
1331 * In the following case (where spaces are replaced with underscores):
1332 * ____foobar(1,
1333 * ___________2)
1334 *
1335 * At the AST representing the 2, the indent has base == 4 and lineUp == 11.
1336 */
1337 struct Indent {
1338 unsigned base;
1339 unsigned lineUp;
1340 Indent(unsigned base, unsigned line_up) : base(base), lineUp(line_up) {}
1341 };
1342
1343 /** Calculate the indentation of sub-expressions.
1344 *
1345 * If the first sub-expression is on the same line as the current node, then subsequent
1346 * ones will be lined up, otherwise subsequent ones will be on the next line indented
1347 * by 'indent'.
1348 */
1349 Indent newIndent(const Fodder &first_fodder, const Indent &old, unsigned line_up)
1350 {
1351 if (first_fodder.size() == 0 || first_fodder[0].kind == FodderElement::INTERSTITIAL) {
1352 return Indent(old.base, line_up);
1353 } else {
1354 // Reset
1355 return Indent(old.base + opts.indent, old.base + opts.indent);
1356 }
1357 }
1358
1359 /** Calculate the indentation of sub-expressions.
1360 *
1361 * If the first sub-expression is on the same line as the current node, then subsequent
1362 * ones will be lined up and further indentations in their subexpressions will be based from
1363 * this column.
1364 */
1365 Indent newIndentStrong(const Fodder &first_fodder, const Indent &old, unsigned line_up)
1366 {
1367 if (first_fodder.size() == 0 || first_fodder[0].kind == FodderElement::INTERSTITIAL) {
1368 return Indent(line_up, line_up);
1369 } else {
1370 // Reset
1371 return Indent(old.base + opts.indent, old.base + opts.indent);
1372 }
1373 }
1374
1375 /** Calculate the indentation of sub-expressions.
1376 *
1377 * If the first sub-expression is on the same line as the current node, then subsequent
1378 * ones will be lined up, otherwise subseqeuent ones will be on the next line with no
1379 * additional indent.
1380 */
1381 Indent align(const Fodder &first_fodder, const Indent &old, unsigned line_up)
1382 {
1383 if (first_fodder.size() == 0 || first_fodder[0].kind == FodderElement::INTERSTITIAL) {
1384 return Indent(old.base, line_up);
1385 } else {
1386 // Reset
1387 return old;
1388 }
1389 }
1390
1391 /** Calculate the indentation of sub-expressions.
1392 *
1393 * If the first sub-expression is on the same line as the current node, then subsequent
1394 * ones will be lined up and further indentations in their subexpressions will be based from
1395 * this column. Otherwise, subseqeuent ones will be on the next line with no
1396 * additional indent.
1397 */
1398 Indent alignStrong(const Fodder &first_fodder, const Indent &old, unsigned line_up)
1399 {
1400 if (first_fodder.size() == 0 || first_fodder[0].kind == FodderElement::INTERSTITIAL) {
1401 return Indent(line_up, line_up);
1402 } else {
1403 // Reset
1404 return old;
1405 }
1406 }
1407
1408 /* Set indentation values within the fodder elements.
1409 *
1410 * The last one gets a special indentation value, all the others are set to the same thing.
1411 */
1412 void setIndents(Fodder &fodder, unsigned all_but_last_indent, unsigned last_indent)
1413 {
1414 // First count how many there are.
1415 unsigned count = 0;
1416 for (const auto &f : fodder) {
1417 if (f.kind != FodderElement::INTERSTITIAL)
1418 count++;
1419 }
1420 // Now set the indents.
1421 unsigned i = 0;
1422 for (auto &f : fodder) {
1423 if (f.kind != FodderElement::INTERSTITIAL) {
1424 if (i + 1 < count) {
1425 f.indent = all_but_last_indent;
1426 } else {
1427 assert(i == count - 1);
1428 f.indent = last_indent;
1429 }
1430 i++;
1431 }
1432 }
1433 }
1434
1435 /** Indent comprehension specs.
1436 * \param indent The indentation level.
1437 */
1438 void specs(std::vector<ComprehensionSpec> &specs, const Indent &indent)
1439 {
1440 for (auto &spec : specs) {
1441 fill(spec.openFodder, true, true, indent.lineUp);
1442 switch (spec.kind) {
1443 case ComprehensionSpec::FOR: {
1444 column += 3; // for
1445 fill(spec.varFodder, true, true, indent.lineUp);
1446 column += spec.var->name.length();
1447 fill(spec.inFodder, true, true, indent.lineUp);
1448 column += 2; // in
1449 Indent new_indent = newIndent(open_fodder(spec.expr), indent, column);
1450 expr(spec.expr, new_indent, true);
1451 } break;
1452
1453 case ComprehensionSpec::IF: {
1454 column += 2; // if
1455 Indent new_indent = newIndent(open_fodder(spec.expr), indent, column);
1456 expr(spec.expr, new_indent, true);
1457 } break;
1458 }
1459 }
1460 }
1461
1462 void params(Fodder &fodder_l, ArgParams &params, bool trailing_comma, Fodder &fodder_r,
1463 const Indent &indent)
1464 {
1465 fill(fodder_l, false, false, indent.lineUp, indent.lineUp);
1466 column++; // (
1467 const Fodder &first_inside = params.size() == 0 ? fodder_r : params[0].idFodder;
1468
1469 Indent new_indent = newIndent(first_inside, indent, column);
1470 bool first = true;
1471 for (auto &param : params) {
1472 if (!first)
1473 column++; // ','
1474 fill(param.idFodder, !first, true, new_indent.lineUp);
1475 column += param.id->name.length();
1476 if (param.expr != nullptr) {
1477 // default arg, no spacing: x=e
1478 fill(param.eqFodder, false, false, new_indent.lineUp);
1479 column++;
1480 expr(param.expr, new_indent, false);
1481 }
1482 fill(param.commaFodder, false, false, new_indent.lineUp);
1483 first = false;
1484 }
1485 if (trailing_comma)
1486 column++;
1487 fill(fodder_r, false, false, new_indent.lineUp, indent.lineUp);
1488 column++; // )
1489 }
1490
1491 void fieldParams(ObjectField &field, const Indent &indent)
1492 {
1493 if (field.methodSugar) {
1494 params(field.fodderL, field.params, field.trailingComma, field.fodderR, indent);
1495 }
1496 }
1497
1498 /** Indent fields within an object.
1499 *
1500 * \params fields
1501 * \param indent Indent of the first field.
1502 * \param space_before
1503 */
1504 void fields(ObjectFields &fields, const Indent &indent, bool space_before)
1505 {
1506 unsigned new_indent = indent.lineUp;
1507 bool first = true;
1508 for (auto &field : fields) {
1509 if (!first)
1510 column++; // ','
1511
1512 switch (field.kind) {
1513 case ObjectField::LOCAL: {
1514 fill(field.fodder1, !first || space_before, true, indent.lineUp);
1515 column += 5; // local
1516 fill(field.fodder2, true, true, indent.lineUp);
1517 column += field.id->name.length();
1518 fieldParams(field, indent);
1519 fill(field.opFodder, true, true, indent.lineUp);
1520 column++; // =
1521 Indent new_indent2 = newIndent(open_fodder(field.expr2), indent, column);
1522 expr(field.expr2, new_indent2, true);
1523 } break;
1524
1525 case ObjectField::FIELD_ID:
1526 case ObjectField::FIELD_STR:
1527 case ObjectField::FIELD_EXPR: {
1528 if (field.kind == ObjectField::FIELD_ID) {
1529 fill(field.fodder1, !first || space_before, true, new_indent);
1530 column += field.id->name.length();
1531
1532 } else if (field.kind == ObjectField::FIELD_STR) {
1533 expr(field.expr1, indent, !first || space_before);
1534
1535 } else if (field.kind == ObjectField::FIELD_EXPR) {
1536 fill(field.fodder1, !first || space_before, true, new_indent);
1537 column++; // [
1538 expr(field.expr1, indent, false);
1539 fill(field.fodder2, false, false, new_indent);
1540 column++; // ]
1541 }
1542
1543 fieldParams(field, indent);
1544
1545 fill(field.opFodder, false, false, new_indent);
1546
1547 if (field.superSugar)
1548 column++;
1549 switch (field.hide) {
1550 case ObjectField::INHERIT: column += 1; break;
1551 case ObjectField::HIDDEN: column += 2; break;
1552 case ObjectField::VISIBLE: column += 3; break;
1553 }
1554 Indent new_indent2 = newIndent(open_fodder(field.expr2), indent, column);
1555 expr(field.expr2, new_indent2, true);
1556
1557 } break;
1558
1559 case ObjectField::ASSERT: {
1560 fill(field.fodder1, !first || space_before, true, new_indent);
1561 column += 6; // assert
1562 // + 1 for the space after the assert
1563 Indent new_indent2 = newIndent(open_fodder(field.expr2), indent, column + 1);
1564 expr(field.expr2, indent, true);
1565 if (field.expr3 != nullptr) {
1566 fill(field.opFodder, true, true, new_indent2.lineUp);
1567 column++; // ":"
1568 expr(field.expr3, new_indent2, true);
1569 }
1570 } break;
1571 }
1572
1573 first = false;
1574 fill(field.commaFodder, false, false, new_indent);
1575 }
1576 }
1577
1578 /** Does the given fodder contain at least one new line? */
1579 bool hasNewLines(const Fodder &fodder)
1580 {
1581 for (const auto &f : fodder) {
1582 if (f.kind != FodderElement::INTERSTITIAL)
1583 return true;
1584 }
1585 return false;
1586 }
1587
1588 /** Get the first fodder from an ArgParam. */
1589 const Fodder &argParamFirstFodder(const ArgParam &ap)
1590 {
1591 if (ap.id != nullptr)
1592 return ap.idFodder;
1593 return open_fodder(ap.expr);
1594 }
1595
1596 /** Reindent an expression.
1597 *
1598 * \param ast_ The ast to reindent.
1599 * \param indent Beginning of the line.
1600 * \param space_before As defined in the pretty-printer.
1601 */
1602 void expr(AST *ast_, const Indent &indent, bool space_before)
1603 {
1604 bool separate_token = !left_recursive(ast_);
1605
1606 fill(ast_->openFodder, space_before, separate_token, indent.lineUp);
1607
1608 if (auto *ast = dynamic_cast<Apply *>(ast_)) {
1609 const Fodder &init_fodder = open_fodder(ast->target);
1610 Indent new_indent = align(init_fodder, indent, column + (space_before ? 1 : 0));
1611 expr(ast->target, new_indent, space_before);
1612 fill(ast->fodderL, false, false, new_indent.lineUp);
1613 column++; // (
1614 const Fodder &first_fodder =
1615 ast->args.size() == 0 ? ast->fodderR : argParamFirstFodder(ast->args[0]);
1616 bool strong_indent = false;
1617 // Need to use strong indent if any of the
1618 // arguments (except the first) are preceded by newlines.
1619 bool first = true;
1620 for (auto &arg : ast->args) {
1621 if (first) {
1622 // Skip first element.
1623 first = false;
1624 continue;
1625 }
1626 if (hasNewLines(argParamFirstFodder(arg)))
1627 strong_indent = true;
1628 }
1629
1630 Indent arg_indent = strong_indent ? newIndentStrong(first_fodder, indent, column)
1631 : newIndent(first_fodder, indent, column);
1632 first = true;
1633 for (auto &arg : ast->args) {
1634 if (!first)
1635 column++; // ","
1636
1637 bool space = !first;
1638 if (arg.id != nullptr) {
1639 fill(arg.idFodder, space, false, arg_indent.lineUp);
1640 column += arg.id->name.length();
1641 space = false;
1642 column++; // "="
1643 }
1644 expr(arg.expr, arg_indent, space);
1645 fill(arg.commaFodder, false, false, arg_indent.lineUp);
1646 first = false;
1647 }
1648 if (ast->trailingComma)
1649 column++; // ","
1650 fill(ast->fodderR, false, false, arg_indent.lineUp, indent.base);
1651 column++; // )
1652 if (ast->tailstrict) {
1653 fill(ast->tailstrictFodder, true, true, indent.base);
1654 column += 10; // tailstrict
1655 }
1656
1657 } else if (auto *ast = dynamic_cast<ApplyBrace *>(ast_)) {
1658 const Fodder &init_fodder = open_fodder(ast->left);
1659 Indent new_indent = align(init_fodder, indent, column + (space_before ? 1 : 0));
1660 expr(ast->left, new_indent, space_before);
1661 expr(ast->right, new_indent, true);
1662
1663 } else if (auto *ast = dynamic_cast<Array *>(ast_)) {
1664 column++; // '['
1665 // First fodder element exists and is a newline
1666 const Fodder &first_fodder =
1667 ast->elements.size() > 0 ? open_fodder(ast->elements[0].expr) : ast->closeFodder;
1668 unsigned new_column = column + (opts.padArrays ? 1 : 0);
1669 bool strong_indent = false;
1670 // Need to use strong indent if there are not newlines before any of the sub-expressions
1671 bool first = true;
1672 for (auto &el : ast->elements) {
1673 if (first) {
1674 first = false;
1675 continue;
1676 }
1677 if (hasNewLines(open_fodder(el.expr)))
1678 strong_indent = true;
1679 }
1680
1681 Indent new_indent = strong_indent ? newIndentStrong(first_fodder, indent, new_column)
1682 : newIndent(first_fodder, indent, new_column);
1683
1684 first = true;
1685 for (auto &element : ast->elements) {
1686 if (!first)
1687 column++;
1688 expr(element.expr, new_indent, !first || opts.padArrays);
1689 fill(element.commaFodder, false, false, new_indent.lineUp, new_indent.lineUp);
1690 first = false;
1691 }
1692 if (ast->trailingComma)
1693 column++;
1694
1695 // Handle penultimate newlines from expr.close_fodder if there are any.
1696 fill(ast->closeFodder,
1697 ast->elements.size() > 0,
1698 opts.padArrays,
1699 new_indent.lineUp,
1700 indent.base);
1701 column++; // ']'
1702
1703 } else if (auto *ast = dynamic_cast<ArrayComprehension *>(ast_)) {
1704 column++; // [
1705 Indent new_indent =
1706 newIndent(open_fodder(ast->body), indent, column + (opts.padArrays ? 1 : 0));
1707 expr(ast->body, new_indent, opts.padArrays);
1708 fill(ast->commaFodder, false, false, new_indent.lineUp);
1709 if (ast->trailingComma)
1710 column++; // ','
1711 specs(ast->specs, new_indent);
1712 fill(ast->closeFodder, true, opts.padArrays, new_indent.lineUp, indent.base);
1713 column++; // ]
1714
1715 } else if (auto *ast = dynamic_cast<Assert *>(ast_)) {
1716 column += 6; // assert
1717 // + 1 for the space after the assert
1718 Indent new_indent = newIndent(open_fodder(ast->cond), indent, column + 1);
1719 expr(ast->cond, new_indent, true);
1720 if (ast->message != nullptr) {
1721 fill(ast->colonFodder, true, true, new_indent.lineUp);
1722 column++; // ":"
1723 expr(ast->message, new_indent, true);
1724 }
1725 fill(ast->semicolonFodder, false, false, new_indent.lineUp);
1726 column++; // ";"
1727 expr(ast->rest, indent, true);
1728
1729 } else if (auto *ast = dynamic_cast<Binary *>(ast_)) {
1730 const Fodder &first_fodder = open_fodder(ast->left);
1731
1732 // Need to use strong indent in the case of
1733 /*
1734 A
1735 + B
1736 or
1737 A +
1738 B
1739 */
1740 bool strong_indent = hasNewLines(ast->opFodder) || hasNewLines(open_fodder(ast->right));
1741
1742 unsigned inner_column = column + (space_before ? 1 : 0);
1743 Indent new_indent = strong_indent ? alignStrong(first_fodder, indent, inner_column)
1744 : align(first_fodder, indent, inner_column);
1745 expr(ast->left, new_indent, space_before);
1746 fill(ast->opFodder, true, true, new_indent.lineUp);
1747 column += bop_string(ast->op).length();
1748 // Don't calculate a new indent for here, because we like being able to do:
1749 // true &&
1750 // true &&
1751 // true
1752 expr(ast->right, new_indent, true);
1753
1754 } else if (auto *ast = dynamic_cast<BuiltinFunction *>(ast_)) {
1755 column += 11; // "/* builtin "
1756 column += ast->body->name.length();
1757 column += 8; // " */ null"
1758
1759 } else if (auto *ast = dynamic_cast<Conditional *>(ast_)) {
1760 column += 2; // if
1761 Indent cond_indent = newIndent(open_fodder(ast->cond), indent, column + 1);
1762 expr(ast->cond, cond_indent, true);
1763 fill(ast->thenFodder, true, true, indent.base);
1764 column += 4; // then
1765 Indent true_indent = newIndent(open_fodder(ast->branchTrue), indent, column + 1);
1766 expr(ast->branchTrue, true_indent, true);
1767 if (ast->branchFalse != nullptr) {
1768 fill(ast->elseFodder, true, true, indent.base);
1769 column += 4; // else
1770 Indent false_indent = newIndent(open_fodder(ast->branchFalse), indent, column + 1);
1771 expr(ast->branchFalse, false_indent, true);
1772 }
1773
1774 } else if (dynamic_cast<Dollar *>(ast_)) {
1775 column++; // $
1776
1777 } else if (auto *ast = dynamic_cast<Error *>(ast_)) {
1778 column += 5; // error
1779 Indent new_indent = newIndent(open_fodder(ast->expr), indent, column + 1);
1780 expr(ast->expr, new_indent, true);
1781
1782 } else if (auto *ast = dynamic_cast<Function *>(ast_)) {
1783 column += 8; // function
1784 params(ast->parenLeftFodder,
1785 ast->params,
1786 ast->trailingComma,
1787 ast->parenRightFodder,
1788 indent);
1789 Indent new_indent = newIndent(open_fodder(ast->body), indent, column + 1);
1790 expr(ast->body, new_indent, true);
1791
1792 } else if (auto *ast = dynamic_cast<Import *>(ast_)) {
1793 column += 6; // import
1794 Indent new_indent = newIndent(open_fodder(ast->file), indent, column + 1);
1795 expr(ast->file, new_indent, true);
1796
1797 } else if (auto *ast = dynamic_cast<Importstr *>(ast_)) {
1798 column += 9; // importstr
1799 Indent new_indent = newIndent(open_fodder(ast->file), indent, column + 1);
1800 expr(ast->file, new_indent, true);
1801
1802 } else if (auto *ast = dynamic_cast<Importbin *>(ast_)) {
1803 column += 9; // importbin
1804 Indent new_indent = newIndent(open_fodder(ast->file), indent, column + 1);
1805 expr(ast->file, new_indent, true);
1806
1807 } else if (auto *ast = dynamic_cast<InSuper *>(ast_)) {
1808 expr(ast->element, indent, space_before);
1809 fill(ast->inFodder, true, true, indent.lineUp);
1810 column += 2; // in
1811 fill(ast->superFodder, true, true, indent.lineUp);
1812 column += 5; // super
1813
1814 } else if (auto *ast = dynamic_cast<Index *>(ast_)) {
1815 expr(ast->target, indent, space_before);
1816 fill(ast->dotFodder, false, false, indent.lineUp);
1817 if (ast->id != nullptr) {
1818 Indent new_indent = newIndent(ast->idFodder, indent, column);
1819 column++; // "."
1820 fill(ast->idFodder, false, false, new_indent.lineUp);
1821 column += ast->id->name.length();
1822 } else {
1823 column++; // "["
1824 if (ast->isSlice) {
1825 Indent new_indent(0, 0);
1826 if (ast->index != nullptr) {
1827 new_indent = newIndent(open_fodder(ast->index), indent, column);
1828 expr(ast->index, new_indent, false);
1829 }
1830 if (ast->end != nullptr) {
1831 new_indent = newIndent(ast->endColonFodder, indent, column);
1832 fill(ast->endColonFodder, false, false, new_indent.lineUp);
1833 column++; // ":"
1834 expr(ast->end, new_indent, false);
1835 }
1836 if (ast->step != nullptr) {
1837 if (ast->end == nullptr) {
1838 new_indent = newIndent(ast->endColonFodder, indent, column);
1839 fill(ast->endColonFodder, false, false, new_indent.lineUp);
1840 column++; // ":"
1841 }
1842 fill(ast->stepColonFodder, false, false, new_indent.lineUp);
1843 column++; // ":"
1844 expr(ast->step, new_indent, false);
1845 }
1846 if (ast->index == nullptr && ast->end == nullptr && ast->step == nullptr) {
1847 new_indent = newIndent(ast->endColonFodder, indent, column);
1848 fill(ast->endColonFodder, false, false, new_indent.lineUp);
1849 column++; // ":"
1850 }
1851 } else {
1852 Indent new_indent = newIndent(open_fodder(ast->index), indent, column);
1853 expr(ast->index, new_indent, false);
1854 fill(ast->idFodder, false, false, new_indent.lineUp, indent.base);
1855 }
1856 column++; // "]"
1857 }
1858
1859 } else if (auto *ast = dynamic_cast<Local *>(ast_)) {
1860 column += 5; // local
1861 assert(ast->binds.size() > 0);
1862 bool first = true;
1863 Indent new_indent = newIndent(ast->binds[0].varFodder, indent, column + 1);
1864 for (auto &bind : ast->binds) {
1865 if (!first)
1866 column++; // ','
1867 first = false;
1868 fill(bind.varFodder, true, true, new_indent.lineUp);
1869 column += bind.var->name.length();
1870 if (bind.functionSugar) {
1871 params(bind.parenLeftFodder,
1872 bind.params,
1873 bind.trailingComma,
1874 bind.parenRightFodder,
1875 new_indent);
1876 }
1877 fill(bind.opFodder, true, true, new_indent.lineUp);
1878 column++; // '='
1879 Indent new_indent2 = newIndent(open_fodder(bind.body), new_indent, column + 1);
1880 expr(bind.body, new_indent2, true);
1881 fill(bind.closeFodder, false, false, new_indent2.lineUp, indent.base);
1882 }
1883 column++; // ';'
1884 expr(ast->body, indent, true);
1885
1886 } else if (auto *ast = dynamic_cast<LiteralBoolean *>(ast_)) {
1887 column += (ast->value ? 4 : 5);
1888
1889 } else if (auto *ast = dynamic_cast<LiteralNumber *>(ast_)) {
1890 column += ast->originalString.length();
1891
1892 } else if (auto *ast = dynamic_cast<LiteralString *>(ast_)) {
1893 assert(ast->tokenKind != LiteralString::RAW_DESUGARED);
1894 if (ast->tokenKind == LiteralString::DOUBLE) {
1895 column += 2 + ast->value.length(); // Include quotes
1896 } else if (ast->tokenKind == LiteralString::SINGLE) {
1897 column += 2 + ast->value.length(); // Include quotes
1898 } else if (ast->tokenKind == LiteralString::BLOCK) {
1899 ast->blockIndent = std::string(indent.base + opts.indent, ' ');
1900 ast->blockTermIndent = std::string(indent.base, ' ');
1901 column = indent.base; // blockTermIndent
1902 column += 3; // "|||"
1903 } else if (ast->tokenKind == LiteralString::VERBATIM_SINGLE) {
1904 column += 3; // Include @, start and end quotes
1905 for (const char32_t *cp = ast->value.c_str(); *cp != U'\0'; ++cp) {
1906 if (*cp == U'\'') {
1907 column += 2;
1908 } else {
1909 column += 1;
1910 }
1911 }
1912 } else if (ast->tokenKind == LiteralString::VERBATIM_DOUBLE) {
1913 column += 3; // Include @, start and end quotes
1914 for (const char32_t *cp = ast->value.c_str(); *cp != U'\0'; ++cp) {
1915 if (*cp == U'"') {
1916 column += 2;
1917 } else {
1918 column += 1;
1919 }
1920 }
1921 }
1922
1923 } else if (dynamic_cast<LiteralNull *>(ast_)) {
1924 column += 4; // null
1925
1926 } else if (auto *ast = dynamic_cast<Object *>(ast_)) {
1927 column++; // '{'
1928 const Fodder &first_fodder = ast->fields.size() == 0
1929 ? ast->closeFodder
1930 : ast->fields[0].kind == ObjectField::FIELD_STR
1931 ? open_fodder(ast->fields[0].expr1)
1932 : ast->fields[0].fodder1;
1933 Indent new_indent = newIndent(first_fodder, indent, column + (opts.padObjects ? 1 : 0));
1934
1935 fields(ast->fields, new_indent, opts.padObjects);
1936 if (ast->trailingComma)
1937 column++;
1938 fill(ast->closeFodder,
1939 ast->fields.size() > 0,
1940 opts.padObjects,
1941 new_indent.lineUp,
1942 indent.base);
1943 column++; // '}'
1944
1945 } else if (auto *ast = dynamic_cast<DesugaredObject *>(ast_)) {
1946 // No fodder but need to recurse and maintain column counter.
1947 column++; // '{'
1948 for (AST *assert : ast->asserts) {
1949 column += 6; // assert
1950 expr(assert, indent, true);
1951 column++; // ','
1952 }
1953 for (auto &field : ast->fields) {
1954 column++; // '['
1955 expr(field.name, indent, false);
1956 column++; // ']'
1957 switch (field.hide) {
1958 case ObjectField::INHERIT: column += 1; break;
1959 case ObjectField::HIDDEN: column += 2; break;
1960 case ObjectField::VISIBLE: column += 3; break;
1961 }
1962 expr(field.body, indent, true);
1963 }
1964 column++; // '}'
1965
1966 } else if (auto *ast = dynamic_cast<ObjectComprehension *>(ast_)) {
1967 column++; // '{'
1968 unsigned start_column = column;
1969 const Fodder &first_fodder = ast->fields.size() == 0
1970 ? ast->closeFodder
1971 : ast->fields[0].kind == ObjectField::FIELD_STR
1972 ? open_fodder(ast->fields[0].expr1)
1973 : ast->fields[0].fodder1;
1974 Indent new_indent =
1975 newIndent(first_fodder, indent, start_column + (opts.padObjects ? 1 : 0));
1976
1977 fields(ast->fields, new_indent, opts.padObjects);
1978 if (ast->trailingComma)
1979 column++; // ','
1980 specs(ast->specs, new_indent);
1981 fill(ast->closeFodder, true, opts.padObjects, new_indent.lineUp, indent.base);
1982 column++; // '}'
1983
1984 } else if (auto *ast = dynamic_cast<ObjectComprehensionSimple *>(ast_)) {
1985 column++; // '{'
1986 column++; // '['
1987 expr(ast->field, indent, false);
1988 column++; // ']'
1989 column++; // ':'
1990 expr(ast->value, indent, true);
1991 column += 5; // " for "
1992 column += ast->id->name.length();
1993 column += 3; // " in"
1994 expr(ast->array, indent, true);
1995 column++; // '}'
1996
1997 } else if (auto *ast = dynamic_cast<Parens *>(ast_)) {
1998 column++; // (
1999 Indent new_indent = newIndentStrong(open_fodder(ast->expr), indent, column);
2000 expr(ast->expr, new_indent, false);
2001 fill(ast->closeFodder, false, false, new_indent.lineUp, indent.base);
2002 column++; // )
2003
2004 } else if (dynamic_cast<const Self *>(ast_)) {
2005 column += 4; // self
2006
2007 } else if (auto *ast = dynamic_cast<SuperIndex *>(ast_)) {
2008 column += 5; // super
2009 fill(ast->dotFodder, false, false, indent.lineUp);
2010 if (ast->id != nullptr) {
2011 column++; // ".";
2012 Indent new_indent = newIndent(ast->idFodder, indent, column);
2013 fill(ast->idFodder, false, false, new_indent.lineUp);
2014 column += ast->id->name.length();
2015 } else {
2016 column++; // "[";
2017 Indent new_indent = newIndent(open_fodder(ast->index), indent, column);
2018 expr(ast->index, new_indent, false);
2019 fill(ast->idFodder, false, false, new_indent.lineUp, indent.base);
2020 column++; // "]";
2021 }
2022
2023 } else if (auto *ast = dynamic_cast<Unary *>(ast_)) {
2024 column += uop_string(ast->op).length();
2025 Indent new_indent = newIndent(open_fodder(ast->expr), indent, column);
2026 if (dynamic_cast<const Dollar *>(left_recursive_deep(ast->expr))) {
2027 expr(ast->expr, new_indent, true);
2028 } else {
2029 expr(ast->expr, new_indent, false);
2030 }
2031
2032 } else if (auto *ast = dynamic_cast<Var *>(ast_)) {
2033 column += ast->id->name.length();
2034
2035 } else {
2036 std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_ << std::endl;
2037 std::abort();
2038 }
2039 }
2040 virtual void file(AST *body, Fodder &final_fodder)
2041 {
2042 expr(body, Indent(0, 0), false);
2043 setIndents(final_fodder, 0, 0);
2044 }
2045 };
2046
2047 /** Sort top-level imports.
2048 *
2049 * Top-level imports are `local x = import 'xxx.jsonnet` expressions
2050 * that go before anything else in the file (more precisely all such imports
2051 * that are either the root of AST or a direct child (body) of a top-level
2052 * import.
2053 *
2054 * Grouping of imports is preserved. Groups of imports are separated by blank
2055 * lines or lines containing comments.
2056 */
2057 class SortImports {
2058 /// Internal representation of an import
2059 struct ImportElem {
2060 ImportElem(UString key, Fodder adjacentFodder, Local::Bind bind)
2061 : key(key), adjacentFodder(adjacentFodder), bind(bind)
2062 {
2063 }
2064
2065 // A key by which the imports should be sorted.
2066 // It's a file path that is imported, represented as UTF-32 codepoints without case folding.
2067 // In particular "Z" < "a", because 'Z' == 90 and 'a' == 97.
2068 UString key;
2069
2070 // Comments adjacent to the import that go after it and that should stay attached
2071 // when imports are reordered.
2072 Fodder adjacentFodder;
2073
2074 // The bind that contains the import
2075 // Satisfies: bind.functionSugar == false && bind.body->type == AST_IMPORT
2076 Local::Bind bind;
2077 bool operator<(const ImportElem &elem) const
2078 {
2079 return key < elem.key;
2080 }
2081 };
2082
2083 typedef std::vector<ImportElem> ImportElems;
2084
2085 Allocator &alloc;
2086
2087 public:
2088 SortImports(Allocator &alloc) : alloc(alloc) {}
2089
2090 /// Get the value by which the imports should be sorted.
2091 UString sortingKey(Import *import)
2092 {
2093 return import->file->value;
2094 }
2095
2096 /// Check if `local` expression is used for importing,
2097 bool isGoodLocal(Local *local)
2098 {
2099 for (const auto &bind : local->binds) {
2100 if (bind.body->type != AST_IMPORT || bind.functionSugar) {
2101 return false;
2102 }
2103 }
2104 return true;
2105 }
2106
2107 Local *goodLocalOrNull(AST *expr)
2108 {
2109 if (auto *local = dynamic_cast<Local *>(expr)) {
2110 return isGoodLocal(local) ? local : nullptr;
2111 } else {
2112 return nullptr;
2113 }
2114 }
2115
2116 /** Split fodder after the first new line / paragraph fodder,
2117 * leaving blank lines after the newline in the second half.
2118 *
2119 * The two returned fodders can be concatenated using concat_fodder to get the original fodder.
2120 *
2121 * It's a heuristic that given two consecutive tokens `prev_token`, `next_token`
2122 * with some fodder between them, decides which part of the fodder logically belongs
2123 * to `prev_token` and which part belongs to the `next_token`.
2124 *
2125 * Example:
2126 * prev_token // prev_token is awesome!
2127 *
2128 * // blah blah
2129 * next_token
2130 *
2131 * In such case "// prev_token is awesome!\n" part of the fodder belongs
2132 * to the `prev_token` and "\n//blah blah\n" to the `next_token`.
2133 */
2134 std::pair<Fodder, Fodder> splitFodder(const Fodder &fodder)
2135 {
2136 Fodder afterPrev, beforeNext;
2137 bool inSecondPart = false;
2138 for (const auto &fodderElem : fodder) {
2139 if (inSecondPart) {
2140 fodder_push_back(beforeNext, fodderElem);
2141 } else {
2142 afterPrev.push_back(fodderElem);
2143 }
2144 if (fodderElem.kind != FodderElement::Kind::INTERSTITIAL && !inSecondPart) {
2145 inSecondPart = true;
2146 if (fodderElem.blanks > 0) {
2147 // If there are any blank lines at the end of afterPrev, move them
2148 // to beforeNext.
2149 afterPrev.back().blanks = 0;
2150 assert(beforeNext.empty());
2151 beforeNext.emplace_back(FodderElement::Kind::LINE_END,
2152 fodderElem.blanks,
2153 fodderElem.indent,
2154 std::vector<std::string>());
2155 }
2156 }
2157 }
2158 return {afterPrev, beforeNext};
2159 }
2160
2161 void sortGroup(ImportElems &imports)
2162 {
2163 // We don't want to change behaviour in such case:
2164 // local foo = "b.jsonnet";
2165 // local foo = "a.jsonnet";
2166 // So we don't change the order when there are shadowed variables.
2167 if (!duplicatedVariables(imports)) {
2168 std::sort(imports.begin(), imports.end());
2169 }
2170 }
2171
2172 ImportElems extractImportElems(const Local::Binds &binds, Fodder after)
2173 {
2174 ImportElems result;
2175 Fodder before = binds.front().varFodder;
2176 for (int i = 0; i < int(binds.size()); ++i) {
2177 const auto &bind = binds[i];
2178 bool last = i == int(binds.size() - 1);
2179 Fodder adjacent, beforeNext;
2180 if (!last) {
2181 auto &next = binds[i + 1];
2182 std::tie(adjacent, beforeNext) = splitFodder(next.varFodder);
2183 } else {
2184 adjacent = after;
2185 }
2186 ensureCleanNewline(adjacent);
2187 Local::Bind newBind = bind;
2188 newBind.varFodder = before;
2189 Import *import = dynamic_cast<Import *>(bind.body);
2190 assert(import != nullptr);
2191 result.emplace_back(sortingKey(import), adjacent, newBind);
2192 before = beforeNext;
2193 }
2194 return result;
2195 }
2196
2197 AST *buildGroupAST(ImportElems &imports, AST *body, const Fodder &groupOpenFodder)
2198 {
2199 for (int i = imports.size() - 1; i >= 0; --i) {
2200 auto &import = imports[i];
2201 Fodder fodder;
2202 if (i == 0) {
2203 fodder = groupOpenFodder;
2204 } else {
2205 fodder = imports[i - 1].adjacentFodder;
2206 }
2207 auto *local =
2208 alloc.make<Local>(LocationRange(), fodder, Local::Binds({import.bind}), body);
2209 body = local;
2210 }
2211
2212 return body;
2213 }
2214
2215 bool duplicatedVariables(const ImportElems &elems)
2216 {
2217 std::set<UString> idents;
2218 for (const auto &elem : elems) {
2219 idents.insert(elem.bind.var->name);
2220 }
2221 return idents.size() < elems.size();
2222 }
2223
2224 /// Check if the import group ends after this local
2225 bool groupEndsAfter(Local *local)
2226 {
2227 Local *next = goodLocalOrNull(local->body);
2228 if (!next) {
2229 return true;
2230 }
2231
2232 bool newlineReached = false;
2233 for (const auto &fodderElem : open_fodder(next)) {
2234 if (newlineReached || fodderElem.blanks > 0) {
2235 return true;
2236 }
2237 if (fodderElem.kind != FodderElement::Kind::INTERSTITIAL) {
2238 newlineReached = true;
2239 }
2240 }
2241 return false;
2242 }
2243
2244 AST *toplevelImport(Local *local, ImportElems &imports, const Fodder &groupOpenFodder)
2245 {
2246 assert(isGoodLocal(local));
2247
2248 Fodder adjacentCommentFodder, beforeNextFodder;
2249 std::tie(adjacentCommentFodder, beforeNextFodder) = splitFodder(open_fodder(local->body));
2250
2251 ensureCleanNewline(adjacentCommentFodder);
2252
2253 ImportElems newImports = extractImportElems(local->binds, adjacentCommentFodder);
2254 imports.insert(imports.end(), newImports.begin(), newImports.end());
2255
2256 if (groupEndsAfter(local)) {
2257 sortGroup(imports);
2258
2259 Fodder afterGroup = imports.back().adjacentFodder;
2260 ensureCleanNewline(beforeNextFodder);
2261 auto nextOpenFodder = concat_fodder(afterGroup, beforeNextFodder);
2262
2263 // Process the code after the current group:
2264 AST *bodyAfterGroup;
2265 Local *next = goodLocalOrNull(local->body);
2266 if (next) {
2267 // Another group of imports
2268 ImportElems nextImports;
2269 bodyAfterGroup = toplevelImport(next, nextImports, nextOpenFodder);
2270 } else {
2271 // Something else
2272 bodyAfterGroup = local->body;
2273 open_fodder(bodyAfterGroup) = nextOpenFodder;
2274 }
2275
2276 return buildGroupAST(imports, bodyAfterGroup, groupOpenFodder);
2277 } else {
2278 assert(beforeNextFodder.empty());
2279 return toplevelImport(dynamic_cast<Local *>(local->body), imports, groupOpenFodder);
2280 }
2281 }
2282
2283 void file(AST *&body)
2284 {
2285 ImportElems imports;
2286 Local *local = goodLocalOrNull(body);
2287 if (local) {
2288 body = toplevelImport(local, imports, open_fodder(local));
2289 }
2290 }
2291 };
2292
2293 std::string jsonnet_fmt(AST *ast, Fodder &final_fodder, const FmtOpts &opts)
2294 {
2295 Allocator alloc;
2296
2297 // Passes to enforce style on the AST.
2298 if (opts.sortImports)
2299 SortImports(alloc).file(ast);
2300 remove_initial_newlines(ast);
2301 if (opts.maxBlankLines > 0)
2302 EnforceMaximumBlankLines(alloc, opts).file(ast, final_fodder);
2303 FixNewlines(alloc, opts).file(ast, final_fodder);
2304 FixTrailingCommas(alloc, opts).file(ast, final_fodder);
2305 FixParens(alloc, opts).file(ast, final_fodder);
2306 FixPlusObject(alloc, opts).file(ast, final_fodder);
2307 NoRedundantSliceColon(alloc, opts).file(ast, final_fodder);
2308 if (opts.stripComments)
2309 StripComments(alloc, opts).file(ast, final_fodder);
2310 else if (opts.stripAllButComments)
2311 StripAllButComments(alloc, opts).file(ast, final_fodder);
2312 else if (opts.stripEverything)
2313 StripEverything(alloc, opts).file(ast, final_fodder);
2314 if (opts.prettyFieldNames)
2315 PrettyFieldNames(alloc, opts).file(ast, final_fodder);
2316 if (opts.stringStyle != 'l')
2317 EnforceStringStyle(alloc, opts).file(ast, final_fodder);
2318 if (opts.commentStyle != 'l')
2319 EnforceCommentStyle(alloc, opts).file(ast, final_fodder);
2320 if (opts.indent > 0)
2321 FixIndentation(opts).file(ast, final_fodder);
2322 remove_extra_trailing_newlines(final_fodder);
2323
2324 std::stringstream ss;
2325 Unparser unparser(ss, opts);
2326 unparser.unparse(ast, false);
2327 unparser.fill_final(final_fodder, true, false);
2328 if (final_fodder.empty() || final_fodder.back().kind == FodderElement::INTERSTITIAL) {
2329 ss << "\n";
2330 }
2331 return ss.str();
2332 }
2333
2334 } // namespace jsonnet::internal