blob: 9fd8ac6916f015a0ae8eae52c6e8ec3b5769a31e [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
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod71ec162013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
39 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
40 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
41 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
42 }
43};
44
Daniel Jasper1fb8d882013-05-14 09:30:02 +000045template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000046struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
47 static void
48 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
49 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
50 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
51 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000052 }
53};
54
55template <> struct MappingTraits<clang::format::FormatStyle> {
56 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000057 if (IO.outputting()) {
58 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
59 ArrayRef<StringRef> Styles(StylesArray);
60 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
61 StringRef StyleName(Styles[i]);
62 if (Style == clang::format::getPredefinedStyle(StyleName)) {
63 IO.mapOptional("# BasedOnStyle", StyleName);
64 break;
65 }
66 }
67 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000068 StringRef BasedOnStyle;
69 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000070 if (!BasedOnStyle.empty())
71 Style = clang::format::getPredefinedStyle(BasedOnStyle);
72 }
73
74 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
75 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
76 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
77 Style.AllowAllParametersOfDeclarationOnNextLine);
78 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
79 Style.AllowShortIfStatementsOnASingleLine);
80 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
81 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
82 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
83 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
84 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
85 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
86 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
87 IO.mapOptional("ObjCSpaceBeforeProtocolList",
88 Style.ObjCSpaceBeforeProtocolList);
89 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
90 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
91 Style.PenaltyReturnTypeOnItsOwnLine);
92 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
93 IO.mapOptional("SpacesBeforeTrailingComments",
94 Style.SpacesBeforeTrailingComments);
95 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +000096 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +000097 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +000098 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000099 }
100};
101}
102}
103
Daniel Jasperbac016b2012-12-03 18:12:45 +0000104namespace clang {
105namespace format {
106
Daniel Jasperbac016b2012-12-03 18:12:45 +0000107FormatStyle getLLVMStyle() {
108 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000109 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000110 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000111 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000112 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000113 LLVMStyle.BinPackParameters = true;
114 LLVMStyle.ColumnLimit = 80;
115 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
116 LLVMStyle.DerivePointerBinding = false;
117 LLVMStyle.IndentCaseLabels = false;
118 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000119 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000120 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000121 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000122 LLVMStyle.PointerBindsToType = false;
123 LLVMStyle.SpacesBeforeTrailingComments = 1;
124 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000125 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000126 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000127 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000128 return LLVMStyle;
129}
130
131FormatStyle getGoogleStyle() {
132 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000133 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000134 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000135 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000136 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000137 GoogleStyle.BinPackParameters = true;
138 GoogleStyle.ColumnLimit = 80;
139 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
140 GoogleStyle.DerivePointerBinding = true;
141 GoogleStyle.IndentCaseLabels = true;
142 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000143 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +0000144 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000145 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000146 GoogleStyle.PointerBindsToType = true;
147 GoogleStyle.SpacesBeforeTrailingComments = 2;
148 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000149 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000150 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000151 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000152 return GoogleStyle;
153}
154
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000155FormatStyle getChromiumStyle() {
156 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000157 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000158 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000159 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000160 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
161 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000162 return ChromiumStyle;
163}
164
Alexander Kornienkofb594862013-05-06 14:11:27 +0000165FormatStyle getMozillaStyle() {
166 FormatStyle MozillaStyle = getLLVMStyle();
167 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
168 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
169 MozillaStyle.DerivePointerBinding = true;
170 MozillaStyle.IndentCaseLabels = true;
171 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
172 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
173 MozillaStyle.PointerBindsToType = true;
174 return MozillaStyle;
175}
176
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000177FormatStyle getPredefinedStyle(StringRef Name) {
178 if (Name.equals_lower("llvm"))
179 return getLLVMStyle();
180 if (Name.equals_lower("chromium"))
181 return getChromiumStyle();
182 if (Name.equals_lower("mozilla"))
183 return getMozillaStyle();
184 if (Name.equals_lower("google"))
185 return getGoogleStyle();
186
187 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
188 return getGoogleStyle();
189}
190
191llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
192 llvm::yaml::Input Input(Text);
193 Input >> *Style;
194 return Input.error();
195}
196
197std::string configurationAsText(const FormatStyle &Style) {
198 std::string Text;
199 llvm::raw_string_ostream Stream(Text);
200 llvm::yaml::Output Output(Stream);
201 // We use the same mapping method for input and output, so we need a non-const
202 // reference here.
203 FormatStyle NonConstStyle = Style;
204 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000205 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000206}
207
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000208// Returns the length of everything up to the first possible line break after
209// the ), ], } or > matching \c Tok.
210static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
211 if (Tok.MatchingParen == NULL)
212 return 0;
213 AnnotatedToken *End = Tok.MatchingParen;
214 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
215 End = &End->Children[0];
216 }
217 return End->TotalLength - Tok.TotalLength + 1;
218}
219
Daniel Jasperbac016b2012-12-03 18:12:45 +0000220class UnwrappedLineFormatter {
221public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000222 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000223 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000224 const AnnotatedToken &RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000225 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000226 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000227 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000228 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000229
Manuel Klimekd4397b92013-01-04 23:34:14 +0000230 /// \brief Formats an \c UnwrappedLine.
231 ///
232 /// \returns The column after the last token in the last line of the
233 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000234 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000235 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000236 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000237 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000238 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000239 State.Stack.push_back(
Daniel Jasper37911302013-04-02 14:33:13 +0000240 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000241 /*NoLineBreak=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000242 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000243 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000244 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000245 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000246
247 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000248 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000249
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000250 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000251 unsigned ColumnLimit = Style.ColumnLimit;
252 if (NextLine && NextLine->InPPDirective &&
253 !NextLine->First.FormatTok.HasUnescapedNewline)
254 ColumnLimit = getColumnLimit();
255 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000256 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000257 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000258 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000259 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000260 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000261
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000262 // If the ObjC method declaration does not fit on a line, we should format
263 // it with one arg per line.
264 if (Line.Type == LT_ObjCMethodDecl)
265 State.Stack.back().BreakBeforeParameter = true;
266
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000267 // Find best solution in solution space.
268 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269 }
270
271private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000272 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
273 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000274 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000275 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000276 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000277 }
278
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000279 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000280 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000281 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000282 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
283 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000284 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000285 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
286 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000287 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000288
Daniel Jasperbac016b2012-12-03 18:12:45 +0000289 /// \brief The position to which a specific parenthesis level needs to be
290 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000291 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000292
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000293 /// \brief The position of the last space on each level.
294 ///
295 /// Used e.g. to break like:
296 /// functionCall(Parameter, otherCall(
297 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000298 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000299
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000300 /// \brief The position the first "<<" operator encountered on each level.
301 ///
302 /// Used to align "<<" operators. 0 if no such operator has been encountered
303 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000304 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000305
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000306 /// \brief Whether a newline needs to be inserted before the block's closing
307 /// brace.
308 ///
309 /// We only want to insert a newline before the closing brace if there also
310 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000311 bool BreakBeforeClosingBrace;
312
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000313 /// \brief The column of a \c ? in a conditional expression;
314 unsigned QuestionColumn;
315
Daniel Jasperf343cab2013-01-31 14:59:26 +0000316 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
317 /// lines, in this context.
318 bool AvoidBinPacking;
319
320 /// \brief Break after the next comma (or all the commas in this context if
321 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000322 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000323
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000324 /// \brief Line breaking in this context would break a formatting rule.
325 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000326
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000327 /// \brief The position of the colon in an ObjC method declaration/call.
328 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000329
Daniel Jasper24849712013-03-01 16:48:32 +0000330 /// \brief The start of the most recent function in a builder-type call.
331 unsigned StartOfFunctionCall;
332
Daniel Jasper37911302013-04-02 14:33:13 +0000333 /// \brief If a nested name specifier was broken over multiple lines, this
334 /// contains the start column of the second line. Otherwise 0.
335 unsigned NestedNameSpecifierContinuation;
336
337 /// \brief If a call expression was broken over multiple lines, this
338 /// contains the start column of the second line. Otherwise 0.
339 unsigned CallContinuation;
340
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000341 /// \brief The column of the first variable name in a variable declaration.
342 ///
343 /// Used to align further variables if necessary.
344 unsigned VariablePos;
345
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000346 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
347 ///
348 /// Does not need to be considered for memoization / the comparison function
349 /// as otherwise identical states will have the same fake/non-fake
350 /// \c ParenStates.
351 bool ForFakeParenthesis;
352
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000353 bool operator<(const ParenState &Other) const {
354 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000355 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000356 if (LastSpace != Other.LastSpace)
357 return LastSpace < Other.LastSpace;
358 if (FirstLessLess != Other.FirstLessLess)
359 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000360 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
361 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000362 if (QuestionColumn != Other.QuestionColumn)
363 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000364 if (AvoidBinPacking != Other.AvoidBinPacking)
365 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000366 if (BreakBeforeParameter != Other.BreakBeforeParameter)
367 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000368 if (NoLineBreak != Other.NoLineBreak)
369 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000370 if (ColonPos != Other.ColonPos)
371 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000372 if (StartOfFunctionCall != Other.StartOfFunctionCall)
373 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000374 if (CallContinuation != Other.CallContinuation)
375 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000376 if (VariablePos != Other.VariablePos)
377 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000378 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000379 }
380 };
381
382 /// \brief The current state when indenting a unwrapped line.
383 ///
384 /// As the indenting tries different combinations this is copied by value.
385 struct LineState {
386 /// \brief The number of used columns in the current line.
387 unsigned Column;
388
389 /// \brief The token that needs to be next formatted.
390 const AnnotatedToken *NextToken;
391
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000392 /// \brief \c true if this line contains a continued for-loop section.
393 bool LineContainsContinuedForLoopSection;
394
Daniel Jasper29f123b2013-02-08 15:28:42 +0000395 /// \brief The level of nesting inside (), [], <> and {}.
396 unsigned ParenLevel;
397
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000398 /// \brief The \c ParenLevel at the start of this line.
399 unsigned StartOfLineLevel;
400
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000401 /// \brief The start column of the string literal, if we're in a string
402 /// literal sequence, 0 otherwise.
403 unsigned StartOfStringLiteral;
404
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000405 /// \brief A stack keeping track of properties applying to parenthesis
406 /// levels.
407 std::vector<ParenState> Stack;
408
409 /// \brief Comparison operator to be able to used \c LineState in \c map.
410 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000411 if (NextToken != Other.NextToken)
412 return NextToken < Other.NextToken;
413 if (Column != Other.Column)
414 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000415 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000416 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000417 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000418 if (ParenLevel != Other.ParenLevel)
419 return ParenLevel < Other.ParenLevel;
420 if (StartOfLineLevel != Other.StartOfLineLevel)
421 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000422 if (StartOfStringLiteral != Other.StartOfStringLiteral)
423 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000424 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425 }
426 };
427
Daniel Jasper20409152012-12-04 14:54:30 +0000428 /// \brief Appends the next token to \p State and updates information
429 /// necessary for indentation.
430 ///
431 /// Puts the token on the current line if \p Newline is \c true and adds a
432 /// line break and necessary indentation otherwise.
433 ///
434 /// If \p DryRun is \c false, also creates and stores the required
435 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000436 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000437 const AnnotatedToken &Current = *State.NextToken;
438 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000439
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000440 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000441 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
442 State.NextToken->FormatTok.TokenLength;
443 if (State.NextToken->Children.empty())
444 State.NextToken = NULL;
445 else
446 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000447 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000448 }
449
Daniel Jasper3776ef32013-04-03 07:21:51 +0000450 // If we are continuing an expression, we want to indent an extra 4 spaces.
451 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000452 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000453 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000454 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000455 if (Current.is(tok::r_brace)) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000456 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000457 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000458 State.StartOfStringLiteral != 0) {
459 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000460 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000461 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000462 State.Stack.back().FirstLessLess != 0) {
463 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper37911302013-04-02 14:33:13 +0000464 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000465 if (State.Stack.back().CallContinuation == 0) {
466 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000467 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000468 } else {
469 State.Column = State.Stack.back().CallContinuation;
470 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000471 } else if (Current.Type == TT_ConditionalExpr) {
472 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000473 } else if (Previous.is(tok::comma) &&
474 State.Stack.back().VariablePos != 0) {
475 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000476 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000477 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
478 Line.StartsDefinition)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000479 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000480 } else if (Current.Type == TT_ObjCSelectorName) {
481 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
482 State.Column =
483 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
484 } else {
485 State.Column = State.Stack.back().Indent;
486 State.Stack.back().ColonPos =
487 State.Column + Current.FormatTok.TokenLength;
488 }
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000489 } else if (Current.Type == TT_StartOfName ||
490 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000491 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000492 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000493 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000494 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000495 // Ensure that we fall back to indenting 4 spaces instead of just
496 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000497 if (State.Column == FirstIndent)
498 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000499 }
500
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000501 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000502 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000503 if ((Previous.isOneOf(tok::comma, tok::semi) &&
504 !State.Stack.back().AvoidBinPacking) ||
505 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000506 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000507 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
508 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000509
Manuel Klimek060143e2013-01-02 18:33:23 +0000510 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000511 unsigned NewLines = 1;
512 if (Current.Type == TT_LineComment)
513 NewLines =
514 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
515 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000516 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000517 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000518 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000519 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000520 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000521 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000522 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523
Daniel Jasper29f123b2013-02-08 15:28:42 +0000524 State.Stack.back().LastSpace = State.Column;
Daniel Jasper04abbb22013-05-10 13:37:16 +0000525 if (Current.isOneOf(tok::arrow, tok::period))
526 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000527 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000528
529 // Any break on this level means that the parent level has been broken
530 // and we need to avoid bin packing there.
531 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
532 State.Stack[i].BreakBeforeParameter = true;
533 }
Daniel Jasper01218ff2013-04-15 22:36:37 +0000534 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
535 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000536 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000537 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000538 State.Stack.back().BreakBeforeParameter = true;
539
Daniel Jasper237d4c12013-02-23 21:01:55 +0000540 // If we break after {, we should also break before the corresponding }.
541 if (Previous.is(tok::l_brace))
542 State.Stack.back().BreakBeforeClosingBrace = true;
543
544 if (State.Stack.back().AvoidBinPacking) {
545 // If we are breaking after '(', '{', '<', this is not bin packing
546 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000547 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
548 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000549 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
550 Line.MustBeDeclaration))
551 State.Stack.back().BreakBeforeParameter = true;
552 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000553 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000554 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000555 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
556 State.Stack.back().VariablePos == 0) {
557 State.Stack.back().VariablePos = State.Column;
558 // Move over * and & if they are bound to the variable name.
559 const AnnotatedToken *Tok = &Previous;
560 while (Tok &&
561 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
562 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
563 if (Tok->SpacesRequiredBefore != 0)
564 break;
565 Tok = Tok->Parent;
566 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000567 if (Previous.PartOfMultiVariableDeclStmt)
568 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
569 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000570
Daniel Jasper729a7432013-02-11 12:36:37 +0000571 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000572
Daniel Jasperbac016b2012-12-03 18:12:45 +0000573 if (!DryRun)
Alexander Kornienko052685c2013-03-19 17:41:36 +0000574 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper20409152012-12-04 14:54:30 +0000575
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000576 if (Current.Type == TT_ObjCSelectorName &&
577 State.Stack.back().ColonPos == 0) {
578 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000579 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000580 State.Stack.back().ColonPos =
581 State.Stack.back().Indent + Current.LongestObjCSelectorName;
582 else
583 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000584 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000585 }
586
Daniel Jasperac3223e2013-04-10 09:49:49 +0000587 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000588 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000589 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000590 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
591 State.Stack.back().AvoidBinPacking)
592 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000593
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000594 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000595 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000596 // Treat the condition inside an if as if it was a second function
597 // parameter, i.e. let nested calls have an indent of 4.
598 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000599 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000600 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 Jasper11e13802013-05-08 14:12:04 +0000608 else if (Previous.opensScope() && !Current.FakeLParens.empty())
609 // If this function has multiple parameters or a binary expression
610 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper986e17f2013-01-28 07:35:34 +0000611 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000612 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000613
Manuel Klimek8092a942013-02-20 10:15:13 +0000614 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000615 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616
Daniel Jasper20409152012-12-04 14:54:30 +0000617 /// \brief Mark the next token as consumed in \p State and modify its stacks
618 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000619 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000620 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000621 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000622
Daniel Jasper6cabab42013-02-14 08:42:54 +0000623 if (Current.Type == TT_InheritanceColon)
624 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000625 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
626 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000627 if (Current.is(tok::question))
628 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000629 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000630 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
631 State.Stack.back().StartOfFunctionCall =
Daniel Jasper04abbb22013-05-10 13:37:16 +0000632 Current.LastInChainOfCalls ? 0 : State.Column +
633 Current.FormatTok.TokenLength;
Daniel Jasper7d812812013-02-21 15:00:29 +0000634 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000635 // Indent 2 from the column, so:
636 // SomeClass::SomeClass()
637 // : First(...), ...
638 // Next(...)
639 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000640 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000641 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
642 State.Stack.back().AvoidBinPacking = true;
643 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000644 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000645
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000646 // If return returns a binary expression, align after it.
647 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
648 State.Stack.back().LastSpace = State.Column + 7;
649
Daniel Jasper3776ef32013-04-03 07:21:51 +0000650 // In ObjC method declaration we align on the ":" of parameters, but we need
651 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000652 if (Current.Type == TT_ObjCMethodSpecifier)
653 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000654
Daniel Jasper29f123b2013-02-08 15:28:42 +0000655 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000656 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
657 // Don't add extra indentation for the first fake parenthesis after
658 // 'return', assignements or opening <({[. The indentation for these cases
659 // is special cased.
660 bool SkipFirstExtraIndent =
661 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000662 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000663 getPrecedence(*Previous) == prec::Assignment));
664 for (SmallVector<prec::Level, 4>::const_reverse_iterator
665 I = Current.FakeLParens.rbegin(),
666 E = Current.FakeLParens.rend();
667 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000668 ParenState NewParenState = State.Stack.back();
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000669 NewParenState.ForFakeParenthesis = true;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000670 NewParenState.Indent =
671 std::max(std::max(State.Column, NewParenState.Indent),
672 State.Stack.back().LastSpace);
673
674 // Always indent conditional expressions. Never indent expression where
675 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
676 // prec::Assignment) as those have different indentation rules. Indent
677 // other expression, unless the indentation needs to be skipped.
678 if (*I == prec::Conditional ||
679 (!SkipFirstExtraIndent && *I > prec::Assignment))
680 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000681 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000682 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000683 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000684 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000685 }
686
Daniel Jaspercf225b62012-12-24 13:43:52 +0000687 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000688 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000689 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000690 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000691 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000692 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000693 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000694 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000695 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000696 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000697 NewIndent =
698 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000699 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000700 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000701
702 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
703 // This parenthesis was the last token possibly making use of Indent and
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000704 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000705 // better memoization results.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000706 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
707 State.Stack[i].Indent = 0;
708 State.Stack[i].LastSpace = 0;
709 if (!State.Stack[i].ForFakeParenthesis)
710 break;
711 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000712 }
713
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000714 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
715 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000716 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000717 }
718
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000719 // If this '[' opens an ObjC call, determine whether all parameters fit into
720 // one line and put one per line if they don't.
721 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
722 Current.MatchingParen != NULL) {
723 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
724 State.Stack.back().BreakBeforeParameter = true;
725 }
726
Daniel Jaspercf225b62012-12-24 13:43:52 +0000727 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000728 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000729 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000730 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
731 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000732 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000733 --State.ParenLevel;
734 }
735
736 // Remove scopes created by fake parenthesis.
737 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000738 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000739 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000740 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000742
Daniel Jasper27c7f542013-05-13 20:50:15 +0000743 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000744 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000745 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
746 tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000747 }
748
Manuel Klimek8092a942013-02-20 10:15:13 +0000749 State.Column += Current.FormatTok.TokenLength;
750
Daniel Jasper26f7e782013-01-08 14:56:18 +0000751 if (State.NextToken->Children.empty())
752 State.NextToken = NULL;
753 else
754 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000755
Manuel Klimek8092a942013-02-20 10:15:13 +0000756 return breakProtrudingToken(Current, State, DryRun);
757 }
758
759 /// \brief If the current token sticks out over the end of the line, break
760 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000761 ///
762 /// \returns An extra penalty if a token was broken, otherwise 0.
763 ///
764 /// Note that the penalty of the token protruding the allowed line length is
765 /// already handled in \c addNextStateToQueue; the returned penalty will only
766 /// cover the cost of the additional line breaks.
Manuel Klimek8092a942013-02-20 10:15:13 +0000767 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000768 bool DryRun,
769 unsigned UnbreakableTailLength = 0) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000770 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000771 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
772 UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000773 if (Current.is(tok::string_literal)) {
774 // Only break up default narrow strings.
Alexander Kornienko919398b2013-04-17 17:34:05 +0000775 const char *LiteralData = SourceMgr.getCharacterData(
776 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000777 if (!LiteralData || *LiteralData != '"')
778 return 0;
779
Alexander Kornienko919398b2013-04-17 17:34:05 +0000780 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
781 StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000782 } else if (Current.Type == TT_BlockComment) {
783 BreakableBlockComment *BBC =
784 new BreakableBlockComment(SourceMgr, Current, StartColumn);
785 if (!DryRun)
786 BBC->alignLines(Whitespaces);
787 Token.reset(BBC);
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000788 } else if (Current.Type == TT_LineComment &&
789 (Current.Parent == NULL ||
790 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko919398b2013-04-17 17:34:05 +0000791 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000792 } else {
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000793 // If a token that we cannot breaks protrudes, it means we were unable to
794 // break a sequence of tokens due to disallowed breaks between the tokens.
795 // Thus, we recursively search backwards to try to find a breakable token.
796 if (State.Column <= getColumnLimit() ||
797 Current.CanBreakBefore || !Current.Parent)
798 return 0;
799 return breakProtrudingToken(
800 *Current.Parent, State, DryRun,
801 UnbreakableTailLength + Current.FormatTok.TokenLength);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000802 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000803 if (UnbreakableTailLength >= getColumnLimit())
804 return 0;
805 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000806
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000807 bool BreakInserted = false;
808 unsigned Penalty = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000809 unsigned PositionAfterLastLineInToken = 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000810 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
811 ++LineIndex) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000812 unsigned TailOffset = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000813 unsigned RemainingTokenLength =
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000814 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000815 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000816 BreakableToken::Split Split =
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000817 Token->getSplit(LineIndex, TailOffset, RemainingSpace);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000818 if (Split.first == StringRef::npos)
819 break;
820 assert(Split.first != 0);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000821 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko919398b2013-04-17 17:34:05 +0000822 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000823 if (NewRemainingTokenLength >= RemainingTokenLength)
Alexander Kornienko919398b2013-04-17 17:34:05 +0000824 break;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000825 if (!DryRun) {
826 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
827 Whitespaces);
828 }
829 TailOffset += Split.first + Split.second;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000830 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000831 Penalty += Style.PenaltyExcessCharacter;
832 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000833 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000834 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000835 if (!DryRun) {
836 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
837 }
838 }
839
840 if (BreakInserted) {
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000841 State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000842 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
843 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000844 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000845 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000846 return Penalty;
847 }
848
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000849 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000850 // In preprocessor directives reserve two chars for trailing " \"
851 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000852 }
853
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000854 /// \brief An edge in the solution space from \c Previous->State to \c State,
855 /// inserting a newline dependent on the \c NewLine.
856 struct StateNode {
857 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000858 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000859 LineState State;
860 bool NewLine;
861 StateNode *Previous;
862 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000863
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000864 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
865 ///
866 /// In case of equal penalties, we want to prefer states that were inserted
867 /// first. During state generation we make sure that we insert states first
868 /// that break the line as late as possible.
869 typedef std::pair<unsigned, unsigned> OrderedPenalty;
870
871 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
872 /// \c State has the given \c OrderedPenalty.
873 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
874
875 /// \brief The BFS queue type.
876 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
877 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000878
879 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000880 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000881 /// This implements a variant of Dijkstra's algorithm on the graph that spans
882 /// the solution space (\c LineStates are the nodes). The algorithm tries to
883 /// find the shortest path (the one with lowest penalty) from \p InitialState
884 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000885 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000886 std::set<LineState> Seen;
887
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000888 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000889 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000890 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
891 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
892 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000893
894 // While not empty, take first element and follow edges.
895 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000896 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000897 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000898 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000899 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000900 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000901 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000902 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000903
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000904 if (!Seen.insert(Node->State).second)
905 // State already examined with lower penalty.
906 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000907
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000908 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
909 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000910 }
911
912 if (Queue.empty())
913 // We were unable to find a solution, do nothing.
914 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000915 return 0;
916
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000917 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000918 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000919 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
920 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000921
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000922 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000923 return Queue.top().second->State.Column;
924 }
925
926 void reconstructPath(LineState &State, StateNode *Current) {
927 // FIXME: This recursive implementation limits the possible number
928 // of tokens per line if compiled into a binary with small stack space.
929 // To become more independent of stack frame limitations we would need
930 // to also change the TokenAnnotator.
931 if (Current->Previous == NULL)
932 return;
933 reconstructPath(State, Current->Previous);
934 DEBUG({
935 if (Current->NewLine) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000936 llvm::dbgs()
Daniel Jaspera03ab102013-02-13 20:33:44 +0000937 << "Penalty for splitting before "
938 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
939 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000940 }
941 });
942 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000943 }
944
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000945 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000946 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000947 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000948 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000949 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
950 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000951 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000952 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000953 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000954 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000955 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000956 Penalty += PreviousNode->State.NextToken->SplitPenalty;
957
958 StateNode *Node = new (Allocator.Allocate())
959 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000960 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000961 if (Node->State.Column > getColumnLimit()) {
962 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000963 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000964 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000965
966 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
967 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000968 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000969
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000970 /// \brief Returns \c true, if a line break after \p State is allowed.
971 bool canBreak(const LineState &State) {
972 if (!State.NextToken->CanBreakBefore &&
973 !(State.NextToken->is(tok::r_brace) &&
974 State.Stack.back().BreakBeforeClosingBrace))
975 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000976 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000977 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000979 /// \brief Returns \c true, if a line break after \p State is mandatory.
980 bool mustBreak(const LineState &State) {
Daniel Jasper11e13802013-05-08 14:12:04 +0000981 const AnnotatedToken &Current = *State.NextToken;
982 const AnnotatedToken &Previous = *Current.Parent;
983 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000984 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000985 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000986 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000987 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000988 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000989 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
990 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000991 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000992 !Current.isTrailingComment() &&
993 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000994 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000995
996 // If we need to break somewhere inside the LHS of a binary expression, we
997 // should also break after the operator.
998 if (Previous.Type == TT_BinaryOperator &&
999 !Previous.isOneOf(tok::lessless, tok::question) &&
1000 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001001 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001002 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001003
1004 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1005 // out whether it is the first parameter. Clean this up.
1006 if (Current.Type == TT_ObjCSelectorName &&
1007 Current.LongestObjCSelectorName == 0 &&
1008 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001009 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001010 if ((Current.Type == TT_CtorInitializerColon ||
1011 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001012 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001013
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001014 // This prevents breaks like:
1015 // ...
1016 // SomeParameter, OtherParameter).DoSomething(
1017 // ...
1018 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasper11e13802013-05-08 14:12:04 +00001019 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001020 getRemainingLength(State) + State.Column > getColumnLimit() &&
1021 State.ParenLevel < State.StartOfLineLevel)
1022 return true;
Daniel Jasper33f4b902013-05-15 09:35:08 +00001023
1024 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1025 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1026 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001027 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001028 }
1029
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001030 // Returns the total number of columns required for the remaining tokens.
1031 unsigned getRemainingLength(const LineState &State) {
1032 if (State.NextToken && State.NextToken->Parent)
1033 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1034 return 0;
1035 }
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
Alexander Kornienko919398b2013-04-17 17:34:05 +00001096 if (FormatTok.Tok.is(tok::comment)) {
1097 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1098 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1099 }
1100
Manuel Klimekd4397b92013-01-04 23:34:14 +00001101 // In case the token starts with escaped newlines, we want to
1102 // take them into account as whitespace - this pattern is quite frequent
1103 // in macro definitions.
1104 // FIXME: What do we want to do with other escaped spaces, and escaped
1105 // spaces or newlines in the middle of tokens?
1106 // FIXME: Add a more explicit test.
1107 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001108 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001109 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001110 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001111 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001112 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001113 }
1114
1115 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001116 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001117 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001118 FormatTok.Tok.setKind(Info.getTokenID());
1119 }
1120
1121 if (FormatTok.Tok.is(tok::greatergreater)) {
1122 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001123 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001124 GreaterStashed = true;
1125 }
1126
1127 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 Jaspercaf42a32013-05-15 08:14:19 +00001148 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001149 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001150 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +00001151 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001152
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001153 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001154
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001155 tooling::Replacements format() {
1156 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001157 UnwrappedLineParser Parser(Style, Tokens, *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001158 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001159 unsigned PreviousEndOfLineColumn = 0;
1160 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1161 Tokens.getIdentTable().get("in"));
1162 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1163 Annotator.annotate(AnnotatedLines[i]);
1164 }
1165 deriveLocalStyle();
1166 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1167 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1168 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001169
1170 // Adapt level to the next line if this is a comment.
1171 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001172 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001173 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1174 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1175 AnnotatedLines[i].First.Children.empty())
1176 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1177 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001178 NextNoneCommentLine =
1179 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1180 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001181 }
1182
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001183 std::vector<int> IndentForLevel;
1184 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001185 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001186 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001187 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1188 E = AnnotatedLines.end();
1189 I != E; ++I) {
1190 const AnnotatedLine &TheLine = *I;
1191 const FormatToken &FirstTok = TheLine.First.FormatTok;
1192 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001193
1194 // Check whether this line is part of a formatted preprocessor directive.
1195 if (FirstTok.HasUnescapedNewline)
1196 FormatPPDirective = false;
1197 if (!FormatPPDirective && TheLine.InPPDirective &&
1198 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1199 FormatPPDirective = true;
1200
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001201 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001202 while (IndentForLevel.size() <= TheLine.Level)
1203 IndentForLevel.push_back(-1);
1204 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001205 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1206 if (static_cast<int>(Indent) + Offset >= 0)
1207 Indent += Offset;
1208 tryFitMultipleLinesInOne(Indent, I, E);
1209
Daniel Jasperf9955d32013-03-20 12:37:50 +00001210 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001211 if (TheLine.First.is(tok::eof)) {
1212 if (PreviousLineWasTouched) {
1213 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1214 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001215 /*WhitespaceStartColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001216 }
1217 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001218 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001219 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001220 if (FirstTok.WhiteSpaceStart.isValid() &&
1221 // Insert a break even if there is a structural error in case where
1222 // we break apart a line consisting of multiple unwrapped lines.
1223 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001224 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1225 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001226 } else {
1227 Indent = LevelIndent =
1228 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001229 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001230 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001231 TheLine.First, Whitespaces);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001232 PreviousEndOfLineColumn =
1233 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1234 IndentForLevel[TheLine.Level] = LevelIndent;
1235 PreviousLineWasTouched = true;
1236 } else {
1237 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001238 unsigned LevelIndent =
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001239 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001240 // Remove trailing whitespace of the previous line if it was touched.
1241 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1242 formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
1243 TheLine.InPPDirective, PreviousEndOfLineColumn);
1244
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001245 if (static_cast<int>(LevelIndent) - Offset >= 0)
1246 LevelIndent -= Offset;
Daniel Jasper83a90e52013-03-20 14:31:47 +00001247 if (TheLine.First.isNot(tok::comment))
1248 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001249 }
1250 // If we did not reformat this unwrapped line, the column at the end of
1251 // the last token is unchanged - thus, we can calculate the end of the
1252 // last token.
1253 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1254 PreviousEndOfLineColumn =
1255 SourceMgr.getSpellingColumnNumber(LastLoc) +
1256 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1257 PreviousLineWasTouched = false;
Daniel Jasperc363dbb2013-03-22 16:25:51 +00001258 if (TheLine.Last->is(tok::comment))
Daniel Jasper11e13802013-05-08 14:12:04 +00001259 Whitespaces.addUntouchableComment(
1260 SourceMgr.getSpellingColumnNumber(
1261 TheLine.Last->FormatTok.Tok.getLocation()) -
1262 1);
Daniel Jasperaf849762013-04-24 06:33:59 +00001263 else
1264 Whitespaces.alignComments();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001265 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001266 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001267 }
1268 return Whitespaces.generateReplacements();
1269 }
1270
1271private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001272 void deriveLocalStyle() {
1273 unsigned CountBoundToVariable = 0;
1274 unsigned CountBoundToType = 0;
1275 bool HasCpp03IncompatibleFormat = false;
1276 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1277 if (AnnotatedLines[i].First.Children.empty())
1278 continue;
1279 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1280 while (!Tok->Children.empty()) {
1281 if (Tok->Type == TT_PointerOrReference) {
1282 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1283 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1284 if (SpacesBefore && !SpacesAfter)
1285 ++CountBoundToVariable;
1286 else if (!SpacesBefore && SpacesAfter)
1287 ++CountBoundToType;
1288 }
1289
Daniel Jasper29f123b2013-02-08 15:28:42 +00001290 if (Tok->Type == TT_TemplateCloser &&
1291 Tok->Parent->Type == TT_TemplateCloser &&
1292 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001293 HasCpp03IncompatibleFormat = true;
1294 Tok = &Tok->Children[0];
1295 }
1296 }
1297 if (Style.DerivePointerBinding) {
1298 if (CountBoundToType > CountBoundToVariable)
1299 Style.PointerBindsToType = true;
1300 else if (CountBoundToType < CountBoundToVariable)
1301 Style.PointerBindsToType = false;
1302 }
1303 if (Style.Standard == FormatStyle::LS_Auto) {
1304 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1305 : FormatStyle::LS_Cpp03;
1306 }
1307 }
1308
Manuel Klimek547d5db2013-02-08 17:38:27 +00001309 /// \brief Get the indent of \p Level from \p IndentForLevel.
1310 ///
1311 /// \p IndentForLevel must contain the indent for the level \c l
1312 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1313 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001314 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001315 if (IndentForLevel[Level] != -1)
1316 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001317 if (Level == 0)
1318 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001319 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001320 }
1321
1322 /// \brief Get the offset of the line relatively to the level.
1323 ///
1324 /// For example, 'public:' labels in classes are offset by 1 or 2
1325 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001326 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001327 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001328 return Style.AccessModifierOffset;
1329 return 0;
1330 }
1331
Manuel Klimek517e8942013-01-11 17:54:10 +00001332 /// \brief Tries to merge lines into one.
1333 ///
1334 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1335 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001336 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001337 std::vector<AnnotatedLine>::iterator &I,
1338 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001339 // We can never merge stuff if there are trailing line comments.
1340 if (I->Last->Type == TT_LineComment)
1341 return;
1342
Daniel Jaspera4d46212013-02-28 11:05:57 +00001343 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001344 // If we already exceed the column limit, we set 'Limit' to 0. The different
1345 // tryMerge..() functions can then decide whether to still do merging.
1346 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001347
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001348 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001349 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001350
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001351 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001352 tryMergeSimpleBlock(I, E, Limit);
1353 } else if (I->First.is(tok::kw_if)) {
1354 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001355 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1356 I->First.FormatTok.IsFirst)) {
1357 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001358 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001359 }
1360
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001361 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1362 std::vector<AnnotatedLine>::iterator E,
1363 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001364 if (Limit == 0)
1365 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001366 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001367 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1368 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001369 if (I + 2 != E && (I + 2)->InPPDirective &&
1370 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1371 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001372 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001373 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001374 join(Line, *(++I));
1375 }
1376
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001377 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1378 std::vector<AnnotatedLine>::iterator E,
1379 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001380 if (Limit == 0)
1381 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001382 if (!Style.AllowShortIfStatementsOnASingleLine)
1383 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001384 if ((I + 1)->InPPDirective != I->InPPDirective ||
1385 ((I + 1)->InPPDirective &&
1386 (I + 1)->First.FormatTok.HasUnescapedNewline))
1387 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001388 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001389 if (Line.Last->isNot(tok::r_paren))
1390 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001391 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001392 return;
1393 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1394 return;
1395 // Only inline simple if's (no nested if or else).
1396 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1397 return;
1398 join(Line, *(++I));
1399 }
1400
1401 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001402 std::vector<AnnotatedLine>::iterator E,
1403 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001404 // No merging if the brace already is on the next line.
1405 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1406 return;
1407
Manuel Klimek517e8942013-01-11 17:54:10 +00001408 // First, check that the current line allows merging. This is the case if
1409 // we're not in a control flow statement and the last token is an opening
1410 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001411 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001412 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1413 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001414 tok::kw_for, tok::kw_namespace,
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001415 // This gets rid of all ObjC @ keywords and methods.
1416 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001417 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001418
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001419 AnnotatedToken *Tok = &(I + 1)->First;
1420 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001421 !Tok->MustBreakBefore) {
1422 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001423 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001424 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001425 join(Line, *(I + 1));
1426 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001427 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001428 // Check that we still have three lines and they fit into the limit.
1429 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1430 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001431 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001432
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001433 // Second, check that the next line does not contain any braces - if it
1434 // does, readability declines when putting it into a single line.
1435 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1436 return;
1437 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001438 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001439 return;
1440 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1441 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001442
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001443 // Last, check that the third line contains a single closing brace.
1444 Tok = &(I + 2)->First;
1445 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1446 Tok->MustBreakBefore)
1447 return;
1448
1449 join(Line, *(I + 1));
1450 join(Line, *(I + 2));
1451 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001452 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001453 }
1454
1455 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1456 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001457 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1458 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001459 }
1460
Daniel Jasper995e8202013-01-14 13:08:07 +00001461 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001462 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001463 A.Last->Children.push_back(B.First);
1464 while (!A.Last->Children.empty()) {
1465 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001466 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001467 A.Last = &A.Last->Children[0];
1468 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001469 }
1470
Daniel Jasper6f21a982013-03-13 07:49:51 +00001471 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001472 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1473 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1474 Ranges[i].getBegin()) &&
1475 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1476 Range.getBegin()))
1477 return true;
1478 }
1479 return false;
1480 }
1481
1482 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001483 const FormatToken *First = &TheLine.First.FormatTok;
1484 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001485 CharSourceRange LineRange = CharSourceRange::getCharRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001486 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001487 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001488 return touchesRanges(LineRange);
1489 }
1490
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001491 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1492 std::vector<AnnotatedLine>::iterator E) {
1493 for (; I != E; ++I) {
1494 if (I->First.FormatTok.HasUnescapedNewline)
1495 return false;
1496 if (touchesLine(*I))
1497 return true;
1498 }
1499 return false;
1500 }
1501
Daniel Jasperf3023542013-03-07 20:50:00 +00001502 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1503 const FormatToken *First = &TheLine.First.FormatTok;
1504 CharSourceRange LineRange = CharSourceRange::getCharRange(
1505 First->WhiteSpaceStart,
1506 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1507 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001508 }
1509
1510 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001511 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001512 }
1513
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001514 /// \brief Add a new line and the required indent before the first Token
1515 /// of the \c UnwrappedLine if there was no structural parsing error.
1516 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001517 void formatFirstToken(const AnnotatedToken &RootToken,
1518 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimek547d5db2013-02-08 17:38:27 +00001519 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001520 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001521
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001522 unsigned Newlines =
1523 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001524 if (Newlines == 0 && !Tok.IsFirst)
1525 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001526
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001527 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001528 // Insert extra new line before access specifiers.
1529 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1530 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1531 ++Newlines;
1532
Alexander Kornienko052685c2013-03-19 17:41:36 +00001533 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001534 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001535 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001536 PreviousEndOfLineColumn);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001537 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001538 }
1539
Daniel Jasperbac016b2012-12-03 18:12:45 +00001540 FormatStyle Style;
1541 Lexer &Lex;
1542 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001543 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001544 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001545 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001546};
1547
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001548tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1549 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001550 std::vector<CharSourceRange> Ranges) {
1551 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001552 return formatter.format();
1553}
1554
Daniel Jasper46ef8522013-01-10 13:08:12 +00001555LangOptions getFormattingLangOpts() {
1556 LangOptions LangOpts;
1557 LangOpts.CPlusPlus = 1;
1558 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001559 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001560 LangOpts.Bool = 1;
1561 LangOpts.ObjC1 = 1;
1562 LangOpts.ObjC2 = 1;
1563 return LangOpts;
1564}
1565
Daniel Jaspercd162382013-01-07 13:26:07 +00001566} // namespace format
1567} // namespace clang