blob: 4aaae844fcadc3f8a6ca1e9c783f5b51aebb560e [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 Klimek32a2fd72013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperbac016b2012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
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 Jasper7e9bf8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jaspera03ab102013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
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;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000064 GoogleStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
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 Jaspera03ab102013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperbac016b2012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000077 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper15417ef2013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperce3d1a62013-02-08 08:22:00 +000088// Returns the length of everything up to the first possible line break after
89// the ), ], } or > matching \c Tok.
90static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
91 if (Tok.MatchingParen == NULL)
92 return 0;
93 AnnotatedToken *End = Tok.MatchingParen;
94 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
95 End = &End->Children[0];
96 }
97 return End->TotalLength - Tok.TotalLength + 1;
98}
99
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000100/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000101///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000102/// This includes special handling for certain constructs, e.g. the alignment of
103/// trailing line comments.
104class WhitespaceManager {
105public:
106 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
107
108 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
109 /// each \c AnnotatedToken.
110 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
111 unsigned Spaces, unsigned WhitespaceStartColumn,
112 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000113 // 2+ newlines mean an empty line separating logic scopes.
114 if (NewLines >= 2)
115 alignComments();
116
117 // Align line comments if they are trailing or if they continue other
118 // trailing comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000119 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000120 if (Style.ColumnLimit >=
121 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
122 Comments.push_back(StoredComment());
123 Comments.back().Tok = Tok.FormatTok;
124 Comments.back().Spaces = Spaces;
125 Comments.back().NewLines = NewLines;
Daniel Jasper474e4622013-02-06 22:04:05 +0000126 if (NewLines == 0)
127 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
128 else
129 Comments.back().MinColumn = Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000130 Comments.back().MaxColumn =
Daniel Jasper42f458d2013-02-13 19:25:54 +0000131 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000132 return;
133 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000134 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000135
136 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000137 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000138 alignComments();
Manuel Klimek8092a942013-02-20 10:15:13 +0000139 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000140 }
141
142 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
143 /// backslashes to escape newlines inside a preprocessor directive.
144 ///
145 /// This function and \c replaceWhitespace have the same behavior if
146 /// \c Newlines == 0.
147 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
148 unsigned Spaces, unsigned WhitespaceStartColumn,
149 const FormatStyle &Style) {
Manuel Klimek8092a942013-02-20 10:15:13 +0000150 storeReplacement(
151 Tok.FormatTok,
152 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
153 }
154
155 /// \brief Inserts a line break into the middle of a token.
156 ///
157 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
158 /// break and \p Postfix before the rest of the token starts in the next line.
159 ///
160 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
161 /// used to generate the correct line break.
162 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
163 StringRef Postfix, bool InPPDirective, unsigned Spaces,
164 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
165 std::string NewLineText;
166 if (!InPPDirective)
167 NewLineText = getNewLineText(1, Spaces);
168 else
169 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
170 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
171 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
172 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
173 Replaces.insert(
174 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
175 }
176
177 /// \brief Returns all the \c Replacements created during formatting.
178 const tooling::Replacements &generateReplacements() {
179 alignComments();
180 return Replaces;
181 }
182
183private:
184 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
185 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
186 }
187
188 std::string
189 getNewLineText(unsigned NewLines, unsigned Spaces,
190 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000191 std::string NewLineText;
192 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000193 unsigned Offset =
194 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000195 for (unsigned i = 0; i < NewLines; ++i) {
196 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
197 NewLineText += "\\\n";
198 Offset = 0;
199 }
200 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000201 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000202 }
203
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000204 /// \brief Structure to store a comment for later layout and alignment.
205 struct StoredComment {
206 FormatToken Tok;
207 unsigned MinColumn;
208 unsigned MaxColumn;
209 unsigned NewLines;
210 unsigned Spaces;
211 };
212 SmallVector<StoredComment, 16> Comments;
213 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
214
215 /// \brief Try to align all stashed comments.
216 void alignComments() {
217 unsigned MinColumn = 0;
218 unsigned MaxColumn = UINT_MAX;
219 comment_iterator Start = Comments.begin();
220 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
221 ++I) {
222 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
223 alignComments(Start, I, MinColumn);
224 MinColumn = I->MinColumn;
225 MaxColumn = I->MaxColumn;
226 Start = I;
227 } else {
228 MinColumn = std::max(MinColumn, I->MinColumn);
229 MaxColumn = std::min(MaxColumn, I->MaxColumn);
230 }
231 }
232 alignComments(Start, Comments.end(), MinColumn);
233 Comments.clear();
234 }
235
236 /// \brief Put all the comments between \p I and \p E into \p Column.
237 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
238 while (I != E) {
239 unsigned Spaces = I->Spaces + Column - I->MinColumn;
240 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper29f123b2013-02-08 15:28:42 +0000241 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000242 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000243 }
244 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000245
246 /// \brief Stores \p Text as the replacement for the whitespace in front of
247 /// \p Tok.
248 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000249 // Don't create a replacement, if it does not change anything.
250 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
251 Tok.WhiteSpaceLength) == Text)
252 return;
253
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000254 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
255 Tok.WhiteSpaceLength, Text));
256 }
257
258 SourceManager &SourceMgr;
259 tooling::Replacements Replaces;
260};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000261
Daniel Jasperbac016b2012-12-03 18:12:45 +0000262class UnwrappedLineFormatter {
263public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000264 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000265 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000266 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000267 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000268 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000269 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000270 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000271
Manuel Klimekd4397b92013-01-04 23:34:14 +0000272 /// \brief Formats an \c UnwrappedLine.
273 ///
274 /// \returns The column after the last token in the last line of the
275 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000276 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000277 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000278 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000279 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000280 State.NextToken = &RootToken;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000281 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
282 !Style.BinPackParameters,
283 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000284 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000285 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000286 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000287 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000288 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000289
Manuel Klimekca547db2013-01-16 14:55:28 +0000290 DEBUG({
291 DebugTokenState(*State.NextToken);
292 });
293
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000294 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000295 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000296
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000297 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000298 unsigned ColumnLimit = Style.ColumnLimit;
299 if (NextLine && NextLine->InPPDirective &&
300 !NextLine->First.FormatTok.HasUnescapedNewline)
301 ColumnLimit = getColumnLimit();
302 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000303 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000304 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000305 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000306 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000308
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000309 // If the ObjC method declaration does not fit on a line, we should format
310 // it with one arg per line.
311 if (Line.Type == LT_ObjCMethodDecl)
312 State.Stack.back().BreakBeforeParameter = true;
313
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000314 // Find best solution in solution space.
315 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000316 }
317
318private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000319 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
320 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000321 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
322 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000323 llvm::errs();
324 }
325
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000326 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000327 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
328 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000329 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
330 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000331 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper237d4c12013-02-23 21:01:55 +0000332 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000333
Daniel Jasperbac016b2012-12-03 18:12:45 +0000334 /// \brief The position to which a specific parenthesis level needs to be
335 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000336 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000337
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000338 /// \brief The position of the last space on each level.
339 ///
340 /// Used e.g. to break like:
341 /// functionCall(Parameter, otherCall(
342 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000343 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000344
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000345 /// \brief The position the first "<<" operator encountered on each level.
346 ///
347 /// Used to align "<<" operators. 0 if no such operator has been encountered
348 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000349 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000350
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000351 /// \brief Whether a newline needs to be inserted before the block's closing
352 /// brace.
353 ///
354 /// We only want to insert a newline before the closing brace if there also
355 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000356 bool BreakBeforeClosingBrace;
357
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000358 /// \brief The column of a \c ? in a conditional expression;
359 unsigned QuestionColumn;
360
Daniel Jasperf343cab2013-01-31 14:59:26 +0000361 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
362 /// lines, in this context.
363 bool AvoidBinPacking;
364
365 /// \brief Break after the next comma (or all the commas in this context if
366 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000367 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000368
369 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000370 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000371
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000372 /// \brief The position of the colon in an ObjC method declaration/call.
373 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000374
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000375 bool operator<(const ParenState &Other) const {
376 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000377 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000378 if (LastSpace != Other.LastSpace)
379 return LastSpace < Other.LastSpace;
380 if (FirstLessLess != Other.FirstLessLess)
381 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000382 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
383 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000384 if (QuestionColumn != Other.QuestionColumn)
385 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000386 if (AvoidBinPacking != Other.AvoidBinPacking)
387 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000388 if (BreakBeforeParameter != Other.BreakBeforeParameter)
389 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000390 if (HasMultiParameterLine != Other.HasMultiParameterLine)
391 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000392 if (ColonPos != Other.ColonPos)
393 return ColonPos < Other.ColonPos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000394 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000395 }
396 };
397
398 /// \brief The current state when indenting a unwrapped line.
399 ///
400 /// As the indenting tries different combinations this is copied by value.
401 struct LineState {
402 /// \brief The number of used columns in the current line.
403 unsigned Column;
404
405 /// \brief The token that needs to be next formatted.
406 const AnnotatedToken *NextToken;
407
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000408 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000409 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000410 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000411 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000412
413 /// \brief \c true if this line contains a continued for-loop section.
414 bool LineContainsContinuedForLoopSection;
415
Daniel Jasper29f123b2013-02-08 15:28:42 +0000416 /// \brief The level of nesting inside (), [], <> and {}.
417 unsigned ParenLevel;
418
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000419 /// \brief The \c ParenLevel at the start of this line.
420 unsigned StartOfLineLevel;
421
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000422 /// \brief The start column of the string literal, if we're in a string
423 /// literal sequence, 0 otherwise.
424 unsigned StartOfStringLiteral;
425
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000426 /// \brief A stack keeping track of properties applying to parenthesis
427 /// levels.
428 std::vector<ParenState> Stack;
429
430 /// \brief Comparison operator to be able to used \c LineState in \c map.
431 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000432 if (NextToken != Other.NextToken)
433 return NextToken < Other.NextToken;
434 if (Column != Other.Column)
435 return Column < Other.Column;
436 if (VariablePos != Other.VariablePos)
437 return VariablePos < Other.VariablePos;
438 if (LineContainsContinuedForLoopSection !=
439 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000440 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000441 if (ParenLevel != Other.ParenLevel)
442 return ParenLevel < Other.ParenLevel;
443 if (StartOfLineLevel != Other.StartOfLineLevel)
444 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000445 if (StartOfStringLiteral != Other.StartOfStringLiteral)
446 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000447 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000448 }
449 };
450
Daniel Jasper20409152012-12-04 14:54:30 +0000451 /// \brief Appends the next token to \p State and updates information
452 /// necessary for indentation.
453 ///
454 /// Puts the token on the current line if \p Newline is \c true and adds a
455 /// line break and necessary indentation otherwise.
456 ///
457 /// If \p DryRun is \c false, also creates and stores the required
458 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000459 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000460 const AnnotatedToken &Current = *State.NextToken;
461 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000462 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000463
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000464 if (Current.Type == TT_ImplicitStringLiteral) {
465 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
466 State.NextToken->FormatTok.TokenLength;
467 if (State.NextToken->Children.empty())
468 State.NextToken = NULL;
469 else
470 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000471 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000472 }
473
Daniel Jasperbac016b2012-12-03 18:12:45 +0000474 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000475 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000476 if (Current.is(tok::r_brace)) {
477 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000478 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000479 State.StartOfStringLiteral != 0) {
480 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000481 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000482 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000483 State.Stack.back().FirstLessLess != 0) {
484 State.Column = State.Stack.back().FirstLessLess;
485 } else if (State.ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000486 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000487 Current.is(tok::period) || Current.is(tok::arrow) ||
488 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000489 // Indent and extra 4 spaces after if we know the current expression is
490 // continued. Don't do that on the top level, as we already indent 4
491 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000492 State.Column = std::max(State.Stack.back().LastSpace,
493 State.Stack.back().Indent) + 4;
494 } else if (Current.Type == TT_ConditionalExpr) {
495 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000496 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000497 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
498 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000499 State.Column = State.VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000500 } else if (Previous.ClosesTemplateDeclaration ||
501 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000502 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000503 } else if (Current.Type == TT_ObjCSelectorName) {
504 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
505 State.Column =
506 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
507 } else {
508 State.Column = State.Stack.back().Indent;
509 State.Stack.back().ColonPos =
510 State.Column + Current.FormatTok.TokenLength;
511 }
Daniel Jasper3c08a812013-02-24 18:54:32 +0000512 } else if (Previous.Type == TT_ObjCMethodExpr ||
513 Current.Type == TT_StartOfName) {
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000514 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000515 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000516 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000517 }
518
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000519 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000520 State.Stack.back().BreakBeforeParameter = true;
521 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
522 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000523 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000524
Manuel Klimek060143e2013-01-02 18:33:23 +0000525 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000526 unsigned NewLines = 1;
527 if (Current.Type == TT_LineComment)
528 NewLines =
529 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
530 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000531 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000532 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000533 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000534 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000535 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000536 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000537 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000538
Daniel Jasper29f123b2013-02-08 15:28:42 +0000539 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000540 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000541 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000542 State.Stack.back().Indent += 2;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000543
544 // Any break on this level means that the parent level has been broken
545 // and we need to avoid bin packing there.
546 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
547 State.Stack[i].BreakBeforeParameter = true;
548 }
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000549 if (Current.is(tok::period) || Current.is(tok::arrow))
550 State.Stack.back().BreakBeforeParameter = true;
551
Daniel Jasper237d4c12013-02-23 21:01:55 +0000552 // If we break after {, we should also break before the corresponding }.
553 if (Previous.is(tok::l_brace))
554 State.Stack.back().BreakBeforeClosingBrace = true;
555
556 if (State.Stack.back().AvoidBinPacking) {
557 // If we are breaking after '(', '{', '<', this is not bin packing
558 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000559 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000560 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
561 Line.MustBeDeclaration))
562 State.Stack.back().BreakBeforeParameter = true;
563 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000564 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000565 // FIXME: Put VariablePos into ParenState and remove second part of if().
566 if (Current.is(tok::equal) &&
567 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000568 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000569
Daniel Jasper729a7432013-02-11 12:36:37 +0000570 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000571
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000573 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000574
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000575 if (Current.Type == TT_ObjCSelectorName &&
576 State.Stack.back().ColonPos == 0) {
577 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
578 State.Column + Spaces + Current.FormatTok.TokenLength)
579 State.Stack.back().ColonPos =
580 State.Stack.back().Indent + Current.LongestObjCSelectorName;
581 else
582 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000583 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000584 }
585
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000586 if (Current.Type != TT_LineComment &&
587 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
588 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000589 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000590 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000591 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000592
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000593 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000594 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
595 // Treat the condition inside an if as if it was a second function
596 // parameter, i.e. let nested calls have an indent of 4.
597 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000598 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000599 // Top-level spaces are exempt as that mostly leads to better results.
600 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000601 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000602 Previous.Type == TT_ConditionalExpr ||
603 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000604 getPrecedence(Previous) != prec::Assignment)
605 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000606 else if (Previous.Type == TT_InheritanceColon)
607 State.Stack.back().Indent = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000608 else if (Previous.ParameterCount > 1 &&
609 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000610 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000611 Previous.Type == TT_TemplateOpener))
612 // If this function has multiple parameters, indent nested calls from
613 // the start of the first parameter.
614 State.Stack.back().LastSpace = State.Column;
Daniel Jasper82282dc2013-02-18 13:52:06 +0000615 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
616 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
617 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000619
Manuel Klimek8092a942013-02-20 10:15:13 +0000620 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000621 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000622
Daniel Jasper20409152012-12-04 14:54:30 +0000623 /// \brief Mark the next token as consumed in \p State and modify its stacks
624 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000625 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000626 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000627 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000628
Daniel Jasper6cabab42013-02-14 08:42:54 +0000629 if (Current.Type == TT_InheritanceColon)
630 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000631 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
632 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000633 if (Current.is(tok::question))
634 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000635 if (Current.Type == TT_CtorInitializerColon) {
636 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
637 State.Stack.back().AvoidBinPacking = true;
638 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000639 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000640
Daniel Jasper29f123b2013-02-08 15:28:42 +0000641 // Insert scopes created by fake parenthesis.
642 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
643 ParenState NewParenState = State.Stack.back();
644 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jasper237d4c12013-02-23 21:01:55 +0000645 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000646 State.Stack.push_back(NewParenState);
647 }
648
Daniel Jaspercf225b62012-12-24 13:43:52 +0000649 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000650 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000651 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
652 Current.is(tok::l_brace) ||
653 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000654 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000655 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000656 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000657 NewIndent = 2 + State.Stack.back().LastSpace;
658 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000659 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000660 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper3a39ac72013-02-28 09:39:12 +0000661 AvoidBinPacking =
662 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000663 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000664 State.Stack.push_back(
665 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
666 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000667 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000668 }
669
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000670 // If this '[' opens an ObjC call, determine whether all parameters fit into
671 // one line and put one per line if they don't.
672 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
673 Current.MatchingParen != NULL) {
674 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
675 State.Stack.back().BreakBeforeParameter = true;
676 }
677
Daniel Jaspercf225b62012-12-24 13:43:52 +0000678 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000679 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000680 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
681 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
682 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000683 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000684 --State.ParenLevel;
685 }
686
687 // Remove scopes created by fake parenthesis.
688 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
689 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000690 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000691
Manuel Klimeke9a62262013-02-20 15:32:58 +0000692 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000693 State.StartOfStringLiteral = State.Column;
694 } else if (Current.isNot(tok::comment)) {
695 State.StartOfStringLiteral = 0;
696 }
697
Manuel Klimek8092a942013-02-20 10:15:13 +0000698 State.Column += Current.FormatTok.TokenLength;
699
Daniel Jasper26f7e782013-01-08 14:56:18 +0000700 if (State.NextToken->Children.empty())
701 State.NextToken = NULL;
702 else
703 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000704
Manuel Klimek8092a942013-02-20 10:15:13 +0000705 return breakProtrudingToken(Current, State, DryRun);
706 }
707
708 /// \brief If the current token sticks out over the end of the line, break
709 /// it if possible.
710 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
711 bool DryRun) {
712 if (Current.isNot(tok::string_literal))
713 return 0;
714
715 unsigned Penalty = 0;
716 unsigned TailOffset = 0;
717 unsigned TailLength = Current.FormatTok.TokenLength;
718 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
719 unsigned OffsetFromStart = 0;
720 while (StartColumn + TailLength > getColumnLimit()) {
721 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
722 TailOffset, TailLength);
723 StringRef::size_type SplitPoint =
724 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
725 if (SplitPoint == StringRef::npos)
726 break;
727 assert(SplitPoint != 0);
728 // +2, because 'Text' starts after the opening quotes, and does not
729 // include the closing quote we need to insert.
730 unsigned WhitespaceStartColumn =
731 StartColumn + OffsetFromStart + SplitPoint + 2;
732 State.Stack.back().LastSpace = StartColumn;
733 if (!DryRun) {
734 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
735 Line.InPPDirective, StartColumn,
736 WhitespaceStartColumn, Style);
737 }
738 TailOffset += SplitPoint + 1;
739 TailLength -= SplitPoint + 1;
740 OffsetFromStart = 1;
Daniel Jasper0fb382b2013-02-26 12:52:34 +0000741 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000742 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
743 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000744 }
745 State.Column = StartColumn + TailLength;
746 return Penalty;
747 }
748
749 StringRef::size_type
750 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
751 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
752 return Text.rfind(' ', Offset);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000753 }
754
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000755 unsigned getColumnLimit() {
Daniel Jaspera4d46212013-02-28 11:05:57 +0000756 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000757 }
758
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000759 /// \brief An edge in the solution space from \c Previous->State to \c State,
760 /// inserting a newline dependent on the \c NewLine.
761 struct StateNode {
762 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000763 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000764 LineState State;
765 bool NewLine;
766 StateNode *Previous;
767 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000768
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000769 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
770 ///
771 /// In case of equal penalties, we want to prefer states that were inserted
772 /// first. During state generation we make sure that we insert states first
773 /// that break the line as late as possible.
774 typedef std::pair<unsigned, unsigned> OrderedPenalty;
775
776 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
777 /// \c State has the given \c OrderedPenalty.
778 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
779
780 /// \brief The BFS queue type.
781 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
782 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000783
784 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000785 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000786 /// This implements a variant of Dijkstra's algorithm on the graph that spans
787 /// the solution space (\c LineStates are the nodes). The algorithm tries to
788 /// find the shortest path (the one with lowest penalty) from \p InitialState
789 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000790 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000791 std::set<LineState> Seen;
792
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000793 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000794 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000795 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
796 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
797 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000798
799 // While not empty, take first element and follow edges.
800 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000801 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000802 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000803 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000804 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000805 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000806 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000807 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000808
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000809 if (!Seen.insert(Node->State).second)
810 // State already examined with lower penalty.
811 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000812
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000813 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
814 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000815 }
816
817 if (Queue.empty())
818 // We were unable to find a solution, do nothing.
819 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 return 0;
821
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000822 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000823 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000824 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000825
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000826 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000827 return Queue.top().second->State.Column;
828 }
829
830 void reconstructPath(LineState &State, StateNode *Current) {
831 // FIXME: This recursive implementation limits the possible number
832 // of tokens per line if compiled into a binary with small stack space.
833 // To become more independent of stack frame limitations we would need
834 // to also change the TokenAnnotator.
835 if (Current->Previous == NULL)
836 return;
837 reconstructPath(State, Current->Previous);
838 DEBUG({
839 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000840 llvm::errs()
841 << "Penalty for splitting before "
842 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
843 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000844 }
845 });
846 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000847 }
848
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000849 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000850 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000851 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000852 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000853 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
854 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000855 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000856 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000857 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000858 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000859 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000860 Penalty += PreviousNode->State.NextToken->SplitPenalty;
861
862 StateNode *Node = new (Allocator.Allocate())
863 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000864 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000865 if (Node->State.Column > getColumnLimit()) {
866 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000867 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000868 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000869
870 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
871 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000872 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000873
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000874 /// \brief Returns \c true, if a line break after \p State is allowed.
875 bool canBreak(const LineState &State) {
876 if (!State.NextToken->CanBreakBefore &&
877 !(State.NextToken->is(tok::r_brace) &&
878 State.Stack.back().BreakBeforeClosingBrace))
879 return false;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000880 // This prevents breaks like:
881 // ...
882 // SomeParameter, OtherParameter).DoSomething(
883 // ...
884 // As they hide "DoSomething" and generally bad for readability.
885 if (State.NextToken->Parent->is(tok::l_paren) &&
886 State.ParenLevel <= State.StartOfLineLevel)
887 return false;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000888 // Trying to insert a parameter on a new line if there are already more than
889 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000890 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000891 State.Stack.back().AvoidBinPacking)
892 return false;
893 return true;
894 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000895
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000896 /// \brief Returns \c true, if a line break after \p State is mandatory.
897 bool mustBreak(const LineState &State) {
898 if (State.NextToken->MustBreakBefore)
899 return true;
900 if (State.NextToken->is(tok::r_brace) &&
901 State.Stack.back().BreakBeforeClosingBrace)
902 return true;
903 if (State.NextToken->Parent->is(tok::semi) &&
904 State.LineContainsContinuedForLoopSection)
905 return true;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000906 if ((State.NextToken->Parent->is(tok::comma) ||
907 State.NextToken->Parent->is(tok::semi) ||
908 State.NextToken->is(tok::question) ||
909 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000910 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc5cfa492013-02-14 09:19:04 +0000911 !isTrailingComment(*State.NextToken) &&
Daniel Jasper7d812812013-02-21 15:00:29 +0000912 State.NextToken->isNot(tok::r_paren) &&
913 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000914 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000915 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
916 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000917 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000918 State.NextToken->LongestObjCSelectorName == 0 &&
919 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000920 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000921 if ((State.NextToken->Type == TT_CtorInitializerColon ||
922 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000923 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000924 return true;
925 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000926 }
927
Daniel Jasperbac016b2012-12-03 18:12:45 +0000928 FormatStyle Style;
929 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000930 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000931 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000932 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000933 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000934
935 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
936 QueueType Queue;
937 // Increasing count of \c StateNode items we have created. This is used
938 // to create a deterministic order independent of the container.
939 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000940};
941
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000942class LexerBasedFormatTokenSource : public FormatTokenSource {
943public:
944 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000945 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000946 IdentTable(Lex.getLangOpts()) {
947 Lex.SetKeepWhitespaceMode(true);
948 }
949
950 virtual FormatToken getNextToken() {
951 if (GreaterStashed) {
952 FormatTok.NewlinesBefore = 0;
953 FormatTok.WhiteSpaceStart =
954 FormatTok.Tok.getLocation().getLocWithOffset(1);
955 FormatTok.WhiteSpaceLength = 0;
956 GreaterStashed = false;
957 return FormatTok;
958 }
959
960 FormatTok = FormatToken();
961 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000962 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000963 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000964 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
965 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000966
967 // Consume and record whitespace until we find a significant token.
968 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000969 unsigned Newlines = Text.count('\n');
970 unsigned EscapedNewlines = Text.count("\\\n");
971 FormatTok.NewlinesBefore += Newlines;
972 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000973 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
974
975 if (FormatTok.Tok.is(tok::eof))
976 return FormatTok;
977 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000978 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000979 }
Manuel Klimek95419382013-01-07 07:56:50 +0000980
981 // Now FormatTok is the next non-whitespace token.
982 FormatTok.TokenLength = Text.size();
983
Manuel Klimekd4397b92013-01-04 23:34:14 +0000984 // In case the token starts with escaped newlines, we want to
985 // take them into account as whitespace - this pattern is quite frequent
986 // in macro definitions.
987 // FIXME: What do we want to do with other escaped spaces, and escaped
988 // spaces or newlines in the middle of tokens?
989 // FIXME: Add a more explicit test.
990 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000991 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000992 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000993 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000994 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000995 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000996 }
997
998 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000999 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001000 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001001 FormatTok.Tok.setKind(Info.getTokenID());
1002 }
1003
1004 if (FormatTok.Tok.is(tok::greatergreater)) {
1005 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001006 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001007 GreaterStashed = true;
1008 }
1009
1010 return FormatTok;
1011 }
1012
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001013 IdentifierTable &getIdentTable() { return IdentTable; }
1014
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001015private:
1016 FormatToken FormatTok;
1017 bool GreaterStashed;
1018 Lexer &Lex;
1019 SourceManager &SourceMgr;
1020 IdentifierTable IdentTable;
1021
1022 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001023 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001024 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1025 Tok.getLength());
1026 }
1027};
1028
Daniel Jasperbac016b2012-12-03 18:12:45 +00001029class Formatter : public UnwrappedLineConsumer {
1030public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001031 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1032 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001033 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001034 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperf11a7052013-02-21 21:33:55 +00001035 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001036
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001037 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001038
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001039 void deriveLocalStyle() {
1040 unsigned CountBoundToVariable = 0;
1041 unsigned CountBoundToType = 0;
1042 bool HasCpp03IncompatibleFormat = false;
1043 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1044 if (AnnotatedLines[i].First.Children.empty())
1045 continue;
1046 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1047 while (!Tok->Children.empty()) {
1048 if (Tok->Type == TT_PointerOrReference) {
1049 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1050 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1051 if (SpacesBefore && !SpacesAfter)
1052 ++CountBoundToVariable;
1053 else if (!SpacesBefore && SpacesAfter)
1054 ++CountBoundToType;
1055 }
1056
Daniel Jasper29f123b2013-02-08 15:28:42 +00001057 if (Tok->Type == TT_TemplateCloser &&
1058 Tok->Parent->Type == TT_TemplateCloser &&
1059 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001060 HasCpp03IncompatibleFormat = true;
1061 Tok = &Tok->Children[0];
1062 }
1063 }
1064 if (Style.DerivePointerBinding) {
1065 if (CountBoundToType > CountBoundToVariable)
1066 Style.PointerBindsToType = true;
1067 else if (CountBoundToType < CountBoundToVariable)
1068 Style.PointerBindsToType = false;
1069 }
1070 if (Style.Standard == FormatStyle::LS_Auto) {
1071 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1072 : FormatStyle::LS_Cpp03;
1073 }
1074 }
1075
Daniel Jasperbac016b2012-12-03 18:12:45 +00001076 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001077 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001078 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001079 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001080 unsigned PreviousEndOfLineColumn = 0;
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001081 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1082 Tokens.getIdentTable().get("in"));
Daniel Jasper995e8202013-01-14 13:08:07 +00001083 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001084 Annotator.annotate(AnnotatedLines[i]);
1085 }
1086 deriveLocalStyle();
1087 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1088 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +00001089 }
Manuel Klimek547d5db2013-02-08 17:38:27 +00001090 std::vector<int> IndentForLevel;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001091 bool PreviousLineWasTouched = false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001092 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1093 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001094 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001095 const AnnotatedLine &TheLine = *I;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001096 int Offset = getIndentOffset(TheLine.First);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001097 while (IndentForLevel.size() <= TheLine.Level)
1098 IndentForLevel.push_back(-1);
1099 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper29333162013-02-18 13:08:03 +00001100 bool WasMoved =
1101 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1102 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001103 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001104 unsigned Indent = LevelIndent;
1105 if (static_cast<int>(Indent) + Offset >= 0)
1106 Indent += Offset;
1107 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1108 StructuralError) {
1109 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1110 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1111 } else {
1112 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1113 PreviousEndOfLineColumn);
1114 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001115 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001116 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001117 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001118 StructuralError);
Daniel Jaspera4d46212013-02-28 11:05:57 +00001119 PreviousEndOfLineColumn =
1120 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001121 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001122 PreviousLineWasTouched = true;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001123 } else {
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001124 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1125 TheLine.First.FormatTok.IsFirst) {
1126 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1127 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1128 unsigned LevelIndent = Indent;
1129 if (static_cast<int>(LevelIndent) - Offset >= 0)
1130 LevelIndent -= Offset;
1131 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001132
1133 // Remove trailing whitespace of the previous line if it was touched.
1134 if (PreviousLineWasTouched)
1135 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1136 PreviousEndOfLineColumn);
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001137 }
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001138 // If we did not reformat this unwrapped line, the column at the end of
1139 // the last token is unchanged - thus, we can calculate the end of the
1140 // last token.
1141 PreviousEndOfLineColumn =
1142 SourceMgr.getSpellingColumnNumber(
1143 TheLine.Last->FormatTok.Tok.getLocation()) +
1144 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1145 SourceMgr, Lex.getLangOpts()) - 1;
1146 PreviousLineWasTouched = false;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001147 }
1148 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001149 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150 }
1151
1152private:
Manuel Klimek547d5db2013-02-08 17:38:27 +00001153 /// \brief Get the indent of \p Level from \p IndentForLevel.
1154 ///
1155 /// \p IndentForLevel must contain the indent for the level \c l
1156 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1157 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001158 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001159 if (IndentForLevel[Level] != -1)
1160 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001161 if (Level == 0)
1162 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001163 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001164 }
1165
1166 /// \brief Get the offset of the line relatively to the level.
1167 ///
1168 /// For example, 'public:' labels in classes are offset by 1 or 2
1169 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001170 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001171 bool IsAccessModifier = false;
1172 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1173 RootToken.is(tok::kw_private))
1174 IsAccessModifier = true;
1175 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1176 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1177 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1178 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1179 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1180 IsAccessModifier = true;
1181
1182 if (IsAccessModifier)
1183 return Style.AccessModifierOffset;
1184 return 0;
1185 }
1186
Manuel Klimek517e8942013-01-11 17:54:10 +00001187 /// \brief Tries to merge lines into one.
1188 ///
1189 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1190 /// if possible; note that \c I will be incremented when lines are merged.
1191 ///
1192 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001193 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001194 std::vector<AnnotatedLine>::iterator &I,
1195 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001196 // We can never merge stuff if there are trailing line comments.
1197 if (I->Last->Type == TT_LineComment)
1198 return;
1199
Daniel Jaspera4d46212013-02-28 11:05:57 +00001200 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001201 // If we already exceed the column limit, we set 'Limit' to 0. The different
1202 // tryMerge..() functions can then decide whether to still do merging.
1203 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001204
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001205 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001206 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001207
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001208 if (I->Last->is(tok::l_brace)) {
1209 tryMergeSimpleBlock(I, E, Limit);
1210 } else if (I->First.is(tok::kw_if)) {
1211 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001212 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1213 I->First.FormatTok.IsFirst)) {
1214 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001215 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001216 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001217 }
1218
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001219 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1220 std::vector<AnnotatedLine>::iterator E,
1221 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001222 if (Limit == 0)
1223 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001224 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001225 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1226 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001227 if (I + 2 != E && (I + 2)->InPPDirective &&
1228 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1229 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001230 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001231 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001232 join(Line, *(++I));
1233 }
1234
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001235 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1236 std::vector<AnnotatedLine>::iterator E,
1237 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001238 if (Limit == 0)
1239 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001240 if (!Style.AllowShortIfStatementsOnASingleLine)
1241 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001242 if ((I + 1)->InPPDirective != I->InPPDirective ||
1243 ((I + 1)->InPPDirective &&
1244 (I + 1)->First.FormatTok.HasUnescapedNewline))
1245 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001246 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001247 if (Line.Last->isNot(tok::r_paren))
1248 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001249 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001250 return;
1251 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1252 return;
1253 // Only inline simple if's (no nested if or else).
1254 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1255 return;
1256 join(Line, *(++I));
1257 }
1258
1259 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001260 std::vector<AnnotatedLine>::iterator E,
1261 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001262 // First, check that the current line allows merging. This is the case if
1263 // we're not in a control flow statement and the last token is an opening
1264 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001265 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001266 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001267 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1268 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1269 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1270 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001271 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001272 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1273 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001274 if (!AllowedTokens)
1275 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001276
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001277 AnnotatedToken *Tok = &(I + 1)->First;
1278 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001279 !Tok->MustBreakBefore) {
1280 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001281 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001282 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001283 join(Line, *(I + 1));
1284 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001285 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001286 // Check that we still have three lines and they fit into the limit.
1287 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1288 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001289 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001290
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001291 // Second, check that the next line does not contain any braces - if it
1292 // does, readability declines when putting it into a single line.
1293 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1294 return;
1295 do {
1296 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1297 return;
1298 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1299 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001300
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001301 // Last, check that the third line contains a single closing brace.
1302 Tok = &(I + 2)->First;
1303 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1304 Tok->MustBreakBefore)
1305 return;
1306
1307 join(Line, *(I + 1));
1308 join(Line, *(I + 2));
1309 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001310 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001311 }
1312
1313 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1314 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001315 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1316 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001317 }
1318
Daniel Jasper995e8202013-01-14 13:08:07 +00001319 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001320 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001321 A.Last->Children.push_back(B.First);
1322 while (!A.Last->Children.empty()) {
1323 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001324 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001325 A.Last = &A.Last->Children[0];
1326 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001327 }
1328
Daniel Jasper995e8202013-01-14 13:08:07 +00001329 bool touchesRanges(const AnnotatedLine &TheLine) {
1330 const FormatToken *First = &TheLine.First.FormatTok;
1331 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001332 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001333 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001334 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001335 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1336 Ranges[i].getBegin()) &&
1337 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1338 LineRange.getBegin()))
1339 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001340 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001341 return false;
1342 }
1343
1344 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001345 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001346 }
1347
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001348 /// \brief Add a new line and the required indent before the first Token
1349 /// of the \c UnwrappedLine if there was no structural parsing error.
1350 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek547d5db2013-02-08 17:38:27 +00001351 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1352 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001353 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001354
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001355 unsigned Newlines =
1356 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001357 if (Newlines == 0 && !Tok.IsFirst)
1358 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001359
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001360 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001361 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001362 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001363 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1364 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001365 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001366 }
1367
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001368 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001369 FormatStyle Style;
1370 Lexer &Lex;
1371 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001372 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001373 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001374 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001375 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001376};
1377
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001378tooling::Replacements
1379reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1380 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001381 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001382 OwningPtr<DiagnosticConsumer> DiagPrinter;
1383 if (DiagClient == 0) {
1384 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1385 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1386 DiagClient = DiagPrinter.get();
1387 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001388 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001389 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001390 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001391 Diagnostics.setSourceManager(&SourceMgr);
1392 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001393 return formatter.format();
1394}
1395
Daniel Jasper46ef8522013-01-10 13:08:12 +00001396LangOptions getFormattingLangOpts() {
1397 LangOptions LangOpts;
1398 LangOpts.CPlusPlus = 1;
1399 LangOpts.CPlusPlus11 = 1;
1400 LangOpts.Bool = 1;
1401 LangOpts.ObjC1 = 1;
1402 LangOpts.ObjC2 = 1;
1403 return LangOpts;
1404}
1405
Daniel Jaspercd162382013-01-07 13:26:07 +00001406} // namespace format
1407} // namespace clang