blob: 6d227cca627540ab5fd24aa30e1cfae5b42b3678 [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 Jasper3a9370c2013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
58 GoogleStyle.PointerAndReferenceBindToType = true;
59 GoogleStyle.AccessModifierOffset = -1;
60 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000061 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000062 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000063 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000064 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000065 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000070 return GoogleStyle;
71}
72
Daniel Jasper1b750ed2013-01-14 16:24:39 +000073FormatStyle getChromiumStyle() {
74 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000075 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper17fdaa42013-01-29 15:19:38 +000076 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000077 return ChromiumStyle;
78}
79
Daniel Jasperaa701fa2013-01-18 08:44:07 +000080/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000081///
Daniel Jasperaa701fa2013-01-18 08:44:07 +000082/// This includes special handling for certain constructs, e.g. the alignment of
83/// trailing line comments.
84class WhitespaceManager {
85public:
86 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
87
88 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
89 /// each \c AnnotatedToken.
90 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
91 unsigned Spaces, unsigned WhitespaceStartColumn,
92 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +000093 // 2+ newlines mean an empty line separating logic scopes.
94 if (NewLines >= 2)
95 alignComments();
96
97 // Align line comments if they are trailing or if they continue other
98 // trailing comments.
99 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000100 (Tok.Parent != NULL || !Comments.empty())) {
101 if (Style.ColumnLimit >=
102 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
103 Comments.push_back(StoredComment());
104 Comments.back().Tok = Tok.FormatTok;
105 Comments.back().Spaces = Spaces;
106 Comments.back().NewLines = NewLines;
107 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000108 Comments.back().MaxColumn =
109 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000110 return;
111 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000112 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000113
114 // If this line does not have a trailing comment, align the stored comments.
115 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
116 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000117 storeReplacement(Tok.FormatTok,
118 std::string(NewLines, '\n') + std::string(Spaces, ' '));
119 }
120
121 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
122 /// backslashes to escape newlines inside a preprocessor directive.
123 ///
124 /// This function and \c replaceWhitespace have the same behavior if
125 /// \c Newlines == 0.
126 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
127 unsigned Spaces, unsigned WhitespaceStartColumn,
128 const FormatStyle &Style) {
129 std::string NewLineText;
130 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000131 unsigned Offset =
132 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 for (unsigned i = 0; i < NewLines; ++i) {
134 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
135 NewLineText += "\\\n";
136 Offset = 0;
137 }
138 }
139 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
140 }
141
142 /// \brief Returns all the \c Replacements created during formatting.
143 const tooling::Replacements &generateReplacements() {
144 alignComments();
145 return Replaces;
146 }
147
148private:
149 /// \brief Structure to store a comment for later layout and alignment.
150 struct StoredComment {
151 FormatToken Tok;
152 unsigned MinColumn;
153 unsigned MaxColumn;
154 unsigned NewLines;
155 unsigned Spaces;
156 };
157 SmallVector<StoredComment, 16> Comments;
158 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
159
160 /// \brief Try to align all stashed comments.
161 void alignComments() {
162 unsigned MinColumn = 0;
163 unsigned MaxColumn = UINT_MAX;
164 comment_iterator Start = Comments.begin();
165 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
166 ++I) {
167 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
168 alignComments(Start, I, MinColumn);
169 MinColumn = I->MinColumn;
170 MaxColumn = I->MaxColumn;
171 Start = I;
172 } else {
173 MinColumn = std::max(MinColumn, I->MinColumn);
174 MaxColumn = std::min(MaxColumn, I->MaxColumn);
175 }
176 }
177 alignComments(Start, Comments.end(), MinColumn);
178 Comments.clear();
179 }
180
181 /// \brief Put all the comments between \p I and \p E into \p Column.
182 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
183 while (I != E) {
184 unsigned Spaces = I->Spaces + Column - I->MinColumn;
185 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
186 std::string(Spaces, ' '));
187 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000188 }
189 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000190
191 /// \brief Stores \p Text as the replacement for the whitespace in front of
192 /// \p Tok.
193 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000194 // Don't create a replacement, if it does not change anything.
195 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
196 Tok.WhiteSpaceLength) == Text)
197 return;
198
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000199 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
200 Tok.WhiteSpaceLength, Text));
201 }
202
203 SourceManager &SourceMgr;
204 tooling::Replacements Replaces;
205};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000206
Daniel Jasperf7935112012-12-03 18:12:45 +0000207class UnwrappedLineFormatter {
208public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000209 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000210 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000211 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000213 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000214 FirstIndent(FirstIndent), RootToken(RootToken),
215 Whitespaces(Whitespaces) {
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 Jasper8a8ce242013-01-31 14:59:26 +0000227 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
228 !Style.BinPackParameters));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000229 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000230 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000231
Manuel Klimek24998102013-01-16 14:55:28 +0000232 DEBUG({
233 DebugTokenState(*State.NextToken);
234 });
235
Daniel Jaspere9de2602012-12-06 09:56:08 +0000236 // The first token has already been indented and thus consumed.
237 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000238
Daniel Jasper4b866272013-02-01 11:00:45 +0000239 // If everything fits on a single line, just put it there.
240 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
241 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000242 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000243 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000244 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000245 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000246
247 // Find best solution in solution space.
248 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000249 }
250
251private:
Manuel Klimek24998102013-01-16 14:55:28 +0000252 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
253 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000254 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
255 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000256 llvm::errs();
257 }
258
Daniel Jasper337816e2013-01-11 10:22:12 +0000259 struct ParenState {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000260 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking)
Daniel Jaspera836b902013-01-23 16:58:21 +0000261 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000262 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000263 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
264 HasMultiParameterLine(false) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000265 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000266
Daniel Jasperf7935112012-12-03 18:12:45 +0000267 /// \brief The position to which a specific parenthesis level needs to be
268 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000269 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000270
Daniel Jaspere9de2602012-12-06 09:56:08 +0000271 /// \brief The position of the last space on each level.
272 ///
273 /// Used e.g. to break like:
274 /// functionCall(Parameter, otherCall(
275 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000276 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000277
Daniel Jaspera836b902013-01-23 16:58:21 +0000278 /// \brief This is the column of the first token after an assignment.
279 unsigned AssignmentColumn;
280
Daniel Jaspere9de2602012-12-06 09:56:08 +0000281 /// \brief The position the first "<<" operator encountered on each level.
282 ///
283 /// Used to align "<<" operators. 0 if no such operator has been encountered
284 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000286
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000287 /// \brief Whether a newline needs to be inserted before the block's closing
288 /// brace.
289 ///
290 /// We only want to insert a newline before the closing brace if there also
291 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000292 bool BreakBeforeClosingBrace;
293
Daniel Jasperca6623b2013-01-28 12:45:14 +0000294 /// \brief The column of a \c ? in a conditional expression;
295 unsigned QuestionColumn;
296
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000297 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
298 /// lines, in this context.
299 bool AvoidBinPacking;
300
301 /// \brief Break after the next comma (or all the commas in this context if
302 /// \c AvoidBinPacking is \c true).
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000303 bool BreakAfterComma;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000304
305 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000306 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000307
Daniel Jasper337816e2013-01-11 10:22:12 +0000308 bool operator<(const ParenState &Other) const {
309 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000310 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000311 if (LastSpace != Other.LastSpace)
312 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000313 if (AssignmentColumn != Other.AssignmentColumn)
314 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000315 if (FirstLessLess != Other.FirstLessLess)
316 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000317 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
318 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000319 if (QuestionColumn != Other.QuestionColumn)
320 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000321 if (AvoidBinPacking != Other.AvoidBinPacking)
322 return AvoidBinPacking;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000323 if (BreakAfterComma != Other.BreakAfterComma)
324 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000325 if (HasMultiParameterLine != Other.HasMultiParameterLine)
326 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000327 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000328 }
329 };
330
331 /// \brief The current state when indenting a unwrapped line.
332 ///
333 /// As the indenting tries different combinations this is copied by value.
334 struct LineState {
335 /// \brief The number of used columns in the current line.
336 unsigned Column;
337
338 /// \brief The token that needs to be next formatted.
339 const AnnotatedToken *NextToken;
340
Daniel Jasperbbc84152013-01-29 11:27:30 +0000341 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000342 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000343 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000344 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000345
346 /// \brief \c true if this line contains a continued for-loop section.
347 bool LineContainsContinuedForLoopSection;
348
Daniel Jasper337816e2013-01-11 10:22:12 +0000349 /// \brief A stack keeping track of properties applying to parenthesis
350 /// levels.
351 std::vector<ParenState> Stack;
352
353 /// \brief Comparison operator to be able to used \c LineState in \c map.
354 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000355 if (Other.NextToken != NextToken)
356 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000357 if (Other.Column != Column)
358 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000359 if (Other.VariablePos != VariablePos)
360 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000361 if (Other.LineContainsContinuedForLoopSection !=
362 LineContainsContinuedForLoopSection)
363 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000364 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000365 }
366 };
367
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000368 /// \brief Appends the next token to \p State and updates information
369 /// necessary for indentation.
370 ///
371 /// Puts the token on the current line if \p Newline is \c true and adds a
372 /// line break and necessary indentation otherwise.
373 ///
374 /// If \p DryRun is \c false, also creates and stores the required
375 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000376 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000377 const AnnotatedToken &Current = *State.NextToken;
378 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000379 assert(State.Stack.size());
380 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000381
Daniel Jasper4b866272013-02-01 11:00:45 +0000382 if (Current.Type == TT_ImplicitStringLiteral) {
383 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
384 State.NextToken->FormatTok.TokenLength;
385 if (State.NextToken->Children.empty())
386 State.NextToken = NULL;
387 else
388 State.NextToken = &State.NextToken->Children[0];
389 return;
390 }
391
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000393 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000394 if (Current.is(tok::r_brace)) {
395 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000396 } else if (Current.is(tok::string_literal) &&
397 Previous.is(tok::string_literal)) {
398 State.Column = State.Column - Previous.FormatTok.TokenLength;
399 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000400 State.Stack[ParenLevel].FirstLessLess != 0) {
401 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000402 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000403 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000404 Current.is(tok::period) || Current.is(tok::arrow) ||
405 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000406 // Indent and extra 4 spaces after if we know the current expression is
407 // continued. Don't do that on the top level, as we already indent 4
408 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000409 State.Column = std::max(State.Stack.back().LastSpace,
410 State.Stack.back().Indent) + 4;
411 } else if (Current.Type == TT_ConditionalExpr) {
412 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000413 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
414 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
415 ParenLevel == 0)) {
416 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000417 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
418 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000419 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000420 } else if (Previous.Type == TT_BinaryOperator &&
421 State.Stack.back().AssignmentColumn != 0) {
422 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000423 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000425 }
426
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000427 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
428 State.Stack.back().BreakAfterComma = false;
429
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000430 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000431 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000432
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000433 if (!DryRun) {
434 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000435 Whitespaces.replaceWhitespace(Current, 1, State.Column,
436 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000437 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000438 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
439 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000440 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000441
Daniel Jasper337816e2013-01-11 10:22:12 +0000442 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000443 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000444 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000445 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000446 if (Current.is(tok::equal) &&
447 (RootToken.is(tok::kw_for) || ParenLevel == 0))
448 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000449
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000450 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
451 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000452 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000453
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000455 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000456
Daniel Jasperbcab4302013-01-09 10:40:23 +0000457 // FIXME: Do we need to do this for assignments nested in other
458 // expressions?
459 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000460 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000461 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000462 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000463 if (Current.Type != TT_LineComment &&
464 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
465 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000466 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000467 if (Previous.is(tok::comma) && Current.Type != TT_LineComment)
Daniel Jasper9278eb92013-01-16 14:59:02 +0000468 State.Stack[ParenLevel].HasMultiParameterLine = true;
469
Daniel Jaspere9de2602012-12-06 09:56:08 +0000470 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000471 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
472 // Treat the condition inside an if as if it was a second function
473 // parameter, i.e. let nested calls have an indent of 4.
474 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000475 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000476 // Top-level spaces are exempt as that mostly leads to better results.
477 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000478 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000479 Previous.Type == TT_ConditionalExpr ||
480 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000481 getPrecedence(Previous) != prec::Assignment)
482 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000483 else if (Previous.ParameterCount > 1 &&
484 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000485 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000486 Previous.Type == TT_TemplateOpener))
487 // If this function has multiple parameters, indent nested calls from
488 // the start of the first parameter.
489 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000490 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000491
492 // If we break after an {, we should also break before the corresponding }.
493 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000494 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000495
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000496 if (State.Stack.back().AvoidBinPacking && Newline) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000497 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000498 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000499 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
500 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000501 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
502 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000503 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000504
Daniel Jaspere941b162013-01-23 10:08:28 +0000505 // Any break on this level means that the parent level has been broken
506 // and we need to avoid bin packing there.
507 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
508 State.Stack[i].BreakAfterComma = true;
509 }
510 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000511
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000512 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000513 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000514
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000515 /// \brief Mark the next token as consumed in \p State and modify its stacks
516 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000517 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000518 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000520
Daniel Jasper337816e2013-01-11 10:22:12 +0000521 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
522 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000523 if (Current.is(tok::question))
524 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000525 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000526 !Current.MatchingParen->MustBreakBefore) {
527 AnnotatedToken *End = Current.MatchingParen;
528 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
529 End = &End->Children[0];
530 }
531 unsigned Length = End->TotalLength - Current.TotalLength + 1;
532 if (Length + State.Column > getColumnLimit())
533 State.Stack.back().BreakAfterComma = true;
534 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000535
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000536 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000537 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000538 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
539 Current.is(tok::l_brace) ||
540 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000541 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000542 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000543 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000544 NewIndent = 2 + State.Stack.back().LastSpace;
545 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000546 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000547 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000548 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000549 }
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000550 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
551 AvoidBinPacking));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000552 }
553
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000554 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000555 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000556 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
557 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
558 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000561
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000562 if (State.NextToken->Children.empty())
563 State.NextToken = NULL;
564 else
565 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000566
567 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 }
569
Daniel Jasper2df93312013-01-09 10:16:05 +0000570 unsigned getColumnLimit() {
571 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
572 }
573
Daniel Jasper4b866272013-02-01 11:00:45 +0000574 /// \brief An edge in the solution space starting from the \c LineState and
575 /// inserting a newline dependent on the \c bool.
576 typedef std::pair<bool, const LineState *> Edge;
577
578 /// \brief An item in the prioritized BFS search queue. The \c LineState was
579 /// reached using the \c Edge.
580 typedef std::pair<LineState, Edge> QueueItem;
581
582 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000584 /// This implements a variant of Dijkstra's algorithm on the graph that spans
585 /// the solution space (\c LineStates are the nodes). The algorithm tries to
586 /// find the shortest path (the one with lowest penalty) from \p InitialState
587 /// to a state where all tokens are placed.
588 unsigned analyzeSolutionSpace(const LineState &InitialState) {
589 // Insert start element into queue.
590 std::multimap<unsigned, QueueItem> Queue;
591 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000592 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000593 std::map<LineState, Edge> Seen;
594
595 // While not empty, take first element and follow edges.
596 while (!Queue.empty()) {
597 unsigned Penalty = Queue.begin()->first;
598 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000599 if (Item.first.NextToken == NULL) {
600 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000601 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000602 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000603 Queue.erase(Queue.begin());
604
605 if (Seen.find(Item.first) != Seen.end())
606 continue; // State already examined with lower penalty.
607
608 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
609 Item.first,
610 Edge(Item.second.first, Item.second.second))).first->first;
611
612 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
613 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
614 }
615
616 if (Queue.empty())
617 // We were unable to find a solution, do nothing.
618 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000619 return 0;
620
Daniel Jasper4b866272013-02-01 11:00:45 +0000621 // Reconstruct the solution.
622 // FIXME: Add debugging output.
623 Edge *CurrentEdge = &Queue.begin()->second.second;
624 while (CurrentEdge->second != NULL) {
625 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000626 if (CurrentEdge->first) {
627 DEBUG(llvm::errs() << "Penalty for splitting before "
628 << CurrentState.NextToken->FormatTok.Tok.getName()
629 << ": " << CurrentState.NextToken->SplitPenalty
630 << "\n");
631 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000632 addTokenToState(CurrentEdge->first, false, CurrentState);
633 CurrentEdge = &Seen[*CurrentEdge->second];
634 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000635 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000636
Daniel Jasper4b866272013-02-01 11:00:45 +0000637 // Return the column after the last token of the solution.
638 return Queue.begin()->second.first.Column;
639 }
640
641 /// \brief Add the following state to the analysis queue \p Queue.
642 ///
643 /// Assume the current state is \p OldState and has been reached with a
644 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
645 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
646 bool NewLine,
647 std::multimap<unsigned, QueueItem> &Queue) {
648 if (NewLine && !canBreak(OldState))
649 return;
650 if (!NewLine && mustBreak(OldState))
651 return;
652 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000653 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000654 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000655 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000656 if (State.Column > getColumnLimit()) {
657 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000658 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000659 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000660 Queue.insert(std::pair<unsigned, QueueItem>(
661 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
662 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000663
Daniel Jasper4b866272013-02-01 11:00:45 +0000664 /// \brief Returns \c true, if a line break after \p State is allowed.
665 bool canBreak(const LineState &State) {
666 if (!State.NextToken->CanBreakBefore &&
667 !(State.NextToken->is(tok::r_brace) &&
668 State.Stack.back().BreakBeforeClosingBrace))
669 return false;
670 // Trying to insert a parameter on a new line if there are already more than
671 // one parameter on the current line is bin packing.
672 if (State.NextToken->Parent->is(tok::comma) &&
673 State.Stack.back().HasMultiParameterLine &&
674 State.Stack.back().AvoidBinPacking)
675 return false;
676 return true;
677 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000678
Daniel Jasper4b866272013-02-01 11:00:45 +0000679 /// \brief Returns \c true, if a line break after \p State is mandatory.
680 bool mustBreak(const LineState &State) {
681 if (State.NextToken->MustBreakBefore)
682 return true;
683 if (State.NextToken->is(tok::r_brace) &&
684 State.Stack.back().BreakBeforeClosingBrace)
685 return true;
686 if (State.NextToken->Parent->is(tok::semi) &&
687 State.LineContainsContinuedForLoopSection)
688 return true;
689 if (State.NextToken->Parent->is(tok::comma) &&
690 State.Stack.back().BreakAfterComma &&
691 State.NextToken->Type != TT_LineComment)
692 return true;
693 if ((State.NextToken->Type == TT_CtorInitializerColon ||
694 (State.NextToken->Parent->ClosesTemplateDeclaration &&
695 State.Stack.size() == 1)))
696 return true;
697 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 }
699
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 FormatStyle Style;
701 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000702 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000703 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000704 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000705 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000706};
707
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000708class LexerBasedFormatTokenSource : public FormatTokenSource {
709public:
710 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000711 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000712 IdentTable(Lex.getLangOpts()) {
713 Lex.SetKeepWhitespaceMode(true);
714 }
715
716 virtual FormatToken getNextToken() {
717 if (GreaterStashed) {
718 FormatTok.NewlinesBefore = 0;
719 FormatTok.WhiteSpaceStart =
720 FormatTok.Tok.getLocation().getLocWithOffset(1);
721 FormatTok.WhiteSpaceLength = 0;
722 GreaterStashed = false;
723 return FormatTok;
724 }
725
726 FormatTok = FormatToken();
727 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000728 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000729 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000730 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
731 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000732
733 // Consume and record whitespace until we find a significant token.
734 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000735 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000736 FormatTok.HasUnescapedNewline =
737 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000738 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
739
740 if (FormatTok.Tok.is(tok::eof))
741 return FormatTok;
742 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000743 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000744 }
Manuel Klimekef920692013-01-07 07:56:50 +0000745
746 // Now FormatTok is the next non-whitespace token.
747 FormatTok.TokenLength = Text.size();
748
Manuel Klimek1abf7892013-01-04 23:34:14 +0000749 // In case the token starts with escaped newlines, we want to
750 // take them into account as whitespace - this pattern is quite frequent
751 // in macro definitions.
752 // FIXME: What do we want to do with other escaped spaces, and escaped
753 // spaces or newlines in the middle of tokens?
754 // FIXME: Add a more explicit test.
755 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000756 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000757 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000758 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000759 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000760 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000761 }
762
763 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000764 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000765 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000766 FormatTok.Tok.setKind(Info.getTokenID());
767 }
768
769 if (FormatTok.Tok.is(tok::greatergreater)) {
770 FormatTok.Tok.setKind(tok::greater);
771 GreaterStashed = true;
772 }
773
774 return FormatTok;
775 }
776
777private:
778 FormatToken FormatTok;
779 bool GreaterStashed;
780 Lexer &Lex;
781 SourceManager &SourceMgr;
782 IdentifierTable IdentTable;
783
784 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000785 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000786 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
787 Tok.getLength());
788 }
789};
790
Daniel Jasperf7935112012-12-03 18:12:45 +0000791class Formatter : public UnwrappedLineConsumer {
792public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000793 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
794 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000795 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000796 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000797 Whitespaces(SourceMgr), Ranges(Ranges) {
798 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000799
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000800 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000801
Daniel Jasperf7935112012-12-03 18:12:45 +0000802 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000803 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000804 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000805 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000806 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000807 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
808 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
809 Annotator.annotate();
810 }
811 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
812 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000813 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000814 const AnnotatedLine &TheLine = *I;
815 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000816 unsigned Indent =
817 formatFirstToken(TheLine.First, TheLine.Level,
818 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000819 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000820 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000821 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000822 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000823 PreviousEndOfLineColumn = Formatter.format();
824 } else {
825 // If we did not reformat this unwrapped line, the column at the end of
826 // the last token is unchanged - thus, we can calculate the end of the
827 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000828 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000829 SourceMgr.getSpellingColumnNumber(
830 TheLine.Last->FormatTok.Tok.getLocation()) +
831 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000832 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000833 }
834 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000835 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000836 }
837
838private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000839 /// \brief Tries to merge lines into one.
840 ///
841 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
842 /// if possible; note that \c I will be incremented when lines are merged.
843 ///
844 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000845 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000846 std::vector<AnnotatedLine>::iterator &I,
847 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000848 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
849
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000850 // We can never merge stuff if there are trailing line comments.
851 if (I->Last->Type == TT_LineComment)
852 return;
853
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000854 // Check whether the UnwrappedLine can be put onto a single line. If
855 // so, this is bound to be the optimal solution (by definition) and we
856 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000857 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000858 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000859 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000860
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000861 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000862 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000863
Daniel Jasper25837aa2013-01-14 14:14:23 +0000864 if (I->Last->is(tok::l_brace)) {
865 tryMergeSimpleBlock(I, E, Limit);
866 } else if (I->First.is(tok::kw_if)) {
867 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000868 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
869 I->First.FormatTok.IsFirst)) {
870 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000871 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000872 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000873 }
874
Daniel Jasper39825ea2013-01-14 15:40:57 +0000875 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
876 std::vector<AnnotatedLine>::iterator E,
877 unsigned Limit) {
878 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000879 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
880 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000881 if (I + 2 != E && (I + 2)->InPPDirective &&
882 !(I + 2)->First.FormatTok.HasUnescapedNewline)
883 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000884 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000885 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000886 join(Line, *(++I));
887 }
888
Daniel Jasper25837aa2013-01-14 14:14:23 +0000889 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
890 std::vector<AnnotatedLine>::iterator E,
891 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000892 if (!Style.AllowShortIfStatementsOnASingleLine)
893 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000894 if ((I + 1)->InPPDirective != I->InPPDirective ||
895 ((I + 1)->InPPDirective &&
896 (I + 1)->First.FormatTok.HasUnescapedNewline))
897 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000898 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000899 if (Line.Last->isNot(tok::r_paren))
900 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000901 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000902 return;
903 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
904 return;
905 // Only inline simple if's (no nested if or else).
906 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
907 return;
908 join(Line, *(++I));
909 }
910
911 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000912 std::vector<AnnotatedLine>::iterator E,
913 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000914 // First, check that the current line allows merging. This is the case if
915 // we're not in a control flow statement and the last token is an opening
916 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000917 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000918 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000919 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
920 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
921 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
922 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +0000923 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000924 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
925 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000926 if (!AllowedTokens)
927 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000928
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000929 AnnotatedToken *Tok = &(I + 1)->First;
930 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
931 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
932 Tok->SpaceRequiredBefore = false;
933 join(Line, *(I + 1));
934 I += 1;
935 } else {
936 // Check that we still have three lines and they fit into the limit.
937 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
938 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +0000939 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000940
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000941 // Second, check that the next line does not contain any braces - if it
942 // does, readability declines when putting it into a single line.
943 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
944 return;
945 do {
946 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
947 return;
948 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
949 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000950
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000951 // Last, check that the third line contains a single closing brace.
952 Tok = &(I + 2)->First;
953 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
954 Tok->MustBreakBefore)
955 return;
956
957 join(Line, *(I + 1));
958 join(Line, *(I + 2));
959 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000960 }
Daniel Jasper25837aa2013-01-14 14:14:23 +0000961 }
962
963 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
964 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000965 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
966 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000967 }
968
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000969 void join(AnnotatedLine &A, const AnnotatedLine &B) {
970 A.Last->Children.push_back(B.First);
971 while (!A.Last->Children.empty()) {
972 A.Last->Children[0].Parent = A.Last;
973 A.Last = &A.Last->Children[0];
974 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000975 }
976
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000977 bool touchesRanges(const AnnotatedLine &TheLine) {
978 const FormatToken *First = &TheLine.First.FormatTok;
979 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000980 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +0000981 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +0000982 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000983 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
984 Ranges[i].getBegin()) &&
985 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
986 LineRange.getBegin()))
987 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000988 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000989 return false;
990 }
991
992 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000993 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 }
995
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000996 /// \brief Add a new line and the required indent before the first Token
997 /// of the \c UnwrappedLine if there was no structural parsing error.
998 /// Returns the indent level of the \c UnwrappedLine.
999 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1000 bool InPPDirective,
1001 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001002 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001003 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1004 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1005
Daniel Jasperbbc84152013-01-29 11:27:30 +00001006 unsigned Newlines =
1007 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001008 if (Newlines == 0 && !Tok.IsFirst)
1009 Newlines = 1;
1010 unsigned Indent = Level * 2;
1011
1012 bool IsAccessModifier = false;
1013 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1014 RootToken.is(tok::kw_private))
1015 IsAccessModifier = true;
1016 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1017 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1018 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1019 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1020 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1021 IsAccessModifier = true;
1022
1023 if (IsAccessModifier &&
1024 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1025 Indent += Style.AccessModifierOffset;
1026 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001027 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001028 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001029 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1030 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001031 }
1032 return Indent;
1033 }
1034
Alexander Kornienko116ba682013-01-14 11:34:14 +00001035 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 FormatStyle Style;
1037 Lexer &Lex;
1038 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001039 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001041 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001042 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001043};
1044
Daniel Jasperbbc84152013-01-29 11:27:30 +00001045tooling::Replacements
1046reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1047 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001048 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001049 OwningPtr<DiagnosticConsumer> DiagPrinter;
1050 if (DiagClient == 0) {
1051 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1052 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1053 DiagClient = DiagPrinter.get();
1054 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001055 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001056 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001057 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001058 Diagnostics.setSourceManager(&SourceMgr);
1059 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001060 return formatter.format();
1061}
1062
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001063LangOptions getFormattingLangOpts() {
1064 LangOptions LangOpts;
1065 LangOpts.CPlusPlus = 1;
1066 LangOpts.CPlusPlus11 = 1;
1067 LangOpts.Bool = 1;
1068 LangOpts.ObjC1 = 1;
1069 LangOpts.ObjC2 = 1;
1070 return LangOpts;
1071}
1072
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001073} // namespace format
1074} // namespace clang