blob: aa715e692d17497a6b9f47bd9a0ce1f8f4d673d5 [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 Jasper812c0452013-03-01 16:45:59 +0000119 if (isTrailingComment(Tok)) {
120 // Remove the comment's trailing whitespace.
121 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
122 Replaces.insert(tooling::Replacement(
123 SourceMgr, Tok.FormatTok.Tok.getLocation().getLocWithOffset(
124 Tok.FormatTok.TokenLength),
125 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
126
127 // Align comment with other comments.
128 if (Tok.Parent != NULL || !Comments.empty()) {
129 if (Style.ColumnLimit >=
130 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
Alexander Kornienkof7536152013-03-14 16:10:54 +0000131 StoredComment Comment;
132 Comment.Tok = Tok.FormatTok;
133 Comment.Spaces = Spaces;
134 Comment.NewLines = NewLines;
135 Comment.MinColumn =
136 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
137 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
138 Comments.push_back(Comment);
Daniel Jasper812c0452013-03-01 16:45:59 +0000139 return;
140 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000141 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000142 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000143
144 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000145 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000146 alignComments();
Alexander Kornienkof7536152013-03-14 16:10:54 +0000147
148 if (Tok.Type == TT_BlockComment)
149 indentBlockComment(Tok.FormatTok, Spaces);
150
Manuel Klimek8092a942013-02-20 10:15:13 +0000151 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000152 }
153
154 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
155 /// backslashes to escape newlines inside a preprocessor directive.
156 ///
157 /// This function and \c replaceWhitespace have the same behavior if
158 /// \c Newlines == 0.
159 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
160 unsigned Spaces, unsigned WhitespaceStartColumn,
161 const FormatStyle &Style) {
Manuel Klimek8092a942013-02-20 10:15:13 +0000162 storeReplacement(
163 Tok.FormatTok,
164 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
165 }
166
167 /// \brief Inserts a line break into the middle of a token.
168 ///
169 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
170 /// break and \p Postfix before the rest of the token starts in the next line.
171 ///
172 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
173 /// used to generate the correct line break.
174 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
175 StringRef Postfix, bool InPPDirective, unsigned Spaces,
176 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
177 std::string NewLineText;
178 if (!InPPDirective)
179 NewLineText = getNewLineText(1, Spaces);
180 else
181 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
182 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
183 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
184 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
185 Replaces.insert(
186 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
187 }
188
189 /// \brief Returns all the \c Replacements created during formatting.
190 const tooling::Replacements &generateReplacements() {
191 alignComments();
192 return Replaces;
193 }
194
195private:
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000196 void indentBlockComment(const FormatToken &Tok, int Indent) {
Alexander Kornienkof7536152013-03-14 16:10:54 +0000197 SourceLocation TokenLoc = Tok.Tok.getLocation();
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000198 int IndentDelta = Indent - SourceMgr.getSpellingColumnNumber(TokenLoc) + 1;
Alexander Kornienkof7536152013-03-14 16:10:54 +0000199 const char *Start = SourceMgr.getCharacterData(TokenLoc);
200 const char *Current = Start;
201 const char *TokEnd = Current + Tok.TokenLength;
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000202 llvm::SmallVector<SourceLocation, 16> LineStarts;
Alexander Kornienkof7536152013-03-14 16:10:54 +0000203 while (Current < TokEnd) {
204 if (*Current == '\n') {
205 ++Current;
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000206 LineStarts.push_back(TokenLoc.getLocWithOffset(Current - Start));
207 // If we need to outdent the line, check that it's indented enough.
208 for (int i = 0; i < -IndentDelta; ++i, ++Current)
209 if (Current >= TokEnd || *Current != ' ')
210 return;
Alexander Kornienkof7536152013-03-14 16:10:54 +0000211 } else {
212 ++Current;
213 }
214 }
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000215
216 for (size_t i = 0; i < LineStarts.size(); ++i) {
217 if (IndentDelta > 0)
218 Replaces.insert(tooling::Replacement(SourceMgr, LineStarts[i], 0,
219 std::string(IndentDelta, ' ')));
220 else if (IndentDelta < 0)
221 Replaces.insert(
222 tooling::Replacement(SourceMgr, LineStarts[i], -IndentDelta, ""));
223 }
Alexander Kornienkof7536152013-03-14 16:10:54 +0000224 }
225
Manuel Klimek8092a942013-02-20 10:15:13 +0000226 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
227 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
228 }
229
230 std::string
231 getNewLineText(unsigned NewLines, unsigned Spaces,
232 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000233 std::string NewLineText;
234 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000235 unsigned Offset =
236 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000237 for (unsigned i = 0; i < NewLines; ++i) {
238 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
239 NewLineText += "\\\n";
240 Offset = 0;
241 }
242 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000243 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000244 }
245
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000246 /// \brief Structure to store a comment for later layout and alignment.
247 struct StoredComment {
248 FormatToken Tok;
249 unsigned MinColumn;
250 unsigned MaxColumn;
251 unsigned NewLines;
252 unsigned Spaces;
253 };
254 SmallVector<StoredComment, 16> Comments;
255 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
256
257 /// \brief Try to align all stashed comments.
258 void alignComments() {
259 unsigned MinColumn = 0;
260 unsigned MaxColumn = UINT_MAX;
261 comment_iterator Start = Comments.begin();
Alexander Kornienkof7536152013-03-14 16:10:54 +0000262 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000263 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
264 alignComments(Start, I, MinColumn);
265 MinColumn = I->MinColumn;
266 MaxColumn = I->MaxColumn;
267 Start = I;
268 } else {
269 MinColumn = std::max(MinColumn, I->MinColumn);
270 MaxColumn = std::min(MaxColumn, I->MaxColumn);
271 }
272 }
273 alignComments(Start, Comments.end(), MinColumn);
274 Comments.clear();
275 }
276
277 /// \brief Put all the comments between \p I and \p E into \p Column.
278 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
279 while (I != E) {
280 unsigned Spaces = I->Spaces + Column - I->MinColumn;
281 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper29f123b2013-02-08 15:28:42 +0000282 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000283 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000284 }
285 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000286
287 /// \brief Stores \p Text as the replacement for the whitespace in front of
288 /// \p Tok.
289 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000290 // Don't create a replacement, if it does not change anything.
291 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
292 Tok.WhiteSpaceLength) == Text)
293 return;
294
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000295 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
296 Tok.WhiteSpaceLength, Text));
297 }
298
299 SourceManager &SourceMgr;
300 tooling::Replacements Replaces;
301};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000302
Daniel Jasperbac016b2012-12-03 18:12:45 +0000303class UnwrappedLineFormatter {
304public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000305 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000306 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000307 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000308 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000309 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000310 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000311 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000312
Manuel Klimekd4397b92013-01-04 23:34:14 +0000313 /// \brief Formats an \c UnwrappedLine.
314 ///
315 /// \returns The column after the last token in the last line of the
316 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000317 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000318 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000319 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000320 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000321 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000322 State.Stack.push_back(
323 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
324 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000325 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000326 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000327 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000328 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000329 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000330
Manuel Klimekca547db2013-01-16 14:55:28 +0000331 DEBUG({
332 DebugTokenState(*State.NextToken);
333 });
334
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000335 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000336 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000337
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000338 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000339 unsigned ColumnLimit = Style.ColumnLimit;
340 if (NextLine && NextLine->InPPDirective &&
341 !NextLine->First.FormatTok.HasUnescapedNewline)
342 ColumnLimit = getColumnLimit();
343 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000344 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000345 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000346 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000347 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000348 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000349
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000350 // If the ObjC method declaration does not fit on a line, we should format
351 // it with one arg per line.
352 if (Line.Type == LT_ObjCMethodDecl)
353 State.Stack.back().BreakBeforeParameter = true;
354
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000355 // Find best solution in solution space.
356 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000357 }
358
359private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000360 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
361 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000362 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
363 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000364 llvm::errs();
365 }
366
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000367 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000368 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
369 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000370 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
371 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000372 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper24849712013-03-01 16:48:32 +0000373 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
374 StartOfFunctionCall(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000375
Daniel Jasperbac016b2012-12-03 18:12:45 +0000376 /// \brief The position to which a specific parenthesis level needs to be
377 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000378 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000379
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000380 /// \brief The position of the last space on each level.
381 ///
382 /// Used e.g. to break like:
383 /// functionCall(Parameter, otherCall(
384 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000385 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000387 /// \brief The position the first "<<" operator encountered on each level.
388 ///
389 /// Used to align "<<" operators. 0 if no such operator has been encountered
390 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000391 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000392
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000393 /// \brief Whether a newline needs to be inserted before the block's closing
394 /// brace.
395 ///
396 /// We only want to insert a newline before the closing brace if there also
397 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000398 bool BreakBeforeClosingBrace;
399
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000400 /// \brief The column of a \c ? in a conditional expression;
401 unsigned QuestionColumn;
402
Daniel Jasperf343cab2013-01-31 14:59:26 +0000403 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
404 /// lines, in this context.
405 bool AvoidBinPacking;
406
407 /// \brief Break after the next comma (or all the commas in this context if
408 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000409 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000410
411 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000412 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000413
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000414 /// \brief The position of the colon in an ObjC method declaration/call.
415 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000416
Daniel Jasper24849712013-03-01 16:48:32 +0000417 /// \brief The start of the most recent function in a builder-type call.
418 unsigned StartOfFunctionCall;
419
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000420 bool operator<(const ParenState &Other) const {
421 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000422 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000423 if (LastSpace != Other.LastSpace)
424 return LastSpace < Other.LastSpace;
425 if (FirstLessLess != Other.FirstLessLess)
426 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000427 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
428 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000429 if (QuestionColumn != Other.QuestionColumn)
430 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000431 if (AvoidBinPacking != Other.AvoidBinPacking)
432 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000433 if (BreakBeforeParameter != Other.BreakBeforeParameter)
434 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000435 if (HasMultiParameterLine != Other.HasMultiParameterLine)
436 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000437 if (ColonPos != Other.ColonPos)
438 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000439 if (StartOfFunctionCall != Other.StartOfFunctionCall)
440 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperb3123142013-01-12 07:36:22 +0000441 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000442 }
443 };
444
445 /// \brief The current state when indenting a unwrapped line.
446 ///
447 /// As the indenting tries different combinations this is copied by value.
448 struct LineState {
449 /// \brief The number of used columns in the current line.
450 unsigned Column;
451
452 /// \brief The token that needs to be next formatted.
453 const AnnotatedToken *NextToken;
454
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000455 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000456 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000457 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000458 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000459
460 /// \brief \c true if this line contains a continued for-loop section.
461 bool LineContainsContinuedForLoopSection;
462
Daniel Jasper29f123b2013-02-08 15:28:42 +0000463 /// \brief The level of nesting inside (), [], <> and {}.
464 unsigned ParenLevel;
465
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000466 /// \brief The \c ParenLevel at the start of this line.
467 unsigned StartOfLineLevel;
468
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000469 /// \brief The start column of the string literal, if we're in a string
470 /// literal sequence, 0 otherwise.
471 unsigned StartOfStringLiteral;
472
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000473 /// \brief A stack keeping track of properties applying to parenthesis
474 /// levels.
475 std::vector<ParenState> Stack;
476
477 /// \brief Comparison operator to be able to used \c LineState in \c map.
478 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000479 if (NextToken != Other.NextToken)
480 return NextToken < Other.NextToken;
481 if (Column != Other.Column)
482 return Column < Other.Column;
483 if (VariablePos != Other.VariablePos)
484 return VariablePos < Other.VariablePos;
485 if (LineContainsContinuedForLoopSection !=
486 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000487 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000488 if (ParenLevel != Other.ParenLevel)
489 return ParenLevel < Other.ParenLevel;
490 if (StartOfLineLevel != Other.StartOfLineLevel)
491 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000492 if (StartOfStringLiteral != Other.StartOfStringLiteral)
493 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000494 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 }
496 };
497
Daniel Jasper20409152012-12-04 14:54:30 +0000498 /// \brief Appends the next token to \p State and updates information
499 /// necessary for indentation.
500 ///
501 /// Puts the token on the current line if \p Newline is \c true and adds a
502 /// line break and necessary indentation otherwise.
503 ///
504 /// If \p DryRun is \c false, also creates and stores the required
505 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000506 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000507 const AnnotatedToken &Current = *State.NextToken;
508 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000509 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000510
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000511 if (Current.Type == TT_ImplicitStringLiteral) {
512 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
513 State.NextToken->FormatTok.TokenLength;
514 if (State.NextToken->Children.empty())
515 State.NextToken = NULL;
516 else
517 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000518 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000519 }
520
Daniel Jasperbac016b2012-12-03 18:12:45 +0000521 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000522 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000523 if (Current.is(tok::r_brace)) {
524 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000525 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000526 State.StartOfStringLiteral != 0) {
527 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000528 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000529 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000530 State.Stack.back().FirstLessLess != 0) {
531 State.Column = State.Stack.back().FirstLessLess;
532 } else if (State.ParenLevel != 0 &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000533 (Previous.isOneOf(tok::equal, tok::coloncolon) ||
534 Current.isOneOf(tok::period, tok::arrow, tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000535 // Indent and extra 4 spaces after if we know the current expression is
536 // continued. Don't do that on the top level, as we already indent 4
537 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000538 State.Column = std::max(State.Stack.back().LastSpace,
539 State.Stack.back().Indent) + 4;
540 } else if (Current.Type == TT_ConditionalExpr) {
541 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000542 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000543 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
544 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000545 State.Column = State.VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000546 } else if (Previous.ClosesTemplateDeclaration ||
547 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000548 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000549 } else if (Current.Type == TT_ObjCSelectorName) {
550 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
551 State.Column =
552 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
553 } else {
554 State.Column = State.Stack.back().Indent;
555 State.Stack.back().ColonPos =
556 State.Column + Current.FormatTok.TokenLength;
557 }
Daniel Jasper3c08a812013-02-24 18:54:32 +0000558 } else if (Previous.Type == TT_ObjCMethodExpr ||
559 Current.Type == TT_StartOfName) {
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000560 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000561 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000562 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000563 }
564
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000565 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000566 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000567 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jasper237d4c12013-02-23 21:01:55 +0000568 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000569 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000570
Manuel Klimek060143e2013-01-02 18:33:23 +0000571 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000572 unsigned NewLines = 1;
573 if (Current.Type == TT_LineComment)
574 NewLines =
575 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
576 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000577 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000578 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000579 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000580 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000581 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000582 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000583 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000584
Daniel Jasper29f123b2013-02-08 15:28:42 +0000585 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000586 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000587
588 // Any break on this level means that the parent level has been broken
589 // and we need to avoid bin packing there.
590 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
591 State.Stack[i].BreakBeforeParameter = true;
592 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000593 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000594 State.Stack.back().BreakBeforeParameter = true;
595
Daniel Jasper237d4c12013-02-23 21:01:55 +0000596 // If we break after {, we should also break before the corresponding }.
597 if (Previous.is(tok::l_brace))
598 State.Stack.back().BreakBeforeClosingBrace = true;
599
600 if (State.Stack.back().AvoidBinPacking) {
601 // If we are breaking after '(', '{', '<', this is not bin packing
602 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000603 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000604 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
605 Line.MustBeDeclaration))
606 State.Stack.back().BreakBeforeParameter = true;
607 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000608 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000609 // FIXME: Put VariablePos into ParenState and remove second part of if().
610 if (Current.is(tok::equal) &&
611 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000612 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000613
Daniel Jasper729a7432013-02-11 12:36:37 +0000614 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000615
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000617 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000618
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000619 if (Current.Type == TT_ObjCSelectorName &&
620 State.Stack.back().ColonPos == 0) {
621 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
622 State.Column + Spaces + Current.FormatTok.TokenLength)
623 State.Stack.back().ColonPos =
624 State.Stack.back().Indent + Current.LongestObjCSelectorName;
625 else
626 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000627 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000628 }
629
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000630 if (Current.Type != TT_LineComment &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000631 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000632 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000633 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000634 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000635 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000636
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000637 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000638 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
639 // Treat the condition inside an if as if it was a second function
640 // parameter, i.e. let nested calls have an indent of 4.
641 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000642 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000643 // Top-level spaces are exempt as that mostly leads to better results.
644 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000645 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000646 Previous.Type == TT_ConditionalExpr ||
647 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000648 getPrecedence(Previous) != prec::Assignment)
649 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000650 else if (Previous.Type == TT_InheritanceColon)
651 State.Stack.back().Indent = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000652 else if (Previous.ParameterCount > 1 &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000653 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000654 Previous.Type == TT_TemplateOpener))
655 // If this function has multiple parameters, indent nested calls from
656 // the start of the first parameter.
657 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000658 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000659
Manuel Klimek8092a942013-02-20 10:15:13 +0000660 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000661 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000662
Daniel Jasper20409152012-12-04 14:54:30 +0000663 /// \brief Mark the next token as consumed in \p State and modify its stacks
664 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000665 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000666 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000667 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000668
Daniel Jasper6cabab42013-02-14 08:42:54 +0000669 if (Current.Type == TT_InheritanceColon)
670 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000671 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
672 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000673 if (Current.is(tok::question))
674 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000675 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000676 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
677 State.Stack.back().StartOfFunctionCall =
678 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000679 if (Current.Type == TT_CtorInitializerColon) {
680 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
681 State.Stack.back().AvoidBinPacking = true;
682 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000683 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000684
Daniel Jasper29f123b2013-02-08 15:28:42 +0000685 // Insert scopes created by fake parenthesis.
686 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
687 ParenState NewParenState = State.Stack.back();
688 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jasper237d4c12013-02-23 21:01:55 +0000689 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000690 State.Stack.push_back(NewParenState);
691 }
692
Daniel Jaspercf225b62012-12-24 13:43:52 +0000693 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000694 // prepare for the following tokens.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000695 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000696 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000697 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000698 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000699 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000700 NewIndent = 2 + State.Stack.back().LastSpace;
701 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000702 } else {
Daniel Jasper24849712013-03-01 16:48:32 +0000703 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
704 State.Stack.back().StartOfFunctionCall);
Daniel Jasper3a39ac72013-02-28 09:39:12 +0000705 AvoidBinPacking =
706 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000707 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000708 State.Stack.push_back(
709 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
710 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000711 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000712 }
713
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000714 // If this '[' opens an ObjC call, determine whether all parameters fit into
715 // one line and put one per line if they don't.
716 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
717 Current.MatchingParen != NULL) {
718 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
719 State.Stack.back().BreakBeforeParameter = true;
720 }
721
Daniel Jaspercf225b62012-12-24 13:43:52 +0000722 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000723 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000724 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000725 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
726 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000727 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000728 --State.ParenLevel;
729 }
730
731 // Remove scopes created by fake parenthesis.
732 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
733 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000735
Manuel Klimeke9a62262013-02-20 15:32:58 +0000736 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000737 State.StartOfStringLiteral = State.Column;
738 } else if (Current.isNot(tok::comment)) {
739 State.StartOfStringLiteral = 0;
740 }
741
Manuel Klimek8092a942013-02-20 10:15:13 +0000742 State.Column += Current.FormatTok.TokenLength;
743
Daniel Jasper26f7e782013-01-08 14:56:18 +0000744 if (State.NextToken->Children.empty())
745 State.NextToken = NULL;
746 else
747 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000748
Manuel Klimek8092a942013-02-20 10:15:13 +0000749 return breakProtrudingToken(Current, State, DryRun);
750 }
751
752 /// \brief If the current token sticks out over the end of the line, break
753 /// it if possible.
754 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
755 bool DryRun) {
756 if (Current.isNot(tok::string_literal))
757 return 0;
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000758 // Only break up default narrow strings.
759 if (StringRef(Current.FormatTok.Tok.getLiteralData()).find('"') != 0)
760 return 0;
Manuel Klimek8092a942013-02-20 10:15:13 +0000761
762 unsigned Penalty = 0;
763 unsigned TailOffset = 0;
764 unsigned TailLength = Current.FormatTok.TokenLength;
765 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
766 unsigned OffsetFromStart = 0;
767 while (StartColumn + TailLength > getColumnLimit()) {
Daniel Jasper6f21a982013-03-13 07:49:51 +0000768 StringRef Text = StringRef(
769 Current.FormatTok.Tok.getLiteralData() + TailOffset, TailLength);
Manuel Klimekbc30c712013-03-01 13:29:19 +0000770 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000771 break;
Manuel Klimekbc30c712013-03-01 13:29:19 +0000772 StringRef::size_type SplitPoint = getSplitPoint(
773 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek8092a942013-02-20 10:15:13 +0000774 if (SplitPoint == StringRef::npos)
775 break;
776 assert(SplitPoint != 0);
777 // +2, because 'Text' starts after the opening quotes, and does not
778 // include the closing quote we need to insert.
779 unsigned WhitespaceStartColumn =
780 StartColumn + OffsetFromStart + SplitPoint + 2;
781 State.Stack.back().LastSpace = StartColumn;
782 if (!DryRun) {
783 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
784 Line.InPPDirective, StartColumn,
785 WhitespaceStartColumn, Style);
786 }
787 TailOffset += SplitPoint + 1;
788 TailLength -= SplitPoint + 1;
789 OffsetFromStart = 1;
Daniel Jasper0fb382b2013-02-26 12:52:34 +0000790 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000791 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
792 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000793 }
794 State.Column = StartColumn + TailLength;
795 return Penalty;
796 }
797
798 StringRef::size_type
799 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000800 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +0000801 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +0000802 return SpaceOffset;
803 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +0000804 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +0000805 return SlashOffset;
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000806 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
807 if (Split != StringRef::npos && Split > 1)
Manuel Klimekbc30c712013-03-01 13:29:19 +0000808 // Do not split at 0.
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000809 return Split - 1;
Manuel Klimekbc30c712013-03-01 13:29:19 +0000810 return StringRef::npos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000811 }
812
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000813 StringRef::size_type
814 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
815 StringRef::size_type NextEscape = Text.find('\\');
816 while (NextEscape != StringRef::npos && NextEscape < Offset) {
817 StringRef::size_type SequenceLength =
818 getEscapeSequenceLength(Text.substr(NextEscape));
819 if (Offset < NextEscape + SequenceLength)
820 return NextEscape;
821 NextEscape = Text.find('\\', NextEscape + SequenceLength);
822 }
823 return Offset;
824 }
825
826 unsigned getEscapeSequenceLength(StringRef Text) {
827 assert(Text[0] == '\\');
828 if (Text.size() < 2)
829 return 1;
830
831 switch (Text[1]) {
832 case 'u':
833 return 6;
834 case 'U':
835 return 10;
836 case 'x':
837 return getHexLength(Text);
838 default:
839 if (Text[1] >= '0' && Text[1] <= '7')
840 return getOctalLength(Text);
841 return 2;
842 }
843 }
844
845 unsigned getHexLength(StringRef Text) {
846 unsigned I = 2; // Point after '\x'.
847 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
848 (Text[I] >= 'a' && Text[I] <= 'f') ||
849 (Text[I] >= 'A' && Text[I] <= 'F'))) {
850 ++I;
851 }
852 return I;
853 }
854
855 unsigned getOctalLength(StringRef Text) {
856 unsigned I = 1;
857 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
858 ++I;
859 }
860 return I;
861 }
862
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000863 unsigned getColumnLimit() {
Daniel Jaspera4d46212013-02-28 11:05:57 +0000864 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000865 }
866
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000867 /// \brief An edge in the solution space from \c Previous->State to \c State,
868 /// inserting a newline dependent on the \c NewLine.
869 struct StateNode {
870 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000871 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000872 LineState State;
873 bool NewLine;
874 StateNode *Previous;
875 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000876
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000877 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
878 ///
879 /// In case of equal penalties, we want to prefer states that were inserted
880 /// first. During state generation we make sure that we insert states first
881 /// that break the line as late as possible.
882 typedef std::pair<unsigned, unsigned> OrderedPenalty;
883
884 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
885 /// \c State has the given \c OrderedPenalty.
886 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
887
888 /// \brief The BFS queue type.
889 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
890 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000891
892 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000893 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000894 /// This implements a variant of Dijkstra's algorithm on the graph that spans
895 /// the solution space (\c LineStates are the nodes). The algorithm tries to
896 /// find the shortest path (the one with lowest penalty) from \p InitialState
897 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000898 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000899 std::set<LineState> Seen;
900
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000901 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000902 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000903 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
904 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
905 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000906
907 // While not empty, take first element and follow edges.
908 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000909 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000910 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000911 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000912 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000913 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000914 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000915 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000916
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000917 if (!Seen.insert(Node->State).second)
918 // State already examined with lower penalty.
919 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000920
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000921 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
922 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000923 }
924
925 if (Queue.empty())
926 // We were unable to find a solution, do nothing.
927 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000928 return 0;
929
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000930 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000931 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000932 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000933
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000934 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000935 return Queue.top().second->State.Column;
936 }
937
938 void reconstructPath(LineState &State, StateNode *Current) {
939 // FIXME: This recursive implementation limits the possible number
940 // of tokens per line if compiled into a binary with small stack space.
941 // To become more independent of stack frame limitations we would need
942 // to also change the TokenAnnotator.
943 if (Current->Previous == NULL)
944 return;
945 reconstructPath(State, Current->Previous);
946 DEBUG({
947 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000948 llvm::errs()
949 << "Penalty for splitting before "
950 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
951 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000952 }
953 });
954 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000955 }
956
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000957 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000958 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000959 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000960 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000961 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
962 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000963 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000964 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000965 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000966 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000967 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000968 Penalty += PreviousNode->State.NextToken->SplitPenalty;
969
970 StateNode *Node = new (Allocator.Allocate())
971 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000972 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000973 if (Node->State.Column > getColumnLimit()) {
974 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000975 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000976 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000977
978 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
979 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000980 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000981
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000982 /// \brief Returns \c true, if a line break after \p State is allowed.
983 bool canBreak(const LineState &State) {
984 if (!State.NextToken->CanBreakBefore &&
985 !(State.NextToken->is(tok::r_brace) &&
986 State.Stack.back().BreakBeforeClosingBrace))
987 return false;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000988 // This prevents breaks like:
989 // ...
990 // SomeParameter, OtherParameter).DoSomething(
991 // ...
992 // As they hide "DoSomething" and generally bad for readability.
993 if (State.NextToken->Parent->is(tok::l_paren) &&
994 State.ParenLevel <= State.StartOfLineLevel)
995 return false;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000996 // Trying to insert a parameter on a new line if there are already more than
997 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000998 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000999 State.Stack.back().AvoidBinPacking)
1000 return false;
1001 return true;
1002 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001003
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001004 /// \brief Returns \c true, if a line break after \p State is mandatory.
1005 bool mustBreak(const LineState &State) {
1006 if (State.NextToken->MustBreakBefore)
1007 return true;
1008 if (State.NextToken->is(tok::r_brace) &&
1009 State.Stack.back().BreakBeforeClosingBrace)
1010 return true;
1011 if (State.NextToken->Parent->is(tok::semi) &&
1012 State.LineContainsContinuedForLoopSection)
1013 return true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001014 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +00001015 State.NextToken->is(tok::question) ||
1016 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001017 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc5cfa492013-02-14 09:19:04 +00001018 !isTrailingComment(*State.NextToken) &&
Daniel Jasper7d812812013-02-21 15:00:29 +00001019 State.NextToken->isNot(tok::r_paren) &&
1020 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001021 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001022 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1023 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001024 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001025 State.NextToken->LongestObjCSelectorName == 0 &&
1026 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001027 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001028 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1029 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +00001030 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001031 return true;
Daniel Jasper923ebef2013-03-14 13:45:21 +00001032 if (State.NextToken->Type == TT_InlineASMColon)
1033 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001034 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001035 }
1036
Daniel Jasperbac016b2012-12-03 18:12:45 +00001037 FormatStyle Style;
1038 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001039 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001040 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001041 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001042 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001043
1044 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1045 QueueType Queue;
1046 // Increasing count of \c StateNode items we have created. This is used
1047 // to create a deterministic order independent of the container.
1048 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001049};
1050
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001051class LexerBasedFormatTokenSource : public FormatTokenSource {
1052public:
1053 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001054 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001055 IdentTable(Lex.getLangOpts()) {
1056 Lex.SetKeepWhitespaceMode(true);
1057 }
1058
1059 virtual FormatToken getNextToken() {
1060 if (GreaterStashed) {
1061 FormatTok.NewlinesBefore = 0;
1062 FormatTok.WhiteSpaceStart =
1063 FormatTok.Tok.getLocation().getLocWithOffset(1);
1064 FormatTok.WhiteSpaceLength = 0;
1065 GreaterStashed = false;
1066 return FormatTok;
1067 }
1068
1069 FormatTok = FormatToken();
1070 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001071 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001072 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001073 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1074 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001075
1076 // Consume and record whitespace until we find a significant token.
1077 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001078 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001079 if (Newlines > 0)
1080 FormatTok.LastNewlineOffset =
1081 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001082 unsigned EscapedNewlines = Text.count("\\\n");
1083 FormatTok.NewlinesBefore += Newlines;
1084 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001085 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1086
1087 if (FormatTok.Tok.is(tok::eof))
1088 return FormatTok;
1089 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001090 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001091 }
Manuel Klimek95419382013-01-07 07:56:50 +00001092
1093 // Now FormatTok is the next non-whitespace token.
1094 FormatTok.TokenLength = Text.size();
1095
Manuel Klimekd4397b92013-01-04 23:34:14 +00001096 // In case the token starts with escaped newlines, we want to
1097 // take them into account as whitespace - this pattern is quite frequent
1098 // in macro definitions.
1099 // FIXME: What do we want to do with other escaped spaces, and escaped
1100 // spaces or newlines in the middle of tokens?
1101 // FIXME: Add a more explicit test.
1102 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001103 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001104 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001105 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001106 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001107 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001108 }
1109
1110 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001111 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001112 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001113 FormatTok.Tok.setKind(Info.getTokenID());
1114 }
1115
1116 if (FormatTok.Tok.is(tok::greatergreater)) {
1117 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001118 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001119 GreaterStashed = true;
1120 }
1121
Daniel Jasper812c0452013-03-01 16:45:59 +00001122 // If we reformat comments, we remove trailing whitespace. Update the length
1123 // accordingly.
1124 if (FormatTok.Tok.is(tok::comment))
1125 FormatTok.TokenLength = Text.rtrim().size();
1126
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001127 return FormatTok;
1128 }
1129
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001130 IdentifierTable &getIdentTable() { return IdentTable; }
1131
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001132private:
1133 FormatToken FormatTok;
1134 bool GreaterStashed;
1135 Lexer &Lex;
1136 SourceManager &SourceMgr;
1137 IdentifierTable IdentTable;
1138
1139 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001140 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001141 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1142 Tok.getLength());
1143 }
1144};
1145
Daniel Jasperbac016b2012-12-03 18:12:45 +00001146class Formatter : public UnwrappedLineConsumer {
1147public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001148 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1149 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001151 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperf11a7052013-02-21 21:33:55 +00001152 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001153
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001154 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001155
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001156 tooling::Replacements format() {
1157 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1158 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1159 StructuralError = Parser.parse();
1160 unsigned PreviousEndOfLineColumn = 0;
1161 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1162 Tokens.getIdentTable().get("in"));
1163 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1164 Annotator.annotate(AnnotatedLines[i]);
1165 }
1166 deriveLocalStyle();
1167 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1168 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper6050a1e2013-03-13 15:53:12 +00001169
1170 // Adapt level to the next line if this is a comment.
1171 // FIXME: Can/should this be done in the UnwrappedLineParser?
1172 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1173 AnnotatedLines[i].First.Children.empty() &&
1174 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1175 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001176 }
1177 std::vector<int> IndentForLevel;
1178 bool PreviousLineWasTouched = false;
1179 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1180 E = AnnotatedLines.end();
1181 I != E; ++I) {
1182 const AnnotatedLine &TheLine = *I;
1183 const FormatToken &FirstTok = TheLine.First.FormatTok;
1184 int Offset = getIndentOffset(TheLine.First);
1185 while (IndentForLevel.size() <= TheLine.Level)
1186 IndentForLevel.push_back(-1);
1187 IndentForLevel.resize(TheLine.Level + 1);
1188 bool WasMoved =
1189 PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
1190 if (TheLine.First.is(tok::eof)) {
1191 if (PreviousLineWasTouched) {
1192 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1193 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
1194 /*WhitespaceStartColumn*/ 0, Style);
1195 }
1196 } else if (TheLine.Type != LT_Invalid &&
1197 (WasMoved || touchesLine(TheLine))) {
1198 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1199 unsigned Indent = LevelIndent;
1200 if (static_cast<int>(Indent) + Offset >= 0)
1201 Indent += Offset;
1202 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
1203 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1204 FirstTok.Tok.getLocation()) - 1;
1205 } else {
1206 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1207 PreviousEndOfLineColumn);
1208 }
1209 tryFitMultipleLinesInOne(Indent, I, E);
1210 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1211 TheLine.First, Whitespaces,
1212 StructuralError);
1213 PreviousEndOfLineColumn =
1214 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1215 IndentForLevel[TheLine.Level] = LevelIndent;
1216 PreviousLineWasTouched = true;
1217 } else {
1218 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1219 unsigned Indent =
1220 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1221 unsigned LevelIndent = Indent;
1222 if (static_cast<int>(LevelIndent) - Offset >= 0)
1223 LevelIndent -= Offset;
1224 IndentForLevel[TheLine.Level] = LevelIndent;
1225
1226 // Remove trailing whitespace of the previous line if it was touched.
1227 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1228 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1229 PreviousEndOfLineColumn);
1230 }
1231 // If we did not reformat this unwrapped line, the column at the end of
1232 // the last token is unchanged - thus, we can calculate the end of the
1233 // last token.
1234 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1235 PreviousEndOfLineColumn =
1236 SourceMgr.getSpellingColumnNumber(LastLoc) +
1237 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1238 PreviousLineWasTouched = false;
1239 }
1240 }
1241 return Whitespaces.generateReplacements();
1242 }
1243
1244private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001245 void deriveLocalStyle() {
1246 unsigned CountBoundToVariable = 0;
1247 unsigned CountBoundToType = 0;
1248 bool HasCpp03IncompatibleFormat = false;
1249 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1250 if (AnnotatedLines[i].First.Children.empty())
1251 continue;
1252 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1253 while (!Tok->Children.empty()) {
1254 if (Tok->Type == TT_PointerOrReference) {
1255 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1256 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1257 if (SpacesBefore && !SpacesAfter)
1258 ++CountBoundToVariable;
1259 else if (!SpacesBefore && SpacesAfter)
1260 ++CountBoundToType;
1261 }
1262
Daniel Jasper29f123b2013-02-08 15:28:42 +00001263 if (Tok->Type == TT_TemplateCloser &&
1264 Tok->Parent->Type == TT_TemplateCloser &&
1265 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001266 HasCpp03IncompatibleFormat = true;
1267 Tok = &Tok->Children[0];
1268 }
1269 }
1270 if (Style.DerivePointerBinding) {
1271 if (CountBoundToType > CountBoundToVariable)
1272 Style.PointerBindsToType = true;
1273 else if (CountBoundToType < CountBoundToVariable)
1274 Style.PointerBindsToType = false;
1275 }
1276 if (Style.Standard == FormatStyle::LS_Auto) {
1277 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1278 : FormatStyle::LS_Cpp03;
1279 }
1280 }
1281
Manuel Klimek547d5db2013-02-08 17:38:27 +00001282 /// \brief Get the indent of \p Level from \p IndentForLevel.
1283 ///
1284 /// \p IndentForLevel must contain the indent for the level \c l
1285 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1286 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001287 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001288 if (IndentForLevel[Level] != -1)
1289 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001290 if (Level == 0)
1291 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001292 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001293 }
1294
1295 /// \brief Get the offset of the line relatively to the level.
1296 ///
1297 /// For example, 'public:' labels in classes are offset by 1 or 2
1298 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001299 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001300 bool IsAccessModifier = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001301 if (RootToken.isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
Manuel Klimek547d5db2013-02-08 17:38:27 +00001302 IsAccessModifier = true;
1303 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1304 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1305 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1306 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1307 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1308 IsAccessModifier = true;
1309
1310 if (IsAccessModifier)
1311 return Style.AccessModifierOffset;
1312 return 0;
1313 }
1314
Manuel Klimek517e8942013-01-11 17:54:10 +00001315 /// \brief Tries to merge lines into one.
1316 ///
1317 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1318 /// if possible; note that \c I will be incremented when lines are merged.
1319 ///
1320 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001321 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001322 std::vector<AnnotatedLine>::iterator &I,
1323 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001324 // We can never merge stuff if there are trailing line comments.
1325 if (I->Last->Type == TT_LineComment)
1326 return;
1327
Daniel Jaspera4d46212013-02-28 11:05:57 +00001328 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001329 // If we already exceed the column limit, we set 'Limit' to 0. The different
1330 // tryMerge..() functions can then decide whether to still do merging.
1331 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001332
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001333 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001334 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001335
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001336 if (I->Last->is(tok::l_brace)) {
1337 tryMergeSimpleBlock(I, E, Limit);
1338 } else if (I->First.is(tok::kw_if)) {
1339 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001340 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1341 I->First.FormatTok.IsFirst)) {
1342 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001343 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001344 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001345 }
1346
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001347 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1348 std::vector<AnnotatedLine>::iterator E,
1349 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001350 if (Limit == 0)
1351 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001352 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001353 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1354 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001355 if (I + 2 != E && (I + 2)->InPPDirective &&
1356 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1357 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001358 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001359 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001360 join(Line, *(++I));
1361 }
1362
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001363 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1364 std::vector<AnnotatedLine>::iterator E,
1365 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001366 if (Limit == 0)
1367 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001368 if (!Style.AllowShortIfStatementsOnASingleLine)
1369 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001370 if ((I + 1)->InPPDirective != I->InPPDirective ||
1371 ((I + 1)->InPPDirective &&
1372 (I + 1)->First.FormatTok.HasUnescapedNewline))
1373 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001374 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001375 if (Line.Last->isNot(tok::r_paren))
1376 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001377 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001378 return;
1379 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1380 return;
1381 // Only inline simple if's (no nested if or else).
1382 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1383 return;
1384 join(Line, *(++I));
1385 }
1386
1387 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001388 std::vector<AnnotatedLine>::iterator E,
1389 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001390 // First, check that the current line allows merging. This is the case if
1391 // we're not in a control flow statement and the last token is an opening
1392 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001393 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001394 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1395 tok::kw_else, tok::kw_try, tok::kw_catch,
1396 tok::kw_for,
1397 // This gets rid of all ObjC @ keywords and methods.
1398 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001399 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001400
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001401 AnnotatedToken *Tok = &(I + 1)->First;
1402 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001403 !Tok->MustBreakBefore) {
1404 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001405 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001406 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001407 join(Line, *(I + 1));
1408 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001409 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001410 // Check that we still have three lines and they fit into the limit.
1411 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1412 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001413 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001414
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001415 // Second, check that the next line does not contain any braces - if it
1416 // does, readability declines when putting it into a single line.
1417 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1418 return;
1419 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001420 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001421 return;
1422 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1423 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001424
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001425 // Last, check that the third line contains a single closing brace.
1426 Tok = &(I + 2)->First;
1427 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1428 Tok->MustBreakBefore)
1429 return;
1430
1431 join(Line, *(I + 1));
1432 join(Line, *(I + 2));
1433 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001434 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001435 }
1436
1437 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1438 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001439 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1440 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001441 }
1442
Daniel Jasper995e8202013-01-14 13:08:07 +00001443 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001444 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001445 A.Last->Children.push_back(B.First);
1446 while (!A.Last->Children.empty()) {
1447 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001448 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001449 A.Last = &A.Last->Children[0];
1450 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001451 }
1452
Daniel Jasper6f21a982013-03-13 07:49:51 +00001453 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001454 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1455 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1456 Ranges[i].getBegin()) &&
1457 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1458 Range.getBegin()))
1459 return true;
1460 }
1461 return false;
1462 }
1463
1464 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001465 const FormatToken *First = &TheLine.First.FormatTok;
1466 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001467 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001468 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1469 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001470 return touchesRanges(LineRange);
1471 }
1472
1473 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1474 const FormatToken *First = &TheLine.First.FormatTok;
1475 CharSourceRange LineRange = CharSourceRange::getCharRange(
1476 First->WhiteSpaceStart,
1477 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1478 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001479 }
1480
1481 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001482 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001483 }
1484
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001485 /// \brief Add a new line and the required indent before the first Token
1486 /// of the \c UnwrappedLine if there was no structural parsing error.
1487 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek547d5db2013-02-08 17:38:27 +00001488 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1489 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001490 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001491
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001492 unsigned Newlines =
1493 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001494 if (Newlines == 0 && !Tok.IsFirst)
1495 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001496
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001497 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001498 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001499 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001500 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1501 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001502 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001503 }
1504
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001505 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001506 FormatStyle Style;
1507 Lexer &Lex;
1508 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001509 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001510 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001511 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001512 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001513};
1514
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001515tooling::Replacements
1516reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1517 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001518 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001519 OwningPtr<DiagnosticConsumer> DiagPrinter;
1520 if (DiagClient == 0) {
1521 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1522 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1523 DiagClient = DiagPrinter.get();
1524 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001525 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001526 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001527 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001528 Diagnostics.setSourceManager(&SourceMgr);
1529 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001530 return formatter.format();
1531}
1532
Daniel Jasper46ef8522013-01-10 13:08:12 +00001533LangOptions getFormattingLangOpts() {
1534 LangOptions LangOpts;
1535 LangOpts.CPlusPlus = 1;
1536 LangOpts.CPlusPlus11 = 1;
1537 LangOpts.Bool = 1;
1538 LangOpts.ObjC1 = 1;
1539 LangOpts.ObjC2 = 1;
1540 return LangOpts;
1541}
1542
Daniel Jaspercd162382013-01-07 13:26:07 +00001543} // namespace format
1544} // namespace clang