blob: 9dfde34e8b5bf18c7cf44694803835f214676a10 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimek24998102013-01-16 14:55:28 +000029// Uncomment to get debug output from tests:
30// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
39 LLVMStyle.PointerAndReferenceBindToType = false;
40 LLVMStyle.AccessModifierOffset = -2;
41 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000050 return LLVMStyle;
51}
52
53FormatStyle getGoogleStyle() {
54 FormatStyle GoogleStyle;
55 GoogleStyle.ColumnLimit = 80;
56 GoogleStyle.MaxEmptyLinesToKeep = 1;
57 GoogleStyle.PointerAndReferenceBindToType = true;
58 GoogleStyle.AccessModifierOffset = -1;
59 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000060 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000061 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000062 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000063 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000064 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000065 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000066 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000067 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000068 return GoogleStyle;
69}
70
Daniel Jasper1b750ed2013-01-14 16:24:39 +000071FormatStyle getChromiumStyle() {
72 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000073 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper17fdaa42013-01-29 15:19:38 +000074 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075 return ChromiumStyle;
76}
77
Daniel Jasperf7935112012-12-03 18:12:45 +000078struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000079 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +000080 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +000081};
82
Daniel Jasperaa701fa2013-01-18 08:44:07 +000083/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000084///
Daniel Jasperaa701fa2013-01-18 08:44:07 +000085/// This includes special handling for certain constructs, e.g. the alignment of
86/// trailing line comments.
87class WhitespaceManager {
88public:
89 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
90
91 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
92 /// each \c AnnotatedToken.
93 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
94 unsigned Spaces, unsigned WhitespaceStartColumn,
95 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +000096 // 2+ newlines mean an empty line separating logic scopes.
97 if (NewLines >= 2)
98 alignComments();
99
100 // Align line comments if they are trailing or if they continue other
101 // trailing comments.
102 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000103 (Tok.Parent != NULL || !Comments.empty())) {
104 if (Style.ColumnLimit >=
105 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
106 Comments.push_back(StoredComment());
107 Comments.back().Tok = Tok.FormatTok;
108 Comments.back().Spaces = Spaces;
109 Comments.back().NewLines = NewLines;
110 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000111 Comments.back().MaxColumn =
112 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000113 return;
114 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000116
117 // If this line does not have a trailing comment, align the stored comments.
118 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
119 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 storeReplacement(Tok.FormatTok,
121 std::string(NewLines, '\n') + std::string(Spaces, ' '));
122 }
123
124 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
125 /// backslashes to escape newlines inside a preprocessor directive.
126 ///
127 /// This function and \c replaceWhitespace have the same behavior if
128 /// \c Newlines == 0.
129 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
130 unsigned Spaces, unsigned WhitespaceStartColumn,
131 const FormatStyle &Style) {
132 std::string NewLineText;
133 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000134 unsigned Offset =
135 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000136 for (unsigned i = 0; i < NewLines; ++i) {
137 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
138 NewLineText += "\\\n";
139 Offset = 0;
140 }
141 }
142 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
143 }
144
145 /// \brief Returns all the \c Replacements created during formatting.
146 const tooling::Replacements &generateReplacements() {
147 alignComments();
148 return Replaces;
149 }
150
151private:
152 /// \brief Structure to store a comment for later layout and alignment.
153 struct StoredComment {
154 FormatToken Tok;
155 unsigned MinColumn;
156 unsigned MaxColumn;
157 unsigned NewLines;
158 unsigned Spaces;
159 };
160 SmallVector<StoredComment, 16> Comments;
161 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
162
163 /// \brief Try to align all stashed comments.
164 void alignComments() {
165 unsigned MinColumn = 0;
166 unsigned MaxColumn = UINT_MAX;
167 comment_iterator Start = Comments.begin();
168 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
169 ++I) {
170 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
171 alignComments(Start, I, MinColumn);
172 MinColumn = I->MinColumn;
173 MaxColumn = I->MaxColumn;
174 Start = I;
175 } else {
176 MinColumn = std::max(MinColumn, I->MinColumn);
177 MaxColumn = std::min(MaxColumn, I->MaxColumn);
178 }
179 }
180 alignComments(Start, Comments.end(), MinColumn);
181 Comments.clear();
182 }
183
184 /// \brief Put all the comments between \p I and \p E into \p Column.
185 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
186 while (I != E) {
187 unsigned Spaces = I->Spaces + Column - I->MinColumn;
188 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
189 std::string(Spaces, ' '));
190 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000191 }
192 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000193
194 /// \brief Stores \p Text as the replacement for the whitespace in front of
195 /// \p Tok.
196 void storeReplacement(const FormatToken &Tok, const std::string Text) {
197 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
198 Tok.WhiteSpaceLength, Text));
199 }
200
201 SourceManager &SourceMgr;
202 tooling::Replacements Replaces;
203};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000204
Daniel Jasperf7935112012-12-03 18:12:45 +0000205class UnwrappedLineFormatter {
206public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000207 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000208 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000209 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000210 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000211 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212 FirstIndent(FirstIndent), RootToken(RootToken),
213 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000214 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000215 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000216 }
217
Manuel Klimek1abf7892013-01-04 23:34:14 +0000218 /// \brief Formats an \c UnwrappedLine.
219 ///
220 /// \returns The column after the last token in the last line of the
221 /// \c UnwrappedLine.
222 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000223 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000224 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000225 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000226 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000227 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000228 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000229 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000230
Manuel Klimek24998102013-01-16 14:55:28 +0000231 DEBUG({
232 DebugTokenState(*State.NextToken);
233 });
234
Daniel Jaspere9de2602012-12-06 09:56:08 +0000235 // The first token has already been indented and thus consumed.
236 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000237
238 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000239 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000240 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
241 // Calculating the column is important for aligning trailing comments.
242 // FIXME: This does not seem to happen in conjunction with escaped
243 // newlines. If it does, fix!
244 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
245 State.NextToken->FormatTok.TokenLength;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000246 State.NextToken = State.NextToken->Children.empty()
247 ? NULL : &State.NextToken->Children[0];
Daniel Jasper997b08c2013-01-18 09:19:33 +0000248 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000249 addTokenToState(false, false, State);
250 } else {
251 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
252 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000253 DEBUG({
254 if (Break < NoBreak)
255 llvm::errs() << "\n";
256 else
257 llvm::errs() << " ";
258 llvm::errs() << "<";
259 DebugPenalty(Break, Break < NoBreak);
260 llvm::errs() << "/";
261 DebugPenalty(NoBreak, !(Break < NoBreak));
262 llvm::errs() << "> ";
263 DebugTokenState(*State.NextToken);
264 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000265 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000266 if (State.NextToken != NULL &&
267 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
268 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000269 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000270 State.Stack.back().BreakAfterComma = true;
271 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000272 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000273 }
Manuel Klimek24998102013-01-16 14:55:28 +0000274 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000275 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000276 }
277
278private:
Manuel Klimek24998102013-01-16 14:55:28 +0000279 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
280 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000281 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
282 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000283 llvm::errs();
284 }
285
286 void DebugPenalty(unsigned Penalty, bool Winner) {
287 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
288 if (Penalty == UINT_MAX)
289 llvm::errs() << "MAX";
290 else
291 llvm::errs() << Penalty;
292 llvm::errs().resetColor();
293 }
294
Daniel Jasper337816e2013-01-11 10:22:12 +0000295 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000296 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000297 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000298 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000299 BreakAfterComma(false), HasMultiParameterLine(false) {
300 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000301
Daniel Jasperf7935112012-12-03 18:12:45 +0000302 /// \brief The position to which a specific parenthesis level needs to be
303 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000304 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000305
Daniel Jaspere9de2602012-12-06 09:56:08 +0000306 /// \brief The position of the last space on each level.
307 ///
308 /// Used e.g. to break like:
309 /// functionCall(Parameter, otherCall(
310 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000311 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000312
Daniel Jaspera836b902013-01-23 16:58:21 +0000313 /// \brief This is the column of the first token after an assignment.
314 unsigned AssignmentColumn;
315
Daniel Jaspere9de2602012-12-06 09:56:08 +0000316 /// \brief The position the first "<<" operator encountered on each level.
317 ///
318 /// Used to align "<<" operators. 0 if no such operator has been encountered
319 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000320 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000321
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000322 /// \brief Whether a newline needs to be inserted before the block's closing
323 /// brace.
324 ///
325 /// We only want to insert a newline before the closing brace if there also
326 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000327 bool BreakBeforeClosingBrace;
328
Daniel Jasperca6623b2013-01-28 12:45:14 +0000329 /// \brief The column of a \c ? in a conditional expression;
330 unsigned QuestionColumn;
331
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000332 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000333 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000334
Daniel Jasper337816e2013-01-11 10:22:12 +0000335 bool operator<(const ParenState &Other) const {
336 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000337 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000338 if (LastSpace != Other.LastSpace)
339 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000340 if (AssignmentColumn != Other.AssignmentColumn)
341 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000342 if (FirstLessLess != Other.FirstLessLess)
343 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000344 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
345 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000346 if (QuestionColumn != Other.QuestionColumn)
347 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000348 if (BreakAfterComma != Other.BreakAfterComma)
349 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000350 if (HasMultiParameterLine != Other.HasMultiParameterLine)
351 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000352 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000353 }
354 };
355
356 /// \brief The current state when indenting a unwrapped line.
357 ///
358 /// As the indenting tries different combinations this is copied by value.
359 struct LineState {
360 /// \brief The number of used columns in the current line.
361 unsigned Column;
362
363 /// \brief The token that needs to be next formatted.
364 const AnnotatedToken *NextToken;
365
Daniel Jasperbbc84152013-01-29 11:27:30 +0000366 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000367 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000368 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000369 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000370
371 /// \brief \c true if this line contains a continued for-loop section.
372 bool LineContainsContinuedForLoopSection;
373
Daniel Jasper337816e2013-01-11 10:22:12 +0000374 /// \brief A stack keeping track of properties applying to parenthesis
375 /// levels.
376 std::vector<ParenState> Stack;
377
378 /// \brief Comparison operator to be able to used \c LineState in \c map.
379 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000380 if (Other.NextToken != NextToken)
381 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000382 if (Other.Column != Column)
383 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000384 if (Other.VariablePos != VariablePos)
385 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000386 if (Other.LineContainsContinuedForLoopSection !=
387 LineContainsContinuedForLoopSection)
388 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000389 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000390 }
391 };
392
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000393 /// \brief Appends the next token to \p State and updates information
394 /// necessary for indentation.
395 ///
396 /// Puts the token on the current line if \p Newline is \c true and adds a
397 /// line break and necessary indentation otherwise.
398 ///
399 /// If \p DryRun is \c false, also creates and stores the required
400 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000401 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000402 const AnnotatedToken &Current = *State.NextToken;
403 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000404 assert(State.Stack.size());
405 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000406
407 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000408 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000409 if (Current.is(tok::r_brace)) {
410 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000411 } else if (Current.is(tok::string_literal) &&
412 Previous.is(tok::string_literal)) {
413 State.Column = State.Column - Previous.FormatTok.TokenLength;
414 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000415 State.Stack[ParenLevel].FirstLessLess != 0) {
416 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000417 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000418 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000419 Current.is(tok::period) || Current.is(tok::arrow) ||
420 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000421 // Indent and extra 4 spaces after if we know the current expression is
422 // continued. Don't do that on the top level, as we already indent 4
423 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000424 State.Column = std::max(State.Stack.back().LastSpace,
425 State.Stack.back().Indent) + 4;
426 } else if (Current.Type == TT_ConditionalExpr) {
427 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000428 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
429 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
430 ParenLevel == 0)) {
431 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000432 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
433 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000435 } else if (Previous.Type == TT_BinaryOperator &&
436 State.Stack.back().AssignmentColumn != 0) {
437 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000438 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000439 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000440 }
441
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000442 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000443 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000444
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000445 if (!DryRun) {
446 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000447 Whitespaces.replaceWhitespace(Current, 1, State.Column,
448 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000449 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000450 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
451 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000452 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000453
Daniel Jasper337816e2013-01-11 10:22:12 +0000454 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000455 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000456 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000457 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000458 if (Current.is(tok::equal) &&
459 (RootToken.is(tok::kw_for) || ParenLevel == 0))
460 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000461
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000462 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
463 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000464 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000465
Daniel Jasperf7935112012-12-03 18:12:45 +0000466 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000467 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000468
Daniel Jasperbcab4302013-01-09 10:40:23 +0000469 // FIXME: Do we need to do this for assignments nested in other
470 // expressions?
471 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000472 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000473 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000474 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000475 if (Current.Type != TT_LineComment &&
476 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
477 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000478 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000479 if (Previous.is(tok::comma) && Current.Type != TT_LineComment)
Daniel Jasper9278eb92013-01-16 14:59:02 +0000480 State.Stack[ParenLevel].HasMultiParameterLine = true;
481
Daniel Jaspere9de2602012-12-06 09:56:08 +0000482 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000483 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
484 // Treat the condition inside an if as if it was a second function
485 // parameter, i.e. let nested calls have an indent of 4.
486 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000487 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000488 // Top-level spaces are exempt as that mostly leads to better results.
489 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000490 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000491 Previous.Type == TT_ConditionalExpr ||
492 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000493 getPrecedence(Previous) != prec::Assignment)
494 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000495 else if (Previous.ParameterCount > 1 &&
496 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
497 Previous.Type == TT_TemplateOpener))
498 // If this function has multiple parameters, indent nested calls from
499 // the start of the first parameter.
500 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000501 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000502
503 // If we break after an {, we should also break before the corresponding }.
504 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000505 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000506
Daniel Jaspere941b162013-01-23 10:08:28 +0000507 if (!Style.BinPackParameters && Newline) {
508 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000509 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000510 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
511 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000512 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
513 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000514 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000515
Daniel Jaspere941b162013-01-23 10:08:28 +0000516 // Any break on this level means that the parent level has been broken
517 // and we need to avoid bin packing there.
518 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
519 State.Stack[i].BreakAfterComma = true;
520 }
521 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000522
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000523 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000524 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000525
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000526 /// \brief Mark the next token as consumed in \p State and modify its stacks
527 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000529 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000531
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
533 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000534 if (Current.is(tok::question))
535 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000536
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000537 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000538 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000539 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
540 Current.is(tok::l_brace) ||
541 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000543 if (Current.is(tok::l_brace)) {
544 // FIXME: This does not work with nested static initializers.
545 // Implement a better handling for static initializers and similar
546 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000547 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000549 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000550 }
Daniel Jasperbbc84152013-01-29 11:27:30 +0000551 State.Stack.push_back(ParenState(NewIndent,
552 State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000553 }
554
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000555 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000556 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000557 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
558 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
559 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000560 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000561 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000562
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000563 if (State.NextToken->Children.empty())
564 State.NextToken = NULL;
565 else
566 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000567
568 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000569 }
570
Daniel Jasper2df93312013-01-09 10:16:05 +0000571 unsigned getColumnLimit() {
572 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
573 }
574
Daniel Jasperf7935112012-12-03 18:12:45 +0000575 /// \brief Calculate the number of lines needed to format the remaining part
576 /// of the unwrapped line.
577 ///
578 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000579 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000580 /// added after the previous token.
581 ///
582 /// \param StopAt is used for optimization. If we can determine that we'll
583 /// definitely need at least \p StopAt additional lines, we already know of a
584 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000586 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000587 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000588 return 0;
589
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000592 if (NewLine && !State.NextToken->CanBreakBefore &&
593 !(State.NextToken->is(tok::r_brace) &&
594 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000596 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000597 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000598 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000599 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000600 State.LineContainsContinuedForLoopSection)
601 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000602 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000603 State.NextToken->Type != TT_LineComment &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000604 State.Stack.back().BreakAfterComma)
605 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000606 // Trying to insert a parameter on a new line if there are already more than
607 // one parameter on the current line is bin packing.
608 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
609 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
610 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000611 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
612 (State.NextToken->Parent->ClosesTemplateDeclaration &&
613 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000614 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000615
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000616 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000617 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000618 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jaspercf330002013-01-29 15:03:01 +0000619 State.NextToken->SplitPenalty;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000620
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000621 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000622
Daniel Jasper2df93312013-01-09 10:16:05 +0000623 // Exceeding column limit is bad, assign penalty.
624 if (State.Column > getColumnLimit()) {
625 unsigned ExcessCharacters = State.Column - getColumnLimit();
626 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
627 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000628
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 if (StopAt <= CurrentPenalty)
630 return UINT_MAX;
631 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000632 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000633 if (I != Memory.end()) {
634 // If this state has already been examined, we can safely return the
635 // previous result if we
636 // - have not hit the optimatization (and thus returned UINT_MAX) OR
637 // - are now computing for a smaller or equal StopAt.
638 unsigned SavedResult = I->second.first;
639 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000640 if (SavedResult != UINT_MAX)
641 return SavedResult + CurrentPenalty;
642 else if (StopAt <= SavedStopAt)
643 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000644 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000645
646 unsigned NoBreak = calcPenalty(State, false, StopAt);
647 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
648 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000649
650 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
651 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000652 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000653
654 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000655 }
656
Daniel Jasperf7935112012-12-03 18:12:45 +0000657 FormatStyle Style;
658 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000659 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000660 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000661 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000662 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000663
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000664 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000665 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000666 StateMap Memory;
667
Daniel Jasperf7935112012-12-03 18:12:45 +0000668 OptimizationParameters Parameters;
669};
670
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000671class LexerBasedFormatTokenSource : public FormatTokenSource {
672public:
673 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000674 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000675 IdentTable(Lex.getLangOpts()) {
676 Lex.SetKeepWhitespaceMode(true);
677 }
678
679 virtual FormatToken getNextToken() {
680 if (GreaterStashed) {
681 FormatTok.NewlinesBefore = 0;
682 FormatTok.WhiteSpaceStart =
683 FormatTok.Tok.getLocation().getLocWithOffset(1);
684 FormatTok.WhiteSpaceLength = 0;
685 GreaterStashed = false;
686 return FormatTok;
687 }
688
689 FormatTok = FormatToken();
690 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000691 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000692 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000693 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
694 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000695
696 // Consume and record whitespace until we find a significant token.
697 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000698 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000699 FormatTok.HasUnescapedNewline =
700 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000701 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
702
703 if (FormatTok.Tok.is(tok::eof))
704 return FormatTok;
705 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000706 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000707 }
Manuel Klimekef920692013-01-07 07:56:50 +0000708
709 // Now FormatTok is the next non-whitespace token.
710 FormatTok.TokenLength = Text.size();
711
Manuel Klimek1abf7892013-01-04 23:34:14 +0000712 // In case the token starts with escaped newlines, we want to
713 // take them into account as whitespace - this pattern is quite frequent
714 // in macro definitions.
715 // FIXME: What do we want to do with other escaped spaces, and escaped
716 // spaces or newlines in the middle of tokens?
717 // FIXME: Add a more explicit test.
718 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000719 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000720 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000721 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000722 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000723 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000724 }
725
726 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000727 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000728 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000729 FormatTok.Tok.setKind(Info.getTokenID());
730 }
731
732 if (FormatTok.Tok.is(tok::greatergreater)) {
733 FormatTok.Tok.setKind(tok::greater);
734 GreaterStashed = true;
735 }
736
737 return FormatTok;
738 }
739
740private:
741 FormatToken FormatTok;
742 bool GreaterStashed;
743 Lexer &Lex;
744 SourceManager &SourceMgr;
745 IdentifierTable IdentTable;
746
747 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000748 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000749 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
750 Tok.getLength());
751 }
752};
753
Daniel Jasperf7935112012-12-03 18:12:45 +0000754class Formatter : public UnwrappedLineConsumer {
755public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000756 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
757 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000759 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000760 Whitespaces(SourceMgr), Ranges(Ranges) {
761 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000762
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000763 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000764
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000766 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000767 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000768 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000769 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000770 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
771 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
772 Annotator.annotate();
773 }
774 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
775 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000776 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000777 const AnnotatedLine &TheLine = *I;
778 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000779 unsigned Indent =
780 formatFirstToken(TheLine.First, TheLine.Level,
781 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000782 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000783 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000784 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000785 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000786 PreviousEndOfLineColumn = Formatter.format();
787 } else {
788 // If we did not reformat this unwrapped line, the column at the end of
789 // the last token is unchanged - thus, we can calculate the end of the
790 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000791 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000792 SourceMgr.getSpellingColumnNumber(
793 TheLine.Last->FormatTok.Tok.getLocation()) +
794 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000795 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000796 }
797 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000798 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000799 }
800
801private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000802 /// \brief Tries to merge lines into one.
803 ///
804 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
805 /// if possible; note that \c I will be incremented when lines are merged.
806 ///
807 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000808 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000809 std::vector<AnnotatedLine>::iterator &I,
810 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000811 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
812
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000813 // We can never merge stuff if there are trailing line comments.
814 if (I->Last->Type == TT_LineComment)
815 return;
816
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000817 // Check whether the UnwrappedLine can be put onto a single line. If
818 // so, this is bound to be the optimal solution (by definition) and we
819 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000820 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000821 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000822 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000823
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000824 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000825 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000826
Daniel Jasper25837aa2013-01-14 14:14:23 +0000827 if (I->Last->is(tok::l_brace)) {
828 tryMergeSimpleBlock(I, E, Limit);
829 } else if (I->First.is(tok::kw_if)) {
830 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000831 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
832 I->First.FormatTok.IsFirst)) {
833 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000834 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000835 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000836 }
837
Daniel Jasper39825ea2013-01-14 15:40:57 +0000838 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
839 std::vector<AnnotatedLine>::iterator E,
840 unsigned Limit) {
841 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000842 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
843 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000844 if (I + 2 != E && (I + 2)->InPPDirective &&
845 !(I + 2)->First.FormatTok.HasUnescapedNewline)
846 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000847 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000848 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000849 join(Line, *(++I));
850 }
851
Daniel Jasper25837aa2013-01-14 14:14:23 +0000852 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
853 std::vector<AnnotatedLine>::iterator E,
854 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000855 if (!Style.AllowShortIfStatementsOnASingleLine)
856 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000857 if ((I + 1)->InPPDirective != I->InPPDirective ||
858 ((I + 1)->InPPDirective &&
859 (I + 1)->First.FormatTok.HasUnescapedNewline))
860 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000861 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000862 if (Line.Last->isNot(tok::r_paren))
863 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000864 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000865 return;
866 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
867 return;
868 // Only inline simple if's (no nested if or else).
869 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
870 return;
871 join(Line, *(++I));
872 }
873
874 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000875 std::vector<AnnotatedLine>::iterator E,
876 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000877 // First, check that the current line allows merging. This is the case if
878 // we're not in a control flow statement and the last token is an opening
879 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000880 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000881 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000882 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
883 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
884 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
885 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +0000886 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000887 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
888 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000889 if (!AllowedTokens)
890 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000891
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000892 AnnotatedToken *Tok = &(I + 1)->First;
893 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
894 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
895 Tok->SpaceRequiredBefore = false;
896 join(Line, *(I + 1));
897 I += 1;
898 } else {
899 // Check that we still have three lines and they fit into the limit.
900 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
901 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +0000902 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000903
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000904 // Second, check that the next line does not contain any braces - if it
905 // does, readability declines when putting it into a single line.
906 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
907 return;
908 do {
909 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
910 return;
911 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
912 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000913
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000914 // Last, check that the third line contains a single closing brace.
915 Tok = &(I + 2)->First;
916 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
917 Tok->MustBreakBefore)
918 return;
919
920 join(Line, *(I + 1));
921 join(Line, *(I + 2));
922 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000923 }
Daniel Jasper25837aa2013-01-14 14:14:23 +0000924 }
925
926 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
927 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000928 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
929 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000930 }
931
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000932 void join(AnnotatedLine &A, const AnnotatedLine &B) {
933 A.Last->Children.push_back(B.First);
934 while (!A.Last->Children.empty()) {
935 A.Last->Children[0].Parent = A.Last;
936 A.Last = &A.Last->Children[0];
937 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000938 }
939
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000940 bool touchesRanges(const AnnotatedLine &TheLine) {
941 const FormatToken *First = &TheLine.First.FormatTok;
942 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000943 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +0000944 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +0000945 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000946 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
947 Ranges[i].getBegin()) &&
948 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
949 LineRange.getBegin()))
950 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000951 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000952 return false;
953 }
954
955 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000956 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +0000957 }
958
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000959 /// \brief Add a new line and the required indent before the first Token
960 /// of the \c UnwrappedLine if there was no structural parsing error.
961 /// Returns the indent level of the \c UnwrappedLine.
962 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
963 bool InPPDirective,
964 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000965 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000966 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
967 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
968
Daniel Jasperbbc84152013-01-29 11:27:30 +0000969 unsigned Newlines =
970 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000971 if (Newlines == 0 && !Tok.IsFirst)
972 Newlines = 1;
973 unsigned Indent = Level * 2;
974
975 bool IsAccessModifier = false;
976 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
977 RootToken.is(tok::kw_private))
978 IsAccessModifier = true;
979 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
980 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
981 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
982 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
983 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
984 IsAccessModifier = true;
985
986 if (IsAccessModifier &&
987 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
988 Indent += Style.AccessModifierOffset;
989 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000990 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000991 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000992 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
993 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000994 }
995 return Indent;
996 }
997
Alexander Kornienko116ba682013-01-14 11:34:14 +0000998 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 FormatStyle Style;
1000 Lexer &Lex;
1001 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001002 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001003 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001004 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001005 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006};
1007
Daniel Jasperbbc84152013-01-29 11:27:30 +00001008tooling::Replacements
1009reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1010 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001011 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001012 OwningPtr<DiagnosticConsumer> DiagPrinter;
1013 if (DiagClient == 0) {
1014 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1015 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1016 DiagClient = DiagPrinter.get();
1017 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001018 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001019 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001020 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001021 Diagnostics.setSourceManager(&SourceMgr);
1022 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 return formatter.format();
1024}
1025
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001026LangOptions getFormattingLangOpts() {
1027 LangOptions LangOpts;
1028 LangOpts.CPlusPlus = 1;
1029 LangOpts.CPlusPlus11 = 1;
1030 LangOpts.Bool = 1;
1031 LangOpts.ObjC1 = 1;
1032 LangOpts.ObjC2 = 1;
1033 return LangOpts;
1034}
1035
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001036} // namespace format
1037} // namespace clang