blob: 2f14fc0ce15bdedce9d70748bde47139d5900d8b [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 Jasperf7f13c02013-02-04 07:30:30 +0000496 if (State.Stack.back().AvoidBinPacking && Newline &&
497 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000498 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000499 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000500 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
501 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000502 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
503 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000504 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000505
Daniel Jaspere941b162013-01-23 10:08:28 +0000506 // Any break on this level means that the parent level has been broken
507 // and we need to avoid bin packing there.
508 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000509 if (Line.First.isNot(tok::kw_for) || i != 1)
510 State.Stack[i].BreakAfterComma = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000511 }
512 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000513
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000514 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000515 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000516
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000517 /// \brief Mark the next token as consumed in \p State and modify its stacks
518 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000520 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000521 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000522
Daniel Jasper337816e2013-01-11 10:22:12 +0000523 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
524 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000525 if (Current.is(tok::question))
526 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000527 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000528 !Current.MatchingParen->MustBreakBefore) {
529 AnnotatedToken *End = Current.MatchingParen;
530 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
531 End = &End->Children[0];
532 }
533 unsigned Length = End->TotalLength - Current.TotalLength + 1;
534 if (Length + State.Column > getColumnLimit())
535 State.Stack.back().BreakAfterComma = true;
536 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000537
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000538 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000539 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000540 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
541 Current.is(tok::l_brace) ||
542 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000544 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000545 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000546 NewIndent = 2 + State.Stack.back().LastSpace;
547 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000549 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000550 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000551 }
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000552 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
553 AvoidBinPacking));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554 }
555
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000556 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000558 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
559 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
560 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000562 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000563
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000564 if (State.NextToken->Children.empty())
565 State.NextToken = NULL;
566 else
567 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000568
569 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 }
571
Daniel Jasper2df93312013-01-09 10:16:05 +0000572 unsigned getColumnLimit() {
573 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
574 }
575
Daniel Jasper4b866272013-02-01 11:00:45 +0000576 /// \brief An edge in the solution space starting from the \c LineState and
577 /// inserting a newline dependent on the \c bool.
578 typedef std::pair<bool, const LineState *> Edge;
579
580 /// \brief An item in the prioritized BFS search queue. The \c LineState was
581 /// reached using the \c Edge.
582 typedef std::pair<LineState, Edge> QueueItem;
583
584 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000586 /// This implements a variant of Dijkstra's algorithm on the graph that spans
587 /// the solution space (\c LineStates are the nodes). The algorithm tries to
588 /// find the shortest path (the one with lowest penalty) from \p InitialState
589 /// to a state where all tokens are placed.
590 unsigned analyzeSolutionSpace(const LineState &InitialState) {
591 // Insert start element into queue.
592 std::multimap<unsigned, QueueItem> Queue;
593 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000594 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000595 std::map<LineState, Edge> Seen;
596
597 // While not empty, take first element and follow edges.
598 while (!Queue.empty()) {
599 unsigned Penalty = Queue.begin()->first;
600 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000601 if (Item.first.NextToken == NULL) {
602 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000603 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000604 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000605 Queue.erase(Queue.begin());
606
607 if (Seen.find(Item.first) != Seen.end())
608 continue; // State already examined with lower penalty.
609
610 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
611 Item.first,
612 Edge(Item.second.first, Item.second.second))).first->first;
613
614 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
615 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
616 }
617
618 if (Queue.empty())
619 // We were unable to find a solution, do nothing.
620 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000621 return 0;
622
Daniel Jasper4b866272013-02-01 11:00:45 +0000623 // Reconstruct the solution.
624 // FIXME: Add debugging output.
625 Edge *CurrentEdge = &Queue.begin()->second.second;
626 while (CurrentEdge->second != NULL) {
627 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000628 if (CurrentEdge->first) {
629 DEBUG(llvm::errs() << "Penalty for splitting before "
630 << CurrentState.NextToken->FormatTok.Tok.getName()
631 << ": " << CurrentState.NextToken->SplitPenalty
632 << "\n");
633 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000634 addTokenToState(CurrentEdge->first, false, CurrentState);
635 CurrentEdge = &Seen[*CurrentEdge->second];
636 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000637 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000638
Daniel Jasper4b866272013-02-01 11:00:45 +0000639 // Return the column after the last token of the solution.
640 return Queue.begin()->second.first.Column;
641 }
642
643 /// \brief Add the following state to the analysis queue \p Queue.
644 ///
645 /// Assume the current state is \p OldState and has been reached with a
646 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
647 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
648 bool NewLine,
649 std::multimap<unsigned, QueueItem> &Queue) {
650 if (NewLine && !canBreak(OldState))
651 return;
652 if (!NewLine && mustBreak(OldState))
653 return;
654 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000655 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000656 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000657 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000658 if (State.Column > getColumnLimit()) {
659 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000660 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000661 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000662 Queue.insert(std::pair<unsigned, QueueItem>(
663 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
664 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000665
Daniel Jasper4b866272013-02-01 11:00:45 +0000666 /// \brief Returns \c true, if a line break after \p State is allowed.
667 bool canBreak(const LineState &State) {
668 if (!State.NextToken->CanBreakBefore &&
669 !(State.NextToken->is(tok::r_brace) &&
670 State.Stack.back().BreakBeforeClosingBrace))
671 return false;
672 // Trying to insert a parameter on a new line if there are already more than
673 // one parameter on the current line is bin packing.
674 if (State.NextToken->Parent->is(tok::comma) &&
675 State.Stack.back().HasMultiParameterLine &&
676 State.Stack.back().AvoidBinPacking)
677 return false;
678 return true;
679 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000680
Daniel Jasper4b866272013-02-01 11:00:45 +0000681 /// \brief Returns \c true, if a line break after \p State is mandatory.
682 bool mustBreak(const LineState &State) {
683 if (State.NextToken->MustBreakBefore)
684 return true;
685 if (State.NextToken->is(tok::r_brace) &&
686 State.Stack.back().BreakBeforeClosingBrace)
687 return true;
688 if (State.NextToken->Parent->is(tok::semi) &&
689 State.LineContainsContinuedForLoopSection)
690 return true;
691 if (State.NextToken->Parent->is(tok::comma) &&
692 State.Stack.back().BreakAfterComma &&
693 State.NextToken->Type != TT_LineComment)
694 return true;
695 if ((State.NextToken->Type == TT_CtorInitializerColon ||
696 (State.NextToken->Parent->ClosesTemplateDeclaration &&
697 State.Stack.size() == 1)))
698 return true;
699 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 }
701
Daniel Jasperf7935112012-12-03 18:12:45 +0000702 FormatStyle Style;
703 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000704 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000705 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000706 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000707 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000708};
709
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000710class LexerBasedFormatTokenSource : public FormatTokenSource {
711public:
712 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000713 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000714 IdentTable(Lex.getLangOpts()) {
715 Lex.SetKeepWhitespaceMode(true);
716 }
717
718 virtual FormatToken getNextToken() {
719 if (GreaterStashed) {
720 FormatTok.NewlinesBefore = 0;
721 FormatTok.WhiteSpaceStart =
722 FormatTok.Tok.getLocation().getLocWithOffset(1);
723 FormatTok.WhiteSpaceLength = 0;
724 GreaterStashed = false;
725 return FormatTok;
726 }
727
728 FormatTok = FormatToken();
729 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000730 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000731 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000732 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
733 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000734
735 // Consume and record whitespace until we find a significant token.
736 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000737 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000738 FormatTok.HasUnescapedNewline =
739 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000740 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
741
742 if (FormatTok.Tok.is(tok::eof))
743 return FormatTok;
744 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000745 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000746 }
Manuel Klimekef920692013-01-07 07:56:50 +0000747
748 // Now FormatTok is the next non-whitespace token.
749 FormatTok.TokenLength = Text.size();
750
Manuel Klimek1abf7892013-01-04 23:34:14 +0000751 // In case the token starts with escaped newlines, we want to
752 // take them into account as whitespace - this pattern is quite frequent
753 // in macro definitions.
754 // FIXME: What do we want to do with other escaped spaces, and escaped
755 // spaces or newlines in the middle of tokens?
756 // FIXME: Add a more explicit test.
757 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000758 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000759 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000760 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000761 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000762 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000763 }
764
765 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000766 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000767 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000768 FormatTok.Tok.setKind(Info.getTokenID());
769 }
770
771 if (FormatTok.Tok.is(tok::greatergreater)) {
772 FormatTok.Tok.setKind(tok::greater);
773 GreaterStashed = true;
774 }
775
776 return FormatTok;
777 }
778
779private:
780 FormatToken FormatTok;
781 bool GreaterStashed;
782 Lexer &Lex;
783 SourceManager &SourceMgr;
784 IdentifierTable IdentTable;
785
786 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000787 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000788 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
789 Tok.getLength());
790 }
791};
792
Daniel Jasperf7935112012-12-03 18:12:45 +0000793class Formatter : public UnwrappedLineConsumer {
794public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000795 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
796 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000797 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000798 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000799 Whitespaces(SourceMgr), Ranges(Ranges) {
800 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000801
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000802 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000803
Daniel Jasperf7935112012-12-03 18:12:45 +0000804 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000805 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000806 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000807 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000808 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000809 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
810 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
811 Annotator.annotate();
812 }
813 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
814 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000815 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000816 const AnnotatedLine &TheLine = *I;
817 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000818 unsigned Indent =
819 formatFirstToken(TheLine.First, TheLine.Level,
820 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000821 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000822 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000823 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000824 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000825 PreviousEndOfLineColumn = Formatter.format();
826 } else {
827 // If we did not reformat this unwrapped line, the column at the end of
828 // the last token is unchanged - thus, we can calculate the end of the
829 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000830 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000831 SourceMgr.getSpellingColumnNumber(
832 TheLine.Last->FormatTok.Tok.getLocation()) +
833 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000834 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000835 }
836 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000837 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 }
839
840private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000841 /// \brief Tries to merge lines into one.
842 ///
843 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
844 /// if possible; note that \c I will be incremented when lines are merged.
845 ///
846 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000847 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000848 std::vector<AnnotatedLine>::iterator &I,
849 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000850 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
851
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000852 // We can never merge stuff if there are trailing line comments.
853 if (I->Last->Type == TT_LineComment)
854 return;
855
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000856 // Check whether the UnwrappedLine can be put onto a single line. If
857 // so, this is bound to be the optimal solution (by definition) and we
858 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000859 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000860 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000861 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000862
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000863 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000864 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000865
Daniel Jasper25837aa2013-01-14 14:14:23 +0000866 if (I->Last->is(tok::l_brace)) {
867 tryMergeSimpleBlock(I, E, Limit);
868 } else if (I->First.is(tok::kw_if)) {
869 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000870 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
871 I->First.FormatTok.IsFirst)) {
872 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000873 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000874 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000875 }
876
Daniel Jasper39825ea2013-01-14 15:40:57 +0000877 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
878 std::vector<AnnotatedLine>::iterator E,
879 unsigned Limit) {
880 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000881 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
882 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000883 if (I + 2 != E && (I + 2)->InPPDirective &&
884 !(I + 2)->First.FormatTok.HasUnescapedNewline)
885 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000886 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000887 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000888 join(Line, *(++I));
889 }
890
Daniel Jasper25837aa2013-01-14 14:14:23 +0000891 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
892 std::vector<AnnotatedLine>::iterator E,
893 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000894 if (!Style.AllowShortIfStatementsOnASingleLine)
895 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000896 if ((I + 1)->InPPDirective != I->InPPDirective ||
897 ((I + 1)->InPPDirective &&
898 (I + 1)->First.FormatTok.HasUnescapedNewline))
899 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000900 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000901 if (Line.Last->isNot(tok::r_paren))
902 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000903 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000904 return;
905 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
906 return;
907 // Only inline simple if's (no nested if or else).
908 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
909 return;
910 join(Line, *(++I));
911 }
912
913 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000914 std::vector<AnnotatedLine>::iterator E,
915 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000916 // First, check that the current line allows merging. This is the case if
917 // we're not in a control flow statement and the last token is an opening
918 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000919 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000920 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000921 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
922 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
923 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
924 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +0000925 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000926 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
927 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000928 if (!AllowedTokens)
929 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000930
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000931 AnnotatedToken *Tok = &(I + 1)->First;
932 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
933 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
934 Tok->SpaceRequiredBefore = false;
935 join(Line, *(I + 1));
936 I += 1;
937 } else {
938 // Check that we still have three lines and they fit into the limit.
939 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
940 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +0000941 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000942
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000943 // Second, check that the next line does not contain any braces - if it
944 // does, readability declines when putting it into a single line.
945 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
946 return;
947 do {
948 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
949 return;
950 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
951 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000952
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000953 // Last, check that the third line contains a single closing brace.
954 Tok = &(I + 2)->First;
955 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
956 Tok->MustBreakBefore)
957 return;
958
959 join(Line, *(I + 1));
960 join(Line, *(I + 2));
961 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000962 }
Daniel Jasper25837aa2013-01-14 14:14:23 +0000963 }
964
965 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
966 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000967 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
968 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000969 }
970
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000971 void join(AnnotatedLine &A, const AnnotatedLine &B) {
972 A.Last->Children.push_back(B.First);
973 while (!A.Last->Children.empty()) {
974 A.Last->Children[0].Parent = A.Last;
975 A.Last = &A.Last->Children[0];
976 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000977 }
978
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000979 bool touchesRanges(const AnnotatedLine &TheLine) {
980 const FormatToken *First = &TheLine.First.FormatTok;
981 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000982 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +0000983 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000985 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
986 Ranges[i].getBegin()) &&
987 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
988 LineRange.getBegin()))
989 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000990 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000991 return false;
992 }
993
994 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000995 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +0000996 }
997
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000998 /// \brief Add a new line and the required indent before the first Token
999 /// of the \c UnwrappedLine if there was no structural parsing error.
1000 /// Returns the indent level of the \c UnwrappedLine.
1001 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1002 bool InPPDirective,
1003 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001004 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001005 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1006 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1007
Daniel Jasperbbc84152013-01-29 11:27:30 +00001008 unsigned Newlines =
1009 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001010 if (Newlines == 0 && !Tok.IsFirst)
1011 Newlines = 1;
1012 unsigned Indent = Level * 2;
1013
1014 bool IsAccessModifier = false;
1015 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1016 RootToken.is(tok::kw_private))
1017 IsAccessModifier = true;
1018 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1019 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1020 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1021 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1022 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1023 IsAccessModifier = true;
1024
1025 if (IsAccessModifier &&
1026 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1027 Indent += Style.AccessModifierOffset;
1028 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001029 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001030 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001031 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1032 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001033 }
1034 return Indent;
1035 }
1036
Alexander Kornienko116ba682013-01-14 11:34:14 +00001037 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001038 FormatStyle Style;
1039 Lexer &Lex;
1040 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001041 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001042 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001043 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001044 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001045};
1046
Daniel Jasperbbc84152013-01-29 11:27:30 +00001047tooling::Replacements
1048reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1049 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001050 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001051 OwningPtr<DiagnosticConsumer> DiagPrinter;
1052 if (DiagClient == 0) {
1053 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1054 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1055 DiagClient = DiagPrinter.get();
1056 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001057 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001058 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001059 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001060 Diagnostics.setSourceManager(&SourceMgr);
1061 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 return formatter.format();
1063}
1064
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001065LangOptions getFormattingLangOpts() {
1066 LangOptions LangOpts;
1067 LangOpts.CPlusPlus = 1;
1068 LangOpts.CPlusPlus11 = 1;
1069 LangOpts.Bool = 1;
1070 LangOpts.ObjC1 = 1;
1071 LangOpts.ObjC2 = 1;
1072 return LangOpts;
1073}
1074
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001075} // namespace format
1076} // namespace clang