Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / tools / gn / command_format.cc
blob06c5670043fd875529a21b280ed6517e8f3eadab
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <sstream>
7 #include "base/command_line.h"
8 #include "base/files/file_util.h"
9 #include "base/strings/string_split.h"
10 #include "tools/gn/commands.h"
11 #include "tools/gn/filesystem_utils.h"
12 #include "tools/gn/input_file.h"
13 #include "tools/gn/parser.h"
14 #include "tools/gn/scheduler.h"
15 #include "tools/gn/setup.h"
16 #include "tools/gn/source_file.h"
17 #include "tools/gn/tokenizer.h"
19 namespace commands {
21 const char kSwitchDryRun[] = "dry-run";
22 const char kSwitchDumpTree[] = "dump-tree";
23 const char kSwitchInPlace[] = "in-place";
24 const char kSwitchStdin[] = "stdin";
26 const char kFormat[] = "format";
27 const char kFormat_HelpShort[] =
28 "format: Format .gn file.";
29 const char kFormat_Help[] =
30 "gn format [--dump-tree] [--in-place] [--stdin] BUILD.gn\n"
31 "\n"
32 " Formats .gn file to a standard format.\n"
33 "\n"
34 "Arguments\n"
35 " --dry-run\n"
36 " Does not change or output anything, but sets the process exit code\n"
37 " based on whether output would be different than what's on disk.\n"
38 " This is useful for presubmit/lint-type checks.\n"
39 " - Exit code 0: successful format, matches on disk.\n"
40 " - Exit code 1: general failure (parse error, etc.)\n"
41 " - Exit code 2: successful format, but differs from on disk.\n"
42 "\n"
43 " --dump-tree\n"
44 " For debugging only, dumps the parse tree.\n"
45 "\n"
46 " --in-place\n"
47 " Instead of writing the formatted file to stdout, replace the input\n"
48 " file with the formatted output. If no reformatting is required,\n"
49 " the input file will not be touched, and nothing printed.\n"
50 "\n"
51 " --stdin\n"
52 " Read input from stdin (and write to stdout). Not compatible with\n"
53 " --in-place of course.\n"
54 "\n"
55 "Examples\n"
56 " gn format //some/BUILD.gn\n"
57 " gn format some\\BUILD.gn\n"
58 " gn format /abspath/some/BUILD.gn\n"
59 " gn format --stdin\n";
61 namespace {
63 const int kIndentSize = 2;
64 const int kMaximumWidth = 80;
66 const int kPenaltyLineBreak = 500;
67 const int kPenaltyHorizontalSeparation = 100;
68 const int kPenaltyExcess = 10000;
69 const int kPenaltyBrokenLineOnOneLiner = 5000;
71 enum Precedence {
72 kPrecedenceLowest,
73 kPrecedenceAssign,
74 kPrecedenceOr,
75 kPrecedenceAnd,
76 kPrecedenceCompare,
77 kPrecedenceAdd,
78 kPrecedenceUnary,
79 kPrecedenceSuffix,
82 int CountLines(const std::string& str) {
83 std::vector<std::string> lines;
84 base::SplitStringDontTrim(str, '\n', &lines);
85 return static_cast<int>(lines.size());
88 class Printer {
89 public:
90 Printer();
91 ~Printer();
93 void Block(const ParseNode* file);
95 std::string String() const { return output_; }
97 private:
98 // Format a list of values using the given style.
99 enum SequenceStyle {
100 kSequenceStyleList,
101 kSequenceStyleBlock,
102 kSequenceStyleBracedBlock,
105 struct Metrics {
106 Metrics() : first_length(-1), longest_length(-1), multiline(false) {}
107 int first_length;
108 int longest_length;
109 bool multiline;
112 // Add to output.
113 void Print(base::StringPiece str);
115 // Add the current margin (as spaces) to the output.
116 void PrintMargin();
118 void TrimAndPrintToken(const Token& token);
120 // End the current line, flushing end of line comments.
121 void Newline();
123 // Remove trailing spaces from the current line.
124 void Trim();
126 // Whether there's a blank separator line at the current position.
127 bool HaveBlankLine();
129 // Flag assignments to sources, deps, etc. to make their RHSs multiline.
130 void AnnotatePreferredMultilineAssignment(const BinaryOpNode* binop);
132 // Heuristics to decide if there should be a blank line added between two
133 // items. For various "small" items, it doesn't look nice if there's too much
134 // vertical whitespace added.
135 bool ShouldAddBlankLineInBetween(const ParseNode* a, const ParseNode* b);
137 // Get the 0-based x position on the current line.
138 int CurrentColumn() const;
140 // Get the current line in the output;
141 int CurrentLine() const;
143 // Adds an opening ( if prec is less than the outers (to maintain evalution
144 // order for a subexpression). If an opening paren is emitted, *parenthesized
145 // will be set so it can be closed at the end of the expression.
146 void AddParen(int prec, int outer_prec, bool* parenthesized);
148 // Print the expression to the output buffer. Returns the type of element
149 // added to the output. The value of outer_prec gives the precedence of the
150 // operator outside this Expr. If that operator binds tighter than root's,
151 // Expr must introduce parentheses.
152 int Expr(const ParseNode* root, int outer_prec, const std::string& suffix);
154 // Generic penalties for exceeding maximum width, adding more lines, etc.
155 int AssessPenalty(const std::string& output);
157 // Tests if any lines exceed the maximum width.
158 bool ExceedsMaximumWidth(const std::string& output);
160 // Format a list of values using the given style.
161 // |end| holds any trailing comments to be printed just before the closing
162 // bracket.
163 template <class PARSENODE> // Just for const covariance.
164 void Sequence(SequenceStyle style,
165 const std::vector<PARSENODE*>& list,
166 const ParseNode* end,
167 bool force_multiline);
169 // Returns the penalty.
170 int FunctionCall(const FunctionCallNode* func_call,
171 const std::string& suffix);
173 // Create a clone of this Printer in a similar state (other than the output,
174 // but including margins, etc.) to be used for dry run measurements.
175 void InitializeSub(Printer* sub);
177 template <class PARSENODE>
178 bool ListWillBeMultiline(const std::vector<PARSENODE*>& list,
179 const ParseNode* end);
181 std::string output_; // Output buffer.
182 std::vector<Token> comments_; // Pending end-of-line comments.
183 int margin() const { return stack_.back().margin; }
185 int penalty_depth_;
186 int GetPenaltyForLineBreak() const {
187 return penalty_depth_ * kPenaltyLineBreak;
190 struct IndentState {
191 IndentState()
192 : margin(0),
193 continuation_requires_indent(false),
194 parent_is_boolean_or(false) {}
195 IndentState(int margin,
196 bool continuation_requires_indent,
197 bool parent_is_boolean_or)
198 : margin(margin),
199 continuation_requires_indent(continuation_requires_indent),
200 parent_is_boolean_or(parent_is_boolean_or) {}
202 // The left margin (number of spaces).
203 int margin;
205 bool continuation_requires_indent;
207 bool parent_is_boolean_or;
209 // Stack used to track
210 std::vector<IndentState> stack_;
212 // Gives the precedence for operators in a BinaryOpNode.
213 std::map<base::StringPiece, Precedence> precedence_;
215 DISALLOW_COPY_AND_ASSIGN(Printer);
218 Printer::Printer() : penalty_depth_(0) {
219 output_.reserve(100 << 10);
220 precedence_["="] = kPrecedenceAssign;
221 precedence_["+="] = kPrecedenceAssign;
222 precedence_["-="] = kPrecedenceAssign;
223 precedence_["||"] = kPrecedenceOr;
224 precedence_["&&"] = kPrecedenceAnd;
225 precedence_["<"] = kPrecedenceCompare;
226 precedence_[">"] = kPrecedenceCompare;
227 precedence_["=="] = kPrecedenceCompare;
228 precedence_["!="] = kPrecedenceCompare;
229 precedence_["<="] = kPrecedenceCompare;
230 precedence_[">="] = kPrecedenceCompare;
231 precedence_["+"] = kPrecedenceAdd;
232 precedence_["-"] = kPrecedenceAdd;
233 precedence_["!"] = kPrecedenceUnary;
234 stack_.push_back(IndentState());
237 Printer::~Printer() {
240 void Printer::Print(base::StringPiece str) {
241 str.AppendToString(&output_);
244 void Printer::PrintMargin() {
245 output_ += std::string(margin(), ' ');
248 void Printer::TrimAndPrintToken(const Token& token) {
249 std::string trimmed;
250 TrimWhitespaceASCII(token.value().as_string(), base::TRIM_ALL, &trimmed);
251 Print(trimmed);
254 void Printer::Newline() {
255 if (!comments_.empty()) {
256 Print(" ");
257 // Save the margin, and temporarily set it to where the first comment
258 // starts so that multiple suffix comments are vertically aligned. This
259 // will need to be fancier once we enforce 80 col.
260 stack_.push_back(IndentState(CurrentColumn(), false, false));
261 int i = 0;
262 for (const auto& c : comments_) {
263 if (i > 0) {
264 Trim();
265 Print("\n");
266 PrintMargin();
268 TrimAndPrintToken(c);
269 ++i;
271 stack_.pop_back();
272 comments_.clear();
274 Trim();
275 Print("\n");
276 PrintMargin();
279 void Printer::Trim() {
280 size_t n = output_.size();
281 while (n > 0 && output_[n - 1] == ' ')
282 --n;
283 output_.resize(n);
286 bool Printer::HaveBlankLine() {
287 size_t n = output_.size();
288 while (n > 0 && output_[n - 1] == ' ')
289 --n;
290 return n > 2 && output_[n - 1] == '\n' && output_[n - 2] == '\n';
293 void Printer::AnnotatePreferredMultilineAssignment(const BinaryOpNode* binop) {
294 const IdentifierNode* ident = binop->left()->AsIdentifier();
295 const ListNode* list = binop->right()->AsList();
296 // This is somewhat arbitrary, but we include the 'deps'- and 'sources'-like
297 // things, but not flags things.
298 if (binop->op().value() == "=" && ident && list) {
299 const base::StringPiece lhs = ident->value().value();
300 if (lhs == "data" || lhs == "datadeps" || lhs == "deps" ||
301 lhs == "inputs" || lhs == "outputs" || lhs == "public" ||
302 lhs == "public_deps" || lhs == "sources") {
303 const_cast<ListNode*>(list)->set_prefer_multiline(true);
308 bool Printer::ShouldAddBlankLineInBetween(const ParseNode* a,
309 const ParseNode* b) {
310 LocationRange a_range = a->GetRange();
311 LocationRange b_range = b->GetRange();
312 // If they're already separated by 1 or more lines, then we want to keep a
313 // blank line.
314 return b_range.begin().line_number() > a_range.end().line_number() + 1;
317 int Printer::CurrentColumn() const {
318 int n = 0;
319 while (n < static_cast<int>(output_.size()) &&
320 output_[output_.size() - 1 - n] != '\n') {
321 ++n;
323 return n;
326 int Printer::CurrentLine() const {
327 int count = 1;
328 for (const char* p = output_.c_str(); (p = strchr(p, '\n')) != nullptr;) {
329 ++count;
330 ++p;
332 return count;
335 void Printer::Block(const ParseNode* root) {
336 const BlockNode* block = root->AsBlock();
338 if (block->comments()) {
339 for (const auto& c : block->comments()->before()) {
340 TrimAndPrintToken(c);
341 Newline();
345 size_t i = 0;
346 for (const auto& stmt : block->statements()) {
347 Expr(stmt, kPrecedenceLowest, std::string());
348 Newline();
349 if (stmt->comments()) {
350 // Why are before() not printed here too? before() are handled inside
351 // Expr(), as are suffix() which are queued to the next Newline().
352 // However, because it's a general expression handler, it doesn't insert
353 // the newline itself, which only happens between block statements. So,
354 // the after are handled explicitly here.
355 for (const auto& c : stmt->comments()->after()) {
356 TrimAndPrintToken(c);
357 Newline();
360 if (i < block->statements().size() - 1 &&
361 (ShouldAddBlankLineInBetween(block->statements()[i],
362 block->statements()[i + 1]))) {
363 Newline();
365 ++i;
368 if (block->comments()) {
369 for (const auto& c : block->comments()->after()) {
370 TrimAndPrintToken(c);
371 Newline();
376 int Printer::AssessPenalty(const std::string& output) {
377 int penalty = 0;
378 std::vector<std::string> lines;
379 base::SplitStringDontTrim(output, '\n', &lines);
380 penalty += static_cast<int>(lines.size() - 1) * GetPenaltyForLineBreak();
381 for (const auto& line : lines) {
382 if (line.size() > kMaximumWidth)
383 penalty += static_cast<int>(line.size() - kMaximumWidth) * kPenaltyExcess;
385 return penalty;
388 bool Printer::ExceedsMaximumWidth(const std::string& output) {
389 std::vector<std::string> lines;
390 base::SplitStringDontTrim(output, '\n', &lines);
391 for (const auto& line : lines) {
392 if (line.size() > kMaximumWidth)
393 return true;
395 return false;
398 void Printer::AddParen(int prec, int outer_prec, bool* parenthesized) {
399 if (prec < outer_prec) {
400 Print("(");
401 *parenthesized = true;
405 int Printer::Expr(const ParseNode* root,
406 int outer_prec,
407 const std::string& suffix) {
408 std::string at_end = suffix;
409 int penalty = 0;
410 penalty_depth_++;
412 if (root->comments()) {
413 if (!root->comments()->before().empty()) {
414 Trim();
415 // If there's already other text on the line, start a new line.
416 if (CurrentColumn() > 0)
417 Print("\n");
418 // We're printing a line comment, so we need to be at the current margin.
419 PrintMargin();
420 for (const auto& c : root->comments()->before()) {
421 TrimAndPrintToken(c);
422 Newline();
427 bool parenthesized = false;
429 if (const AccessorNode* accessor = root->AsAccessor()) {
430 AddParen(kPrecedenceSuffix, outer_prec, &parenthesized);
431 Print(accessor->base().value());
432 if (accessor->member()) {
433 Print(".");
434 Expr(accessor->member(), kPrecedenceLowest, std::string());
435 } else {
436 CHECK(accessor->index());
437 Print("[");
438 Expr(accessor->index(), kPrecedenceLowest, "]");
440 } else if (const BinaryOpNode* binop = root->AsBinaryOp()) {
441 CHECK(precedence_.find(binop->op().value()) != precedence_.end());
442 AnnotatePreferredMultilineAssignment(binop);
444 Precedence prec = precedence_[binop->op().value()];
446 // Since binary operators format left-to-right, it is ok for the left side
447 // use the same operator without parentheses, so the left uses prec. For the
448 // same reason, the right side cannot reuse the same operator, or else "x +
449 // (y + z)" would format as "x + y + z" which means "(x + y) + z". So, treat
450 // the right expression as appearing one precedence level higher.
451 // However, because the source parens are not in the parse tree, as a
452 // special case for && and || we insert strictly-redundant-but-helpful-for-
453 // human-readers parentheses.
454 int prec_left = prec;
455 int prec_right = prec + 1;
456 if (binop->op().value() == "&&" && stack_.back().parent_is_boolean_or) {
457 Print("(");
458 parenthesized = true;
459 } else {
460 AddParen(prec_left, outer_prec, &parenthesized);
463 int start_line = CurrentLine();
464 int start_column = CurrentColumn();
465 bool is_assignment = binop->op().value() == "=" ||
466 binop->op().value() == "+=" ||
467 binop->op().value() == "-=";
468 // A sort of funny special case for the long lists that are common in .gn
469 // files, don't indent them + 4, even though they're just continuations when
470 // they're simple lists like "x = [ a, b, c, ... ]"
471 const ListNode* right_as_list = binop->right()->AsList();
472 int indent_column =
473 (is_assignment &&
474 (!right_as_list || (!right_as_list->prefer_multiline() &&
475 !ListWillBeMultiline(right_as_list->contents(),
476 right_as_list->End()))))
477 ? margin() + kIndentSize * 2
478 : start_column;
479 if (stack_.back().continuation_requires_indent)
480 indent_column += kIndentSize * 2;
482 stack_.push_back(IndentState(indent_column,
483 stack_.back().continuation_requires_indent,
484 binop->op().value() == "||"));
485 Printer sub_left;
486 InitializeSub(&sub_left);
487 sub_left.Expr(binop->left(),
488 prec_left,
489 std::string(" ") + binop->op().value().as_string());
490 bool left_is_multiline = CountLines(sub_left.String()) > 1;
491 // Avoid walking the whole left redundantly times (see timing of Format.046)
492 // so pull the output and comments from subprinter.
493 Print(sub_left.String().substr(start_column));
494 std::copy(sub_left.comments_.begin(),
495 sub_left.comments_.end(),
496 std::back_inserter(comments_));
498 // Single line.
499 Printer sub1;
500 InitializeSub(&sub1);
501 sub1.Print(" ");
502 int penalty_current_line =
503 sub1.Expr(binop->right(), prec_right, std::string());
504 sub1.Print(suffix);
505 penalty_current_line += AssessPenalty(sub1.String());
506 if (!is_assignment && left_is_multiline) {
507 // In e.g. xxx + yyy, if xxx is already multiline, then we want a penalty
508 // for trying to continue as if this were one line.
509 penalty_current_line +=
510 (CountLines(sub1.String()) - 1) * kPenaltyBrokenLineOnOneLiner;
513 // Break after operator.
514 Printer sub2;
515 InitializeSub(&sub2);
516 sub2.Newline();
517 int penalty_next_line =
518 sub2.Expr(binop->right(), prec_right, std::string());
519 sub2.Print(suffix);
520 penalty_next_line += AssessPenalty(sub2.String());
522 // If in both cases it was forced past 80col, then we don't break to avoid
523 // breaking after '=' in the case of:
524 // variable = "... very long string ..."
525 // as breaking and indenting doesn't make things much more readable, even
526 // though there's less characters past the maximum width.
527 bool exceeds_maximum_either_way = ExceedsMaximumWidth(sub1.String()) &&
528 ExceedsMaximumWidth(sub2.String());
530 if (penalty_current_line < penalty_next_line ||
531 exceeds_maximum_either_way) {
532 Print(" ");
533 Expr(binop->right(), prec_right, std::string());
534 } else {
535 // Otherwise, put first argument and op, and indent next.
536 Newline();
537 penalty += std::abs(CurrentColumn() - start_column) *
538 kPenaltyHorizontalSeparation;
539 Expr(binop->right(), prec_right, std::string());
541 stack_.pop_back();
542 penalty += (CurrentLine() - start_line) * GetPenaltyForLineBreak();
543 } else if (const BlockNode* block = root->AsBlock()) {
544 Sequence(
545 kSequenceStyleBracedBlock, block->statements(), block->End(), false);
546 } else if (const ConditionNode* condition = root->AsConditionNode()) {
547 Print("if (");
548 // TODO(scottmg): The { needs to be included in the suffix here.
549 Expr(condition->condition(), kPrecedenceLowest, ") ");
550 Sequence(kSequenceStyleBracedBlock,
551 condition->if_true()->statements(),
552 condition->if_true()->End(),
553 false);
554 if (condition->if_false()) {
555 Print(" else ");
556 // If it's a block it's a bare 'else', otherwise it's an 'else if'. See
557 // ConditionNode::Execute.
558 bool is_else_if = condition->if_false()->AsBlock() == nullptr;
559 if (is_else_if) {
560 Expr(condition->if_false(), kPrecedenceLowest, std::string());
561 } else {
562 Sequence(kSequenceStyleBracedBlock,
563 condition->if_false()->AsBlock()->statements(),
564 condition->if_false()->AsBlock()->End(),
565 false);
568 } else if (const FunctionCallNode* func_call = root->AsFunctionCall()) {
569 penalty += FunctionCall(func_call, at_end);
570 at_end = "";
571 } else if (const IdentifierNode* identifier = root->AsIdentifier()) {
572 Print(identifier->value().value());
573 } else if (const ListNode* list = root->AsList()) {
574 bool force_multiline =
575 list->prefer_multiline() && !list->contents().empty();
576 Sequence(
577 kSequenceStyleList, list->contents(), list->End(), force_multiline);
578 } else if (const LiteralNode* literal = root->AsLiteral()) {
579 Print(literal->value().value());
580 } else if (const UnaryOpNode* unaryop = root->AsUnaryOp()) {
581 Print(unaryop->op().value());
582 Expr(unaryop->operand(), kPrecedenceUnary, std::string());
583 } else if (const BlockCommentNode* block_comment = root->AsBlockComment()) {
584 Print(block_comment->comment().value());
585 } else if (const EndNode* end = root->AsEnd()) {
586 Print(end->value().value());
587 } else {
588 CHECK(false) << "Unhandled case in Expr.";
591 if (parenthesized)
592 Print(")");
594 // Defer any end of line comment until we reach the newline.
595 if (root->comments() && !root->comments()->suffix().empty()) {
596 std::copy(root->comments()->suffix().begin(),
597 root->comments()->suffix().end(),
598 std::back_inserter(comments_));
601 Print(at_end);
603 penalty_depth_--;
604 return penalty;
607 template <class PARSENODE>
608 void Printer::Sequence(SequenceStyle style,
609 const std::vector<PARSENODE*>& list,
610 const ParseNode* end,
611 bool force_multiline) {
612 if (style == kSequenceStyleList)
613 Print("[");
614 else if (style == kSequenceStyleBracedBlock)
615 Print("{");
617 if (style == kSequenceStyleBlock || style == kSequenceStyleBracedBlock)
618 force_multiline = true;
620 force_multiline |= ListWillBeMultiline(list, end);
622 if (list.size() == 0 && !force_multiline) {
623 // No elements, and not forcing newlines, print nothing.
624 } else if (list.size() == 1 && !force_multiline) {
625 Print(" ");
626 Expr(list[0], kPrecedenceLowest, std::string());
627 CHECK(!list[0]->comments() || list[0]->comments()->after().empty());
628 Print(" ");
629 } else {
630 stack_.push_back(IndentState(margin() + kIndentSize,
631 style == kSequenceStyleList,
632 false));
633 size_t i = 0;
634 for (const auto& x : list) {
635 Newline();
636 // If:
637 // - we're going to output some comments, and;
638 // - we haven't just started this multiline list, and;
639 // - there isn't already a blank line here;
640 // Then: insert one.
641 if (i != 0 && x->comments() && !x->comments()->before().empty() &&
642 !HaveBlankLine()) {
643 Newline();
645 bool body_of_list = i < list.size() - 1 || style == kSequenceStyleList;
646 bool want_comma =
647 body_of_list && (style == kSequenceStyleList && !x->AsBlockComment());
648 Expr(x, kPrecedenceLowest, want_comma ? "," : std::string());
649 CHECK(!x->comments() || x->comments()->after().empty());
650 if (body_of_list) {
651 if (!want_comma) {
652 if (i < list.size() - 1 &&
653 ShouldAddBlankLineInBetween(list[i], list[i + 1]))
654 Newline();
657 ++i;
660 // Trailing comments.
661 if (end->comments() && !end->comments()->before().empty()) {
662 if (list.size() >= 2)
663 Newline();
664 for (const auto& c : end->comments()->before()) {
665 Newline();
666 TrimAndPrintToken(c);
670 stack_.pop_back();
671 Newline();
673 // Defer any end of line comment until we reach the newline.
674 if (end->comments() && !end->comments()->suffix().empty()) {
675 std::copy(end->comments()->suffix().begin(),
676 end->comments()->suffix().end(),
677 std::back_inserter(comments_));
681 if (style == kSequenceStyleList)
682 Print("]");
683 else if (style == kSequenceStyleBracedBlock)
684 Print("}");
687 int Printer::FunctionCall(const FunctionCallNode* func_call,
688 const std::string& suffix) {
689 int start_line = CurrentLine();
690 int start_column = CurrentColumn();
691 Print(func_call->function().value());
692 Print("(");
694 bool have_block = func_call->block() != nullptr;
695 bool force_multiline = false;
697 const std::vector<const ParseNode*>& list = func_call->args()->contents();
698 const ParseNode* end = func_call->args()->End();
700 if (end && end->comments() && !end->comments()->before().empty())
701 force_multiline = true;
703 // If there's before line comments, make sure we have a place to put them.
704 for (const auto& i : list) {
705 if (i->comments() && !i->comments()->before().empty())
706 force_multiline = true;
709 // Calculate the penalties for 3 possible layouts:
710 // 1. all on same line;
711 // 2. starting on same line, broken at each comma but paren aligned;
712 // 3. broken to next line + 4, broken at each comma.
713 std::string terminator = ")";
714 if (have_block)
715 terminator += " {";
716 terminator += suffix;
718 // Special case to make function calls of one arg taking a long list of
719 // boolean operators not indent.
720 bool continuation_requires_indent =
721 list.size() != 1 || !list[0]->AsBinaryOp();
723 // 1: Same line.
724 Printer sub1;
725 InitializeSub(&sub1);
726 sub1.stack_.push_back(
727 IndentState(CurrentColumn(), continuation_requires_indent, false));
728 int penalty_one_line = 0;
729 for (size_t i = 0; i < list.size(); ++i) {
730 penalty_one_line += sub1.Expr(list[i], kPrecedenceLowest,
731 i < list.size() - 1 ? ", " : std::string());
733 sub1.Print(terminator);
734 penalty_one_line += AssessPenalty(sub1.String());
735 // This extra penalty prevents a short second argument from being squeezed in
736 // after a first argument that went multiline (and instead preferring a
737 // variant below).
738 penalty_one_line +=
739 (CountLines(sub1.String()) - 1) * kPenaltyBrokenLineOnOneLiner;
741 // 2: Starting on same line, broken at commas.
742 Printer sub2;
743 InitializeSub(&sub2);
744 sub2.stack_.push_back(
745 IndentState(CurrentColumn(), continuation_requires_indent, false));
746 int penalty_multiline_start_same_line = 0;
747 for (size_t i = 0; i < list.size(); ++i) {
748 penalty_multiline_start_same_line += sub2.Expr(
749 list[i], kPrecedenceLowest, i < list.size() - 1 ? "," : std::string());
750 if (i < list.size() - 1) {
751 sub2.Newline();
754 sub2.Print(terminator);
755 penalty_multiline_start_same_line += AssessPenalty(sub2.String());
757 // 3: Starting on next line, broken at commas.
758 Printer sub3;
759 InitializeSub(&sub3);
760 sub3.stack_.push_back(IndentState(margin() + kIndentSize * 2,
761 continuation_requires_indent, false));
762 sub3.Newline();
763 int penalty_multiline_start_next_line = 0;
764 for (size_t i = 0; i < list.size(); ++i) {
765 if (i == 0) {
766 penalty_multiline_start_next_line +=
767 std::abs(sub3.CurrentColumn() - start_column) *
768 kPenaltyHorizontalSeparation;
770 penalty_multiline_start_next_line += sub3.Expr(
771 list[i], kPrecedenceLowest, i < list.size() - 1 ? "," : std::string());
772 if (i < list.size() - 1) {
773 sub3.Newline();
776 sub3.Print(terminator);
777 penalty_multiline_start_next_line += AssessPenalty(sub3.String());
779 int penalty = penalty_multiline_start_next_line;
780 bool fits_on_current_line = false;
781 if (penalty_one_line < penalty_multiline_start_next_line ||
782 penalty_multiline_start_same_line < penalty_multiline_start_next_line) {
783 fits_on_current_line = true;
784 penalty = penalty_one_line;
785 if (penalty_multiline_start_same_line < penalty_one_line) {
786 penalty = penalty_multiline_start_same_line;
787 force_multiline = true;
789 } else {
790 force_multiline = true;
793 if (list.size() == 0 && !force_multiline) {
794 // No elements, and not forcing newlines, print nothing.
795 } else {
796 if (penalty_multiline_start_next_line < penalty_multiline_start_same_line) {
797 stack_.push_back(IndentState(margin() + kIndentSize * 2,
798 continuation_requires_indent,
799 false));
800 Newline();
801 } else {
802 stack_.push_back(
803 IndentState(CurrentColumn(), continuation_requires_indent, false));
806 for (size_t i = 0; i < list.size(); ++i) {
807 const auto& x = list[i];
808 if (i > 0) {
809 if (fits_on_current_line && !force_multiline)
810 Print(" ");
811 else
812 Newline();
814 bool want_comma = i < list.size() - 1 && !x->AsBlockComment();
815 Expr(x, kPrecedenceLowest, want_comma ? "," : std::string());
816 CHECK(!x->comments() || x->comments()->after().empty());
817 if (i < list.size() - 1) {
818 if (!want_comma)
819 Newline();
823 // Trailing comments.
824 if (end->comments() && !end->comments()->before().empty()) {
825 if (!list.empty())
826 Newline();
827 for (const auto& c : end->comments()->before()) {
828 Newline();
829 TrimAndPrintToken(c);
831 Newline();
833 stack_.pop_back();
836 // Defer any end of line comment until we reach the newline.
837 if (end->comments() && !end->comments()->suffix().empty()) {
838 std::copy(end->comments()->suffix().begin(),
839 end->comments()->suffix().end(), std::back_inserter(comments_));
842 Print(")");
843 Print(suffix);
845 if (have_block) {
846 Print(" ");
847 Sequence(kSequenceStyleBracedBlock,
848 func_call->block()->statements(),
849 func_call->block()->End(),
850 false);
852 return penalty + (CurrentLine() - start_line) * GetPenaltyForLineBreak();
855 void Printer::InitializeSub(Printer* sub) {
856 sub->stack_ = stack_;
857 sub->comments_ = comments_;
858 sub->penalty_depth_ = penalty_depth_;
859 sub->Print(std::string(CurrentColumn(), 'x'));
862 template <class PARSENODE>
863 bool Printer::ListWillBeMultiline(const std::vector<PARSENODE*>& list,
864 const ParseNode* end) {
865 if (list.size() > 1)
866 return true;
868 if (end && end->comments() && !end->comments()->before().empty())
869 return true;
871 // If there's before line comments, make sure we have a place to put them.
872 for (const auto& i : list) {
873 if (i->comments() && !i->comments()->before().empty())
874 return true;
877 return false;
880 void DoFormat(const ParseNode* root, bool dump_tree, std::string* output) {
881 if (dump_tree) {
882 std::ostringstream os;
883 root->Print(os, 0);
884 printf("----------------------\n");
885 printf("-- PARSE TREE --------\n");
886 printf("----------------------\n");
887 printf("%s", os.str().c_str());
888 printf("----------------------\n");
890 Printer pr;
891 pr.Block(root);
892 *output = pr.String();
895 std::string ReadStdin() {
896 static const int kBufferSize = 256;
897 char buffer[kBufferSize];
898 std::string result;
899 while (true) {
900 char* input = nullptr;
901 input = fgets(buffer, kBufferSize, stdin);
902 if (input == nullptr && feof(stdin))
903 return result;
904 int length = static_cast<int>(strlen(buffer));
905 if (length == 0)
906 return result;
907 else
908 result += std::string(buffer, length);
912 } // namespace
914 bool FormatFileToString(Setup* setup,
915 const SourceFile& file,
916 bool dump_tree,
917 std::string* output) {
918 Err err;
919 const ParseNode* parse_node =
920 setup->scheduler().input_file_manager()->SyncLoadFile(
921 LocationRange(), &setup->build_settings(), file, &err);
922 if (err.has_error()) {
923 err.PrintToStdout();
924 return false;
926 DoFormat(parse_node, dump_tree, output);
927 return true;
930 bool FormatStringToString(const std::string& input,
931 bool dump_tree,
932 std::string* output) {
933 SourceFile source_file;
934 InputFile file(source_file);
935 file.SetContents(input);
936 Err err;
937 // Tokenize.
938 std::vector<Token> tokens = Tokenizer::Tokenize(&file, &err);
939 if (err.has_error()) {
940 err.PrintToStdout();
941 return false;
944 // Parse.
945 scoped_ptr<ParseNode> parse_node = Parser::Parse(tokens, &err);
946 if (err.has_error()) {
947 err.PrintToStdout();
948 return false;
951 DoFormat(parse_node.get(), dump_tree, output);
952 return true;
955 int RunFormat(const std::vector<std::string>& args) {
956 bool dry_run =
957 base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchDryRun);
958 bool dump_tree =
959 base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchDumpTree);
960 bool from_stdin =
961 base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchStdin);
962 bool in_place =
963 base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchInPlace);
965 if (dry_run) {
966 // --dry-run only works with an actual file to compare to.
967 from_stdin = false;
968 in_place = true;
971 if (from_stdin) {
972 if (args.size() != 0) {
973 Err(Location(), "Expecting no arguments when reading from stdin.\n")
974 .PrintToStdout();
975 return 1;
977 std::string input = ReadStdin();
978 std::string output;
979 if (!FormatStringToString(input, dump_tree, &output))
980 return 1;
981 printf("%s", output.c_str());
982 return 0;
985 // TODO(scottmg): Eventually, this should be a list/spec of files, and they
986 // should all be done in parallel.
987 if (args.size() != 1) {
988 Err(Location(), "Expecting exactly one argument, see `gn help format`.\n")
989 .PrintToStdout();
990 return 1;
993 Setup setup;
994 SourceDir source_dir =
995 SourceDirForCurrentDirectory(setup.build_settings().root_path());
996 SourceFile file = source_dir.ResolveRelativeFile(args[0]);
998 std::string output_string;
999 if (FormatFileToString(&setup, file, dump_tree, &output_string)) {
1000 if (in_place) {
1001 base::FilePath to_write = setup.build_settings().GetFullPath(file);
1002 std::string original_contents;
1003 if (!base::ReadFileToString(to_write, &original_contents)) {
1004 Err(Location(), std::string("Couldn't read \"") +
1005 to_write.AsUTF8Unsafe() +
1006 std::string("\" for comparison.")).PrintToStdout();
1007 return 1;
1009 if (dry_run)
1010 return original_contents == output_string ? 0 : 2;
1011 if (original_contents != output_string) {
1012 if (base::WriteFile(to_write,
1013 output_string.data(),
1014 static_cast<int>(output_string.size())) == -1) {
1015 Err(Location(),
1016 std::string("Failed to write formatted output back to \"") +
1017 to_write.AsUTF8Unsafe() + std::string("\".")).PrintToStdout();
1018 return 1;
1020 printf("Wrote formatted to '%s'.\n", to_write.AsUTF8Unsafe().c_str());
1022 } else {
1023 printf("%s", output_string.c_str());
1027 return 0;
1030 } // namespace commands