blob: 47d6340cfdfb78e1d9d0af0a941d1fe67d2bb36f [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper32d28ee2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimekca547db2013-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 Jasperbac016b2012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000061 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000062 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000063 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +000064 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000065 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +000070 return GoogleStyle;
71}
72
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000073FormatStyle getChromiumStyle() {
74 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000075 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperf40fb4b2013-01-29 15:19:38 +000076 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000077 return ChromiumStyle;
78}
79
Daniel Jasperdcc2a622013-01-18 08:44:07 +000080/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +000081///
Daniel Jasperdcc2a622013-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 Jasper821627e2013-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 Jasperdcc2a622013-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 Jasper1a1ce832013-01-29 11:27:30 +0000108 Comments.back().MaxColumn =
109 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000110 return;
111 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000112 }
Daniel Jasper821627e2013-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 Jasperdcc2a622013-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 Jasper1a1ce832013-01-29 11:27:30 +0000131 unsigned Offset =
132 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-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 Klimek3f8c7f32013-01-10 18:45:26 +0000188 }
189 }
Daniel Jasperdcc2a622013-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 Jasperafcbd852013-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 Jasperdcc2a622013-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 Klimek3f8c7f32013-01-10 18:45:26 +0000206
Daniel Jaspercda16502013-02-04 08:34:57 +0000207static bool isTrailingComment(const AnnotatedToken &Tok) {
208 return Tok.is(tok::comment) &&
209 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
210}
211
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212class UnwrappedLineFormatter {
213public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000214 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000215 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000216 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000217 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000218 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000219 FirstIndent(FirstIndent), RootToken(RootToken),
220 Whitespaces(Whitespaces) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000221 }
222
Manuel Klimekd4397b92013-01-04 23:34:14 +0000223 /// \brief Formats an \c UnwrappedLine.
224 ///
225 /// \returns The column after the last token in the last line of the
226 /// \c UnwrappedLine.
227 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000228 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000229 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000230 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000231 State.NextToken = &RootToken;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000232 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
233 !Style.BinPackParameters));
Daniel Jasper2e603772013-01-29 11:21:01 +0000234 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000235 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000236
Manuel Klimekca547db2013-01-16 14:55:28 +0000237 DEBUG({
238 DebugTokenState(*State.NextToken);
239 });
240
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000241 // The first token has already been indented and thus consumed.
242 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000243
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000244 // If everything fits on a single line, just put it there.
245 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
246 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000247 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000248 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000249 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000251
252 // Find best solution in solution space.
253 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000254 }
255
256private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000257 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
258 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000259 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
260 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000261 llvm::errs();
262 }
263
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000264 struct ParenState {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000265 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking)
Daniel Jasperf39c8852013-01-23 16:58:21 +0000266 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000267 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperf343cab2013-01-31 14:59:26 +0000268 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
269 HasMultiParameterLine(false) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000270 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000271
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272 /// \brief The position to which a specific parenthesis level needs to be
273 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000274 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000275
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000276 /// \brief The position of the last space on each level.
277 ///
278 /// Used e.g. to break like:
279 /// functionCall(Parameter, otherCall(
280 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000281 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000282
Daniel Jasperf39c8852013-01-23 16:58:21 +0000283 /// \brief This is the column of the first token after an assignment.
284 unsigned AssignmentColumn;
285
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000286 /// \brief The position the first "<<" operator encountered on each level.
287 ///
288 /// Used to align "<<" operators. 0 if no such operator has been encountered
289 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000290 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000291
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000292 /// \brief Whether a newline needs to be inserted before the block's closing
293 /// brace.
294 ///
295 /// We only want to insert a newline before the closing brace if there also
296 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000297 bool BreakBeforeClosingBrace;
298
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000299 /// \brief The column of a \c ? in a conditional expression;
300 unsigned QuestionColumn;
301
Daniel Jasperf343cab2013-01-31 14:59:26 +0000302 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
303 /// lines, in this context.
304 bool AvoidBinPacking;
305
306 /// \brief Break after the next comma (or all the commas in this context if
307 /// \c AvoidBinPacking is \c true).
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000308 bool BreakAfterComma;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000309
310 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000311 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000312
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000313 bool operator<(const ParenState &Other) const {
314 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000315 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000316 if (LastSpace != Other.LastSpace)
317 return LastSpace < Other.LastSpace;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000318 if (AssignmentColumn != Other.AssignmentColumn)
319 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000320 if (FirstLessLess != Other.FirstLessLess)
321 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000322 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
323 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000324 if (QuestionColumn != Other.QuestionColumn)
325 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000326 if (AvoidBinPacking != Other.AvoidBinPacking)
327 return AvoidBinPacking;
Daniel Jasperb3123142013-01-12 07:36:22 +0000328 if (BreakAfterComma != Other.BreakAfterComma)
329 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000330 if (HasMultiParameterLine != Other.HasMultiParameterLine)
331 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000332 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000333 }
334 };
335
336 /// \brief The current state when indenting a unwrapped line.
337 ///
338 /// As the indenting tries different combinations this is copied by value.
339 struct LineState {
340 /// \brief The number of used columns in the current line.
341 unsigned Column;
342
343 /// \brief The token that needs to be next formatted.
344 const AnnotatedToken *NextToken;
345
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000346 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000347 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000348 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000349 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000350
351 /// \brief \c true if this line contains a continued for-loop section.
352 bool LineContainsContinuedForLoopSection;
353
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000354 /// \brief A stack keeping track of properties applying to parenthesis
355 /// levels.
356 std::vector<ParenState> Stack;
357
358 /// \brief Comparison operator to be able to used \c LineState in \c map.
359 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000360 if (Other.NextToken != NextToken)
361 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000362 if (Other.Column != Column)
363 return Other.Column > Column;
Daniel Jasper2e603772013-01-29 11:21:01 +0000364 if (Other.VariablePos != VariablePos)
365 return Other.VariablePos < VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000366 if (Other.LineContainsContinuedForLoopSection !=
367 LineContainsContinuedForLoopSection)
368 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000369 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000370 }
371 };
372
Daniel Jasper20409152012-12-04 14:54:30 +0000373 /// \brief Appends the next token to \p State and updates information
374 /// necessary for indentation.
375 ///
376 /// Puts the token on the current line if \p Newline is \c true and adds a
377 /// line break and necessary indentation otherwise.
378 ///
379 /// If \p DryRun is \c false, also creates and stores the required
380 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000381 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000382 const AnnotatedToken &Current = *State.NextToken;
383 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000384 assert(State.Stack.size());
385 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000387 if (Current.Type == TT_ImplicitStringLiteral) {
388 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
389 State.NextToken->FormatTok.TokenLength;
390 if (State.NextToken->Children.empty())
391 State.NextToken = NULL;
392 else
393 State.NextToken = &State.NextToken->Children[0];
394 return;
395 }
396
Daniel Jasperbac016b2012-12-03 18:12:45 +0000397 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000398 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000399 if (Current.is(tok::r_brace)) {
400 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000401 } else if (Current.is(tok::string_literal) &&
402 Previous.is(tok::string_literal)) {
403 State.Column = State.Column - Previous.FormatTok.TokenLength;
404 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000405 State.Stack[ParenLevel].FirstLessLess != 0) {
406 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000407 } else if (ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000408 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000409 Current.is(tok::period) || Current.is(tok::arrow) ||
410 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000411 // Indent and extra 4 spaces after if we know the current expression is
412 // continued. Don't do that on the top level, as we already indent 4
413 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000414 State.Column = std::max(State.Stack.back().LastSpace,
415 State.Stack.back().Indent) + 4;
416 } else if (Current.Type == TT_ConditionalExpr) {
417 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000418 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
419 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
420 ParenLevel == 0)) {
421 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000422 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
423 Current.Type == TT_StartOfName) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000424 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000425 } else if (Previous.Type == TT_BinaryOperator &&
426 State.Stack.back().AssignmentColumn != 0) {
427 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000428 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000429 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000430 }
431
Daniel Jasperf343cab2013-01-31 14:59:26 +0000432 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
433 State.Stack.back().BreakAfterComma = false;
434
Daniel Jasper26f7e782013-01-08 14:56:18 +0000435 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000436 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000437
Manuel Klimek060143e2013-01-02 18:33:23 +0000438 if (!DryRun) {
439 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000440 Whitespaces.replaceWhitespace(Current, 1, State.Column,
441 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000442 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000443 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
444 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000445 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000446
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000447 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000448 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000449 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000450 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000451 if (Current.is(tok::equal) &&
452 (RootToken.is(tok::kw_for) || ParenLevel == 0))
453 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000454
Daniel Jasper26f7e782013-01-08 14:56:18 +0000455 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
456 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000457 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000458
Daniel Jasperbac016b2012-12-03 18:12:45 +0000459 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000460 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000461
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000462 // FIXME: Do we need to do this for assignments nested in other
463 // expressions?
464 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000465 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000466 Previous.is(tok::kw_return)))
Daniel Jasperf39c8852013-01-23 16:58:21 +0000467 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000468 if (Current.Type != TT_LineComment &&
469 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
470 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000471 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000472 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000473 State.Stack[ParenLevel].HasMultiParameterLine = true;
474
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000475 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000476 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
477 // Treat the condition inside an if as if it was a second function
478 // parameter, i.e. let nested calls have an indent of 4.
479 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper3499dda2013-01-25 15:43:32 +0000480 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000481 // Top-level spaces are exempt as that mostly leads to better results.
482 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000483 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000484 Previous.Type == TT_ConditionalExpr ||
485 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000486 getPrecedence(Previous) != prec::Assignment)
487 State.Stack.back().LastSpace = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000488 else if (Previous.ParameterCount > 1 &&
489 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000490 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000491 Previous.Type == TT_TemplateOpener))
492 // If this function has multiple parameters, indent nested calls from
493 // the start of the first parameter.
494 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000496
497 // If we break after an {, we should also break before the corresponding }.
498 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000499 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000500
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000501 if (State.Stack.back().AvoidBinPacking && Newline &&
502 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000503 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000504 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000505 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
506 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000507 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
508 Line.MustBeDeclaration))
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000509 State.Stack.back().BreakAfterComma = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000510
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000511 // Any break on this level means that the parent level has been broken
512 // and we need to avoid bin packing there.
513 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000514 if (Line.First.isNot(tok::kw_for) || i != 1)
515 State.Stack[i].BreakAfterComma = true;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000516 }
517 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000518
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000519 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000520 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000521
Daniel Jasper20409152012-12-04 14:54:30 +0000522 /// \brief Mark the next token as consumed in \p State and modify its stacks
523 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000524 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000525 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000526 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000527
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000528 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
529 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000530 if (Current.is(tok::question))
531 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000532 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasperf343cab2013-01-31 14:59:26 +0000533 !Current.MatchingParen->MustBreakBefore) {
534 AnnotatedToken *End = Current.MatchingParen;
535 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
536 End = &End->Children[0];
537 }
538 unsigned Length = End->TotalLength - Current.TotalLength + 1;
539 if (Length + State.Column > getColumnLimit())
540 State.Stack.back().BreakAfterComma = true;
541 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000542
Daniel Jaspercf225b62012-12-24 13:43:52 +0000543 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000544 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000545 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
546 Current.is(tok::l_brace) ||
547 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000548 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000549 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000550 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000551 NewIndent = 2 + State.Stack.back().LastSpace;
552 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000553 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000554 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000555 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000556 }
Daniel Jasperf343cab2013-01-31 14:59:26 +0000557 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
558 AvoidBinPacking));
Daniel Jasper20409152012-12-04 14:54:30 +0000559 }
560
Daniel Jaspercf225b62012-12-24 13:43:52 +0000561 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000562 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000563 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
564 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
565 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000566 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000567 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000568
Daniel Jasper26f7e782013-01-08 14:56:18 +0000569 if (State.NextToken->Children.empty())
570 State.NextToken = NULL;
571 else
572 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000573
574 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000575 }
576
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000577 unsigned getColumnLimit() {
578 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
579 }
580
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000581 /// \brief An edge in the solution space starting from the \c LineState and
582 /// inserting a newline dependent on the \c bool.
583 typedef std::pair<bool, const LineState *> Edge;
584
585 /// \brief An item in the prioritized BFS search queue. The \c LineState was
586 /// reached using the \c Edge.
587 typedef std::pair<LineState, Edge> QueueItem;
588
589 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000590 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000591 /// This implements a variant of Dijkstra's algorithm on the graph that spans
592 /// the solution space (\c LineStates are the nodes). The algorithm tries to
593 /// find the shortest path (the one with lowest penalty) from \p InitialState
594 /// to a state where all tokens are placed.
595 unsigned analyzeSolutionSpace(const LineState &InitialState) {
596 // Insert start element into queue.
597 std::multimap<unsigned, QueueItem> Queue;
598 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper01786732013-02-04 07:21:18 +0000599 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000600 std::map<LineState, Edge> Seen;
601
602 // While not empty, take first element and follow edges.
603 while (!Queue.empty()) {
604 unsigned Penalty = Queue.begin()->first;
605 QueueItem Item = Queue.begin()->second;
Daniel Jasper01786732013-02-04 07:21:18 +0000606 if (Item.first.NextToken == NULL) {
607 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000608 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000609 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000610 Queue.erase(Queue.begin());
611
612 if (Seen.find(Item.first) != Seen.end())
613 continue; // State already examined with lower penalty.
614
615 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
616 Item.first,
617 Edge(Item.second.first, Item.second.second))).first->first;
618
619 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
620 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
621 }
622
623 if (Queue.empty())
624 // We were unable to find a solution, do nothing.
625 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000626 return 0;
627
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000628 // Reconstruct the solution.
629 // FIXME: Add debugging output.
630 Edge *CurrentEdge = &Queue.begin()->second.second;
631 while (CurrentEdge->second != NULL) {
632 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper01786732013-02-04 07:21:18 +0000633 if (CurrentEdge->first) {
634 DEBUG(llvm::errs() << "Penalty for splitting before "
635 << CurrentState.NextToken->FormatTok.Tok.getName()
636 << ": " << CurrentState.NextToken->SplitPenalty
637 << "\n");
638 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000639 addTokenToState(CurrentEdge->first, false, CurrentState);
640 CurrentEdge = &Seen[*CurrentEdge->second];
641 }
Daniel Jasper01786732013-02-04 07:21:18 +0000642 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000643
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000644 // Return the column after the last token of the solution.
645 return Queue.begin()->second.first.Column;
646 }
647
648 /// \brief Add the following state to the analysis queue \p Queue.
649 ///
650 /// Assume the current state is \p OldState and has been reached with a
651 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
652 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
653 bool NewLine,
654 std::multimap<unsigned, QueueItem> &Queue) {
655 if (NewLine && !canBreak(OldState))
656 return;
657 if (!NewLine && mustBreak(OldState))
658 return;
659 LineState State(OldState);
Daniel Jasperae8699b2013-01-28 09:35:24 +0000660 if (NewLine)
Daniel Jasper01786732013-02-04 07:21:18 +0000661 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper20409152012-12-04 14:54:30 +0000662 addTokenToState(NewLine, true, State);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000663 if (State.Column > getColumnLimit()) {
664 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000665 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000666 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000667 Queue.insert(std::pair<unsigned, QueueItem>(
668 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
669 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000670
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000671 /// \brief Returns \c true, if a line break after \p State is allowed.
672 bool canBreak(const LineState &State) {
673 if (!State.NextToken->CanBreakBefore &&
674 !(State.NextToken->is(tok::r_brace) &&
675 State.Stack.back().BreakBeforeClosingBrace))
676 return false;
677 // Trying to insert a parameter on a new line if there are already more than
678 // one parameter on the current line is bin packing.
679 if (State.NextToken->Parent->is(tok::comma) &&
680 State.Stack.back().HasMultiParameterLine &&
681 State.Stack.back().AvoidBinPacking)
682 return false;
683 return true;
684 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000685
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000686 /// \brief Returns \c true, if a line break after \p State is mandatory.
687 bool mustBreak(const LineState &State) {
688 if (State.NextToken->MustBreakBefore)
689 return true;
690 if (State.NextToken->is(tok::r_brace) &&
691 State.Stack.back().BreakBeforeClosingBrace)
692 return true;
693 if (State.NextToken->Parent->is(tok::semi) &&
694 State.LineContainsContinuedForLoopSection)
695 return true;
696 if (State.NextToken->Parent->is(tok::comma) &&
697 State.Stack.back().BreakAfterComma &&
Daniel Jaspercda16502013-02-04 08:34:57 +0000698 !isTrailingComment(*State.NextToken))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000699 return true;
700 if ((State.NextToken->Type == TT_CtorInitializerColon ||
701 (State.NextToken->Parent->ClosesTemplateDeclaration &&
702 State.Stack.size() == 1)))
703 return true;
704 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000705 }
706
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 FormatStyle Style;
708 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000709 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000710 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000711 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000712 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000713};
714
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000715class LexerBasedFormatTokenSource : public FormatTokenSource {
716public:
717 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000718 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000719 IdentTable(Lex.getLangOpts()) {
720 Lex.SetKeepWhitespaceMode(true);
721 }
722
723 virtual FormatToken getNextToken() {
724 if (GreaterStashed) {
725 FormatTok.NewlinesBefore = 0;
726 FormatTok.WhiteSpaceStart =
727 FormatTok.Tok.getLocation().getLocWithOffset(1);
728 FormatTok.WhiteSpaceLength = 0;
729 GreaterStashed = false;
730 return FormatTok;
731 }
732
733 FormatTok = FormatToken();
734 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000735 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000736 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000737 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
738 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000739
740 // Consume and record whitespace until we find a significant token.
741 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000742 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000743 FormatTok.HasUnescapedNewline =
744 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000745 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
746
747 if (FormatTok.Tok.is(tok::eof))
748 return FormatTok;
749 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000750 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000751 }
Manuel Klimek95419382013-01-07 07:56:50 +0000752
753 // Now FormatTok is the next non-whitespace token.
754 FormatTok.TokenLength = Text.size();
755
Manuel Klimekd4397b92013-01-04 23:34:14 +0000756 // In case the token starts with escaped newlines, we want to
757 // take them into account as whitespace - this pattern is quite frequent
758 // in macro definitions.
759 // FIXME: What do we want to do with other escaped spaces, and escaped
760 // spaces or newlines in the middle of tokens?
761 // FIXME: Add a more explicit test.
762 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000763 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000764 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000765 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000766 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000767 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000768 }
769
770 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000771 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000772 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000773 FormatTok.Tok.setKind(Info.getTokenID());
774 }
775
776 if (FormatTok.Tok.is(tok::greatergreater)) {
777 FormatTok.Tok.setKind(tok::greater);
778 GreaterStashed = true;
779 }
780
781 return FormatTok;
782 }
783
784private:
785 FormatToken FormatTok;
786 bool GreaterStashed;
787 Lexer &Lex;
788 SourceManager &SourceMgr;
789 IdentifierTable IdentTable;
790
791 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000792 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000793 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
794 Tok.getLength());
795 }
796};
797
Daniel Jasperbac016b2012-12-03 18:12:45 +0000798class Formatter : public UnwrappedLineConsumer {
799public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000800 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
801 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000802 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000803 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000804 Whitespaces(SourceMgr), Ranges(Ranges) {
805 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000806
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000807 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000808
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000810 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000811 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000812 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000813 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +0000814 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
815 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
816 Annotator.annotate();
817 }
818 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
819 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000820 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000821 const AnnotatedLine &TheLine = *I;
822 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000823 unsigned Indent =
824 formatFirstToken(TheLine.First, TheLine.Level,
825 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000826 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +0000827 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000828 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +0000829 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000830 PreviousEndOfLineColumn = Formatter.format();
831 } else {
832 // If we did not reformat this unwrapped line, the column at the end of
833 // the last token is unchanged - thus, we can calculate the end of the
834 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000835 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +0000836 SourceMgr.getSpellingColumnNumber(
837 TheLine.Last->FormatTok.Tok.getLocation()) +
838 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000839 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000840 }
841 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000842 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000843 }
844
845private:
Manuel Klimek517e8942013-01-11 17:54:10 +0000846 /// \brief Tries to merge lines into one.
847 ///
848 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
849 /// if possible; note that \c I will be incremented when lines are merged.
850 ///
851 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000852 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +0000853 std::vector<AnnotatedLine>::iterator &I,
854 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +0000855 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
856
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000857 // We can never merge stuff if there are trailing line comments.
858 if (I->Last->Type == TT_LineComment)
859 return;
860
Manuel Klimek517e8942013-01-11 17:54:10 +0000861 // Check whether the UnwrappedLine can be put onto a single line. If
862 // so, this is bound to be the optimal solution (by definition) and we
863 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000864 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000865 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000866 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000867
Daniel Jasper9c8c40e2013-01-21 14:18:28 +0000868 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000869 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000870
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000871 if (I->Last->is(tok::l_brace)) {
872 tryMergeSimpleBlock(I, E, Limit);
873 } else if (I->First.is(tok::kw_if)) {
874 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000875 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
876 I->First.FormatTok.IsFirst)) {
877 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000878 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000879 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000880 }
881
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000882 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
883 std::vector<AnnotatedLine>::iterator E,
884 unsigned Limit) {
885 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +0000886 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
887 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000888 if (I + 2 != E && (I + 2)->InPPDirective &&
889 !(I + 2)->First.FormatTok.HasUnescapedNewline)
890 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000891 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000892 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000893 join(Line, *(++I));
894 }
895
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000896 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
897 std::vector<AnnotatedLine>::iterator E,
898 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000899 if (!Style.AllowShortIfStatementsOnASingleLine)
900 return;
Manuel Klimek4c128122013-01-18 14:46:43 +0000901 if ((I + 1)->InPPDirective != I->InPPDirective ||
902 ((I + 1)->InPPDirective &&
903 (I + 1)->First.FormatTok.HasUnescapedNewline))
904 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000905 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000906 if (Line.Last->isNot(tok::r_paren))
907 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000908 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000909 return;
910 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
911 return;
912 // Only inline simple if's (no nested if or else).
913 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
914 return;
915 join(Line, *(++I));
916 }
917
918 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000919 std::vector<AnnotatedLine>::iterator E,
920 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +0000921 // First, check that the current line allows merging. This is the case if
922 // we're not in a control flow statement and the last token is an opening
923 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000924 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +0000925 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +0000926 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
927 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
928 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
929 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +0000930 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +0000931 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
932 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000933 if (!AllowedTokens)
934 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000935
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000936 AnnotatedToken *Tok = &(I + 1)->First;
937 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
938 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
939 Tok->SpaceRequiredBefore = false;
940 join(Line, *(I + 1));
941 I += 1;
942 } else {
943 // Check that we still have three lines and they fit into the limit.
944 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
945 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000946 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000947
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000948 // Second, check that the next line does not contain any braces - if it
949 // does, readability declines when putting it into a single line.
950 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
951 return;
952 do {
953 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
954 return;
955 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
956 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +0000957
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000958 // Last, check that the third line contains a single closing brace.
959 Tok = &(I + 2)->First;
960 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
961 Tok->MustBreakBefore)
962 return;
963
964 join(Line, *(I + 1));
965 join(Line, *(I + 2));
966 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +0000967 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000968 }
969
970 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
971 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000972 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
973 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +0000974 }
975
Daniel Jasper995e8202013-01-14 13:08:07 +0000976 void join(AnnotatedLine &A, const AnnotatedLine &B) {
977 A.Last->Children.push_back(B.First);
978 while (!A.Last->Children.empty()) {
979 A.Last->Children[0].Parent = A.Last;
980 A.Last = &A.Last->Children[0];
981 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000982 }
983
Daniel Jasper995e8202013-01-14 13:08:07 +0000984 bool touchesRanges(const AnnotatedLine &TheLine) {
985 const FormatToken *First = &TheLine.First.FormatTok;
986 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +0000987 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000988 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000989 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000990 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
991 Ranges[i].getBegin()) &&
992 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
993 LineRange.getBegin()))
994 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000995 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000996 return false;
997 }
998
999 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001000 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001001 }
1002
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001003 /// \brief Add a new line and the required indent before the first Token
1004 /// of the \c UnwrappedLine if there was no structural parsing error.
1005 /// Returns the indent level of the \c UnwrappedLine.
1006 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1007 bool InPPDirective,
1008 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001009 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001010 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1011 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1012
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001013 unsigned Newlines =
1014 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001015 if (Newlines == 0 && !Tok.IsFirst)
1016 Newlines = 1;
1017 unsigned Indent = Level * 2;
1018
1019 bool IsAccessModifier = false;
1020 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1021 RootToken.is(tok::kw_private))
1022 IsAccessModifier = true;
1023 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1024 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1025 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1026 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1027 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1028 IsAccessModifier = true;
1029
1030 if (IsAccessModifier &&
1031 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1032 Indent += Style.AccessModifierOffset;
1033 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001034 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001035 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001036 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1037 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001038 }
1039 return Indent;
1040 }
1041
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001042 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001043 FormatStyle Style;
1044 Lexer &Lex;
1045 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001046 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001047 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001048 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001049 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001050};
1051
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001052tooling::Replacements
1053reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1054 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001055 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001056 OwningPtr<DiagnosticConsumer> DiagPrinter;
1057 if (DiagClient == 0) {
1058 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1059 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1060 DiagClient = DiagPrinter.get();
1061 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001062 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001063 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001064 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001065 Diagnostics.setSourceManager(&SourceMgr);
1066 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001067 return formatter.format();
1068}
1069
Daniel Jasper46ef8522013-01-10 13:08:12 +00001070LangOptions getFormattingLangOpts() {
1071 LangOptions LangOpts;
1072 LangOpts.CPlusPlus = 1;
1073 LangOpts.CPlusPlus11 = 1;
1074 LangOpts.Bool = 1;
1075 LangOpts.ObjC1 = 1;
1076 LangOpts.ObjC2 = 1;
1077 return LangOpts;
1078}
1079
Daniel Jaspercd162382013-01-07 13:26:07 +00001080} // namespace format
1081} // namespace clang