blob: 3dd0002abb53f1c42c2b3a617d74d125409c9f5a [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod6538332013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43 }
44};
45
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000046template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000047struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48 static void
49 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod6538332013-05-07 15:32:14 +000053 }
54};
55
56template <> struct MappingTraits<clang::format::FormatStyle> {
57 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000058 if (IO.outputting()) {
59 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60 ArrayRef<StringRef> Styles(StylesArray);
61 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62 StringRef StyleName(Styles[i]);
63 if (Style == clang::format::getPredefinedStyle(StyleName)) {
64 IO.mapOptional("# BasedOnStyle", StyleName);
65 break;
66 }
67 }
68 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000069 StringRef BasedOnStyle;
70 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000071 if (!BasedOnStyle.empty())
72 Style = clang::format::getPredefinedStyle(BasedOnStyle);
73 }
74
75 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
76 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
77 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
78 Style.AllowAllParametersOfDeclarationOnNextLine);
79 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
80 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +000081 IO.mapOptional("AllowShortLoopsOnASingleLine",
82 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +000083 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
84 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
85 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
86 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
87 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
88 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
89 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
90 IO.mapOptional("ObjCSpaceBeforeProtocolList",
91 Style.ObjCSpaceBeforeProtocolList);
92 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
93 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
94 Style.PenaltyReturnTypeOnItsOwnLine);
95 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
96 IO.mapOptional("SpacesBeforeTrailingComments",
97 Style.SpacesBeforeTrailingComments);
98 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +000099 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000100 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000101 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000102 }
103};
104}
105}
106
Daniel Jasperf7935112012-12-03 18:12:45 +0000107namespace clang {
108namespace format {
109
Daniel Jasperf7935112012-12-03 18:12:45 +0000110FormatStyle getLLVMStyle() {
111 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000112 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000113 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000114 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000115 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000116 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000117 LLVMStyle.BinPackParameters = true;
118 LLVMStyle.ColumnLimit = 80;
119 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
120 LLVMStyle.DerivePointerBinding = false;
121 LLVMStyle.IndentCaseLabels = false;
122 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000123 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000124 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000125 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000126 LLVMStyle.PointerBindsToType = false;
127 LLVMStyle.SpacesBeforeTrailingComments = 1;
128 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000129 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000130 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000131 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000132 return LLVMStyle;
133}
134
135FormatStyle getGoogleStyle() {
136 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000137 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000138 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000139 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000140 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000141 GoogleStyle.AllowShortLoopsOnASingleLine= true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000142 GoogleStyle.BinPackParameters = true;
143 GoogleStyle.ColumnLimit = 80;
144 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
145 GoogleStyle.DerivePointerBinding = true;
146 GoogleStyle.IndentCaseLabels = true;
147 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000148 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000149 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000150 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000151 GoogleStyle.PointerBindsToType = true;
152 GoogleStyle.SpacesBeforeTrailingComments = 2;
153 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000154 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000155 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000156 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000157 return GoogleStyle;
158}
159
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000160FormatStyle getChromiumStyle() {
161 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000162 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000163 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000164 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000165 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000166 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
167 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000168 return ChromiumStyle;
169}
170
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000171FormatStyle getMozillaStyle() {
172 FormatStyle MozillaStyle = getLLVMStyle();
173 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
174 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
175 MozillaStyle.DerivePointerBinding = true;
176 MozillaStyle.IndentCaseLabels = true;
177 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
178 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
179 MozillaStyle.PointerBindsToType = true;
180 return MozillaStyle;
181}
182
Alexander Kornienkod6538332013-05-07 15:32:14 +0000183FormatStyle getPredefinedStyle(StringRef Name) {
184 if (Name.equals_lower("llvm"))
185 return getLLVMStyle();
186 if (Name.equals_lower("chromium"))
187 return getChromiumStyle();
188 if (Name.equals_lower("mozilla"))
189 return getMozillaStyle();
190 if (Name.equals_lower("google"))
191 return getGoogleStyle();
192
193 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
194 return getGoogleStyle();
195}
196
197llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
198 llvm::yaml::Input Input(Text);
199 Input >> *Style;
200 return Input.error();
201}
202
203std::string configurationAsText(const FormatStyle &Style) {
204 std::string Text;
205 llvm::raw_string_ostream Stream(Text);
206 llvm::yaml::Output Output(Stream);
207 // We use the same mapping method for input and output, so we need a non-const
208 // reference here.
209 FormatStyle NonConstStyle = Style;
210 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000211 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000212}
213
Daniel Jasperacc33662013-02-08 08:22:00 +0000214// Returns the length of everything up to the first possible line break after
215// the ), ], } or > matching \c Tok.
216static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
217 if (Tok.MatchingParen == NULL)
218 return 0;
219 AnnotatedToken *End = Tok.MatchingParen;
220 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
221 End = &End->Children[0];
222 }
223 return End->TotalLength - Tok.TotalLength + 1;
224}
225
Daniel Jasperf7935112012-12-03 18:12:45 +0000226class UnwrappedLineFormatter {
227public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000228 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000229 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000230 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000231 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000232 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000233 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000234 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000235
Manuel Klimek1abf7892013-01-04 23:34:14 +0000236 /// \brief Formats an \c UnwrappedLine.
237 ///
238 /// \returns The column after the last token in the last line of the
239 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000240 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000241 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000242 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000243 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000244 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000245 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000246 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000247 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000248 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000249 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000250 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000251 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000252
253 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000254 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000255
Daniel Jasper4b866272013-02-01 11:00:45 +0000256 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000257 unsigned ColumnLimit = Style.ColumnLimit;
258 if (NextLine && NextLine->InPPDirective &&
259 !NextLine->First.FormatTok.HasUnescapedNewline)
260 ColumnLimit = getColumnLimit();
261 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000262 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000263 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000264 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000265 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000266 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000267
Daniel Jasperacc33662013-02-08 08:22:00 +0000268 // If the ObjC method declaration does not fit on a line, we should format
269 // it with one arg per line.
270 if (Line.Type == LT_ObjCMethodDecl)
271 State.Stack.back().BreakBeforeParameter = true;
272
Daniel Jasper4b866272013-02-01 11:00:45 +0000273 // Find best solution in solution space.
274 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 }
276
277private:
Manuel Klimek24998102013-01-16 14:55:28 +0000278 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
279 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000280 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000281 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000282 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000283 }
284
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000286 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000287 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000288 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
289 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000290 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000291 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
292 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000293 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000294
Daniel Jasperf7935112012-12-03 18:12:45 +0000295 /// \brief The position to which a specific parenthesis level needs to be
296 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000297 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000298
Daniel Jaspere9de2602012-12-06 09:56:08 +0000299 /// \brief The position of the last space on each level.
300 ///
301 /// Used e.g. to break like:
302 /// functionCall(Parameter, otherCall(
303 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000304 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000305
Daniel Jaspere9de2602012-12-06 09:56:08 +0000306 /// \brief The position the first "<<" operator encountered on each level.
307 ///
308 /// Used to align "<<" operators. 0 if no such operator has been encountered
309 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000310 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000311
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000312 /// \brief Whether a newline needs to be inserted before the block's closing
313 /// brace.
314 ///
315 /// We only want to insert a newline before the closing brace if there also
316 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000317 bool BreakBeforeClosingBrace;
318
Daniel Jasperca6623b2013-01-28 12:45:14 +0000319 /// \brief The column of a \c ? in a conditional expression;
320 unsigned QuestionColumn;
321
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000322 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
323 /// lines, in this context.
324 bool AvoidBinPacking;
325
326 /// \brief Break after the next comma (or all the commas in this context if
327 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000328 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000329
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000330 /// \brief Line breaking in this context would break a formatting rule.
331 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000332
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000333 /// \brief The position of the colon in an ObjC method declaration/call.
334 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000335
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000336 /// \brief The start of the most recent function in a builder-type call.
337 unsigned StartOfFunctionCall;
338
Daniel Jasperc238c872013-04-02 14:33:13 +0000339 /// \brief If a nested name specifier was broken over multiple lines, this
340 /// contains the start column of the second line. Otherwise 0.
341 unsigned NestedNameSpecifierContinuation;
342
343 /// \brief If a call expression was broken over multiple lines, this
344 /// contains the start column of the second line. Otherwise 0.
345 unsigned CallContinuation;
346
Daniel Jaspera628c982013-04-03 13:36:17 +0000347 /// \brief The column of the first variable name in a variable declaration.
348 ///
349 /// Used to align further variables if necessary.
350 unsigned VariablePos;
351
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000352 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
353 ///
354 /// Does not need to be considered for memoization / the comparison function
355 /// as otherwise identical states will have the same fake/non-fake
356 /// \c ParenStates.
357 bool ForFakeParenthesis;
358
Daniel Jasper337816e2013-01-11 10:22:12 +0000359 bool operator<(const ParenState &Other) const {
360 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000361 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 if (LastSpace != Other.LastSpace)
363 return LastSpace < Other.LastSpace;
364 if (FirstLessLess != Other.FirstLessLess)
365 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000366 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
367 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000368 if (QuestionColumn != Other.QuestionColumn)
369 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000370 if (AvoidBinPacking != Other.AvoidBinPacking)
371 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000372 if (BreakBeforeParameter != Other.BreakBeforeParameter)
373 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000374 if (NoLineBreak != Other.NoLineBreak)
375 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000376 if (ColonPos != Other.ColonPos)
377 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000378 if (StartOfFunctionCall != Other.StartOfFunctionCall)
379 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000380 if (CallContinuation != Other.CallContinuation)
381 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000382 if (VariablePos != Other.VariablePos)
383 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000384 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000385 }
386 };
387
388 /// \brief The current state when indenting a unwrapped line.
389 ///
390 /// As the indenting tries different combinations this is copied by value.
391 struct LineState {
392 /// \brief The number of used columns in the current line.
393 unsigned Column;
394
395 /// \brief The token that needs to be next formatted.
396 const AnnotatedToken *NextToken;
397
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000398 /// \brief \c true if this line contains a continued for-loop section.
399 bool LineContainsContinuedForLoopSection;
400
Daniel Jasper400adc62013-02-08 15:28:42 +0000401 /// \brief The level of nesting inside (), [], <> and {}.
402 unsigned ParenLevel;
403
Daniel Jasper40c36c52013-02-18 11:05:07 +0000404 /// \brief The \c ParenLevel at the start of this line.
405 unsigned StartOfLineLevel;
406
Manuel Klimek02f640a2013-02-20 15:25:48 +0000407 /// \brief The start column of the string literal, if we're in a string
408 /// literal sequence, 0 otherwise.
409 unsigned StartOfStringLiteral;
410
Daniel Jasper337816e2013-01-11 10:22:12 +0000411 /// \brief A stack keeping track of properties applying to parenthesis
412 /// levels.
413 std::vector<ParenState> Stack;
414
415 /// \brief Comparison operator to be able to used \c LineState in \c map.
416 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000417 if (NextToken != Other.NextToken)
418 return NextToken < Other.NextToken;
419 if (Column != Other.Column)
420 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000421 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000422 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000423 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000424 if (ParenLevel != Other.ParenLevel)
425 return ParenLevel < Other.ParenLevel;
426 if (StartOfLineLevel != Other.StartOfLineLevel)
427 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000428 if (StartOfStringLiteral != Other.StartOfStringLiteral)
429 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000430 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000431 }
432 };
433
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000434 /// \brief Appends the next token to \p State and updates information
435 /// necessary for indentation.
436 ///
437 /// Puts the token on the current line if \p Newline is \c true and adds a
438 /// line break and necessary indentation otherwise.
439 ///
440 /// If \p DryRun is \c false, also creates and stores the required
441 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000442 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000443 const AnnotatedToken &Current = *State.NextToken;
444 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000445
Daniel Jasper291f9362013-03-20 15:58:10 +0000446 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000447 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
448 State.NextToken->FormatTok.TokenLength;
449 if (State.NextToken->Children.empty())
450 State.NextToken = NULL;
451 else
452 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000453 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000454 }
455
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000456 // If we are continuing an expression, we want to indent an extra 4 spaces.
457 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000458 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000460 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000461 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000462 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000463 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000464 State.StartOfStringLiteral != 0) {
465 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000466 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000467 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000468 State.Stack.back().FirstLessLess != 0) {
469 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000470 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000471 if (State.Stack.back().CallContinuation == 0) {
472 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000473 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000474 } else {
475 State.Column = State.Stack.back().CallContinuation;
476 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000477 } else if (Current.Type == TT_ConditionalExpr) {
478 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000479 } else if (Previous.is(tok::comma) &&
480 State.Stack.back().VariablePos != 0) {
481 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000482 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000483 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
484 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000485 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000486 } else if (Current.Type == TT_ObjCSelectorName) {
487 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
488 State.Column =
489 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
490 } else {
491 State.Column = State.Stack.back().Indent;
492 State.Stack.back().ColonPos =
493 State.Column + Current.FormatTok.TokenLength;
494 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000495 } else if (Current.Type == TT_StartOfName ||
496 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000497 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000498 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000500 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000501 // Ensure that we fall back to indenting 4 spaces instead of just
502 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000503 if (State.Column == FirstIndent)
504 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000505 }
506
Daniel Jasper54a86022013-02-15 11:07:25 +0000507 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000508 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000509 if ((Previous.isOneOf(tok::comma, tok::semi) &&
510 !State.Stack.back().AvoidBinPacking) ||
511 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000512 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000513 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
514 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000515
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000516 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000517 unsigned NewLines = 1;
518 if (Current.Type == TT_LineComment)
519 NewLines =
520 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
521 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000522 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000523 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000524 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000525 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000526 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000527 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000528 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000529
Daniel Jasper400adc62013-02-08 15:28:42 +0000530 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000531 if (Current.isOneOf(tok::arrow, tok::period))
532 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000533 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000534
535 // Any break on this level means that the parent level has been broken
536 // and we need to avoid bin packing there.
537 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
538 State.Stack[i].BreakBeforeParameter = true;
539 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000540 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
541 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000542 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000543 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000544 State.Stack.back().BreakBeforeParameter = true;
545
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000546 // If we break after {, we should also break before the corresponding }.
547 if (Previous.is(tok::l_brace))
548 State.Stack.back().BreakBeforeClosingBrace = true;
549
550 if (State.Stack.back().AvoidBinPacking) {
551 // If we are breaking after '(', '{', '<', this is not bin packing
552 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000553 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
554 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000555 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
556 Line.MustBeDeclaration))
557 State.Stack.back().BreakBeforeParameter = true;
558 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000560 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000561 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
562 State.Stack.back().VariablePos == 0) {
563 State.Stack.back().VariablePos = State.Column;
564 // Move over * and & if they are bound to the variable name.
565 const AnnotatedToken *Tok = &Previous;
566 while (Tok &&
567 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
568 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
569 if (Tok->SpacesRequiredBefore != 0)
570 break;
571 Tok = Tok->Parent;
572 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000573 if (Previous.PartOfMultiVariableDeclStmt)
574 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
575 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000576
Daniel Jaspereef30492013-02-11 12:36:37 +0000577 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000578
Daniel Jasperf7935112012-12-03 18:12:45 +0000579 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000580 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000581
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000582 if (Current.Type == TT_ObjCSelectorName &&
583 State.Stack.back().ColonPos == 0) {
584 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000585 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000586 State.Stack.back().ColonPos =
587 State.Stack.back().Indent + Current.LongestObjCSelectorName;
588 else
589 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000590 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000591 }
592
Daniel Jasperc04baae2013-04-10 09:49:49 +0000593 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000594 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000595 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000596 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
597 State.Stack.back().AvoidBinPacking)
598 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000599
Daniel Jaspere9de2602012-12-06 09:56:08 +0000600 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000601 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000602 // Treat the condition inside an if as if it was a second function
603 // parameter, i.e. let nested calls have an indent of 4.
604 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000605 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000606 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000607 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000608 Previous.Type == TT_ConditionalExpr ||
609 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000610 getPrecedence(Previous) != prec::Assignment)
611 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000612 else if (Previous.Type == TT_InheritanceColon)
613 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000614 else if (Previous.opensScope() && !Current.FakeLParens.empty())
615 // If this function has multiple parameters or a binary expression
616 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000617 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000618 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000619
Manuel Klimek1998ea22013-02-20 10:15:13 +0000620 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000621 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000622
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000623 /// \brief Mark the next token as consumed in \p State and modify its stacks
624 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000625 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000626 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000627 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000628
Daniel Jaspereead02b2013-02-14 08:42:54 +0000629 if (Current.Type == TT_InheritanceColon)
630 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000631 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
632 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000633 if (Current.is(tok::question))
634 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000635 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000636 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
637 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000638 Current.LastInChainOfCalls ? 0 : State.Column +
639 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000640 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000641 // Indent 2 from the column, so:
642 // SomeClass::SomeClass()
643 // : First(...), ...
644 // Next(...)
645 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000646 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000647 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
648 State.Stack.back().AvoidBinPacking = true;
649 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000650 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000651
Daniel Jasper6bee6822013-04-08 20:33:42 +0000652 // If return returns a binary expression, align after it.
653 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
654 State.Stack.back().LastSpace = State.Column + 7;
655
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000656 // In ObjC method declaration we align on the ":" of parameters, but we need
657 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000658 if (Current.Type == TT_ObjCMethodSpecifier)
659 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000660
Daniel Jasper400adc62013-02-08 15:28:42 +0000661 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000662 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
663 // Don't add extra indentation for the first fake parenthesis after
664 // 'return', assignements or opening <({[. The indentation for these cases
665 // is special cased.
666 bool SkipFirstExtraIndent =
667 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000668 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000669 getPrecedence(*Previous) == prec::Assignment));
670 for (SmallVector<prec::Level, 4>::const_reverse_iterator
671 I = Current.FakeLParens.rbegin(),
672 E = Current.FakeLParens.rend();
673 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000674 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000675 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000676 NewParenState.Indent =
677 std::max(std::max(State.Column, NewParenState.Indent),
678 State.Stack.back().LastSpace);
679
680 // Always indent conditional expressions. Never indent expression where
681 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
682 // prec::Assignment) as those have different indentation rules. Indent
683 // other expression, unless the indentation needs to be skipped.
684 if (*I == prec::Conditional ||
685 (!SkipFirstExtraIndent && *I > prec::Assignment))
686 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000687 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000688 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000689 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000690 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000691 }
692
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000693 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000694 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000695 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000696 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000697 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000698 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000699 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000700 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000701 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000702 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000703 NewIndent =
704 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000705 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000706 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000707
708 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
709 // This parenthesis was the last token possibly making use of Indent and
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000710 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000711 // better memoization results.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000712 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
713 State.Stack[i].Indent = 0;
714 State.Stack[i].LastSpace = 0;
715 if (!State.Stack[i].ForFakeParenthesis)
716 break;
717 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000718 }
719
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000720 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
721 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000722 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000723 }
724
Daniel Jasperacc33662013-02-08 08:22:00 +0000725 // If this '[' opens an ObjC call, determine whether all parameters fit into
726 // one line and put one per line if they don't.
727 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
728 Current.MatchingParen != NULL) {
729 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
730 State.Stack.back().BreakBeforeParameter = true;
731 }
732
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000733 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000734 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000735 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000736 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
737 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000738 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000739 --State.ParenLevel;
740 }
741
742 // Remove scopes created by fake parenthesis.
743 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000744 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000745 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000746 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000747 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000748
Daniel Jasper47a04442013-05-13 20:50:15 +0000749 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000750 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000751 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
752 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000753 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000754 }
755
Manuel Klimek1998ea22013-02-20 10:15:13 +0000756 State.Column += Current.FormatTok.TokenLength;
757
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 if (State.NextToken->Children.empty())
759 State.NextToken = NULL;
760 else
761 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000762
Manuel Klimek1998ea22013-02-20 10:15:13 +0000763 return breakProtrudingToken(Current, State, DryRun);
764 }
765
766 /// \brief If the current token sticks out over the end of the line, break
767 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000768 ///
769 /// \returns An extra penalty if a token was broken, otherwise 0.
770 ///
771 /// Note that the penalty of the token protruding the allowed line length is
772 /// already handled in \c addNextStateToQueue; the returned penalty will only
773 /// cover the cost of the additional line breaks.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000774 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000775 bool DryRun,
776 unsigned UnbreakableTailLength = 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000777 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000778 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
779 UnbreakableTailLength;
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000780 if (Current.is(tok::string_literal) &&
781 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000782 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000783 const char *LiteralData = SourceMgr.getCharacterData(
784 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000785 if (!LiteralData || *LiteralData != '"')
786 return 0;
787
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000788 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
789 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000790 } else if (Current.Type == TT_BlockComment) {
791 BreakableBlockComment *BBC =
792 new BreakableBlockComment(SourceMgr, Current, StartColumn);
793 if (!DryRun)
794 BBC->alignLines(Whitespaces);
795 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000796 } else if (Current.Type == TT_LineComment &&
797 (Current.Parent == NULL ||
798 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000799 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000800 } else {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000801 // If a token that we cannot breaks protrudes, it means we were unable to
802 // break a sequence of tokens due to disallowed breaks between the tokens.
803 // Thus, we recursively search backwards to try to find a breakable token.
804 if (State.Column <= getColumnLimit() ||
805 Current.CanBreakBefore || !Current.Parent)
806 return 0;
807 return breakProtrudingToken(
808 *Current.Parent, State, DryRun,
809 UnbreakableTailLength + Current.FormatTok.TokenLength);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000810 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000811 if (UnbreakableTailLength >= getColumnLimit())
812 return 0;
813 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000814
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000815 bool BreakInserted = false;
816 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000817 unsigned PositionAfterLastLineInToken = 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000818 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
819 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000820 unsigned TailOffset = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000821 unsigned RemainingTokenLength =
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000822 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000823 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000824 BreakableToken::Split Split =
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000825 Token->getSplit(LineIndex, TailOffset, RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000826 if (Split.first == StringRef::npos)
827 break;
828 assert(Split.first != 0);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000829 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000830 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000831 if (NewRemainingTokenLength >= RemainingTokenLength)
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000832 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000833 if (!DryRun) {
834 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
835 Whitespaces);
836 }
837 TailOffset += Split.first + Split.second;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000838 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000839 Penalty += Style.PenaltyExcessCharacter;
840 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000841 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000842 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000843 if (!DryRun) {
844 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
845 }
846 }
847
848 if (BreakInserted) {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000849 State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000850 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
851 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000852 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000853 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000854 return Penalty;
855 }
856
Daniel Jasper2df93312013-01-09 10:16:05 +0000857 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000858 // In preprocessor directives reserve two chars for trailing " \"
859 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000860 }
861
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000862 /// \brief An edge in the solution space from \c Previous->State to \c State,
863 /// inserting a newline dependent on the \c NewLine.
864 struct StateNode {
865 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000866 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000867 LineState State;
868 bool NewLine;
869 StateNode *Previous;
870 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000871
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000872 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
873 ///
874 /// In case of equal penalties, we want to prefer states that were inserted
875 /// first. During state generation we make sure that we insert states first
876 /// that break the line as late as possible.
877 typedef std::pair<unsigned, unsigned> OrderedPenalty;
878
879 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
880 /// \c State has the given \c OrderedPenalty.
881 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
882
883 /// \brief The BFS queue type.
884 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
885 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000886
887 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000888 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000889 /// This implements a variant of Dijkstra's algorithm on the graph that spans
890 /// the solution space (\c LineStates are the nodes). The algorithm tries to
891 /// find the shortest path (the one with lowest penalty) from \p InitialState
892 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000893 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000894 std::set<LineState> Seen;
895
Daniel Jasper4b866272013-02-01 11:00:45 +0000896 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000897 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000898 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
899 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
900 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000901
902 // While not empty, take first element and follow edges.
903 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000904 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000905 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000907 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000908 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000909 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000910 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000911
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000912 if (!Seen.insert(Node->State).second)
913 // State already examined with lower penalty.
914 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000915
Manuel Klimekaf491072013-02-13 10:54:19 +0000916 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
917 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000918 }
919
920 if (Queue.empty())
921 // We were unable to find a solution, do nothing.
922 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000923 return 0;
924
Daniel Jasper4b866272013-02-01 11:00:45 +0000925 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000926 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000927 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
928 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000929
Daniel Jasper4b866272013-02-01 11:00:45 +0000930 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000931 return Queue.top().second->State.Column;
932 }
933
934 void reconstructPath(LineState &State, StateNode *Current) {
935 // FIXME: This recursive implementation limits the possible number
936 // of tokens per line if compiled into a binary with small stack space.
937 // To become more independent of stack frame limitations we would need
938 // to also change the TokenAnnotator.
939 if (Current->Previous == NULL)
940 return;
941 reconstructPath(State, Current->Previous);
942 DEBUG({
943 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000944 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000945 << "Penalty for splitting before "
946 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
947 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000948 }
949 });
950 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000951 }
952
Manuel Klimekaf491072013-02-13 10:54:19 +0000953 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000954 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000955 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000956 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000957 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
958 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000959 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000960 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000961 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000962 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000963 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000964 Penalty += PreviousNode->State.NextToken->SplitPenalty;
965
966 StateNode *Node = new (Allocator.Allocate())
967 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000968 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000969 if (Node->State.Column > getColumnLimit()) {
970 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000971 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000972 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000973
974 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
975 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000976 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000977
Daniel Jasper4b866272013-02-01 11:00:45 +0000978 /// \brief Returns \c true, if a line break after \p State is allowed.
979 bool canBreak(const LineState &State) {
Daniel Jasper473c62c2013-05-17 09:35:01 +0000980 const AnnotatedToken &Current = *State.NextToken;
981 const AnnotatedToken &Previous = *Current.Parent;
982 if (!Current.CanBreakBefore &&
983 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000984 State.Stack.back().BreakBeforeClosingBrace))
985 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +0000986 // The opening "{" of a braced list has to be on the same line as the first
987 // element if it is nested in another braced init list or function call.
988 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
989 Previous.Parent &&
990 Previous.Parent->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
991 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000992 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000993 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000994
Daniel Jasper4b866272013-02-01 11:00:45 +0000995 /// \brief Returns \c true, if a line break after \p State is mandatory.
996 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000997 const AnnotatedToken &Current = *State.NextToken;
998 const AnnotatedToken &Previous = *Current.Parent;
999 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001000 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001001 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +00001002 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001003 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001004 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001005 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1006 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001007 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001008 !Current.isTrailingComment() &&
1009 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001010 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001011
1012 // If we need to break somewhere inside the LHS of a binary expression, we
1013 // should also break after the operator.
1014 if (Previous.Type == TT_BinaryOperator &&
1015 !Previous.isOneOf(tok::lessless, tok::question) &&
1016 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001017 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001018 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001019
1020 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1021 // out whether it is the first parameter. Clean this up.
1022 if (Current.Type == TT_ObjCSelectorName &&
1023 Current.LongestObjCSelectorName == 0 &&
1024 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001025 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001026 if ((Current.Type == TT_CtorInitializerColon ||
1027 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001028 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001029
Daniel Jasper9b334242013-03-15 14:57:30 +00001030 // This prevents breaks like:
1031 // ...
1032 // SomeParameter, OtherParameter).DoSomething(
1033 // ...
1034 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +00001035 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +00001036 getRemainingLength(State) + State.Column > getColumnLimit() &&
1037 State.ParenLevel < State.StartOfLineLevel)
1038 return true;
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001039
1040 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1041 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1042 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001043 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 }
1045
Daniel Jasper9b334242013-03-15 14:57:30 +00001046 // Returns the total number of columns required for the remaining tokens.
1047 unsigned getRemainingLength(const LineState &State) {
1048 if (State.NextToken && State.NextToken->Parent)
1049 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1050 return 0;
1051 }
1052
Daniel Jasperf7935112012-12-03 18:12:45 +00001053 FormatStyle Style;
1054 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001055 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001056 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001057 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001058 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001059
1060 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1061 QueueType Queue;
1062 // Increasing count of \c StateNode items we have created. This is used
1063 // to create a deterministic order independent of the container.
1064 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001065};
1066
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001067class LexerBasedFormatTokenSource : public FormatTokenSource {
1068public:
1069 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001070 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001071 IdentTable(Lex.getLangOpts()) {
1072 Lex.SetKeepWhitespaceMode(true);
1073 }
1074
1075 virtual FormatToken getNextToken() {
1076 if (GreaterStashed) {
1077 FormatTok.NewlinesBefore = 0;
1078 FormatTok.WhiteSpaceStart =
1079 FormatTok.Tok.getLocation().getLocWithOffset(1);
1080 FormatTok.WhiteSpaceLength = 0;
1081 GreaterStashed = false;
1082 return FormatTok;
1083 }
1084
1085 FormatTok = FormatToken();
1086 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001087 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001088 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001089 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1090 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001091
1092 // Consume and record whitespace until we find a significant token.
1093 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001094 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001095 if (Newlines > 0)
1096 FormatTok.LastNewlineOffset =
1097 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001098 unsigned EscapedNewlines = Text.count("\\\n");
1099 FormatTok.NewlinesBefore += Newlines;
1100 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001101 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1102
1103 if (FormatTok.Tok.is(tok::eof))
1104 return FormatTok;
1105 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001106 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001107 }
Manuel Klimekef920692013-01-07 07:56:50 +00001108
1109 // Now FormatTok is the next non-whitespace token.
1110 FormatTok.TokenLength = Text.size();
1111
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001112 if (FormatTok.Tok.is(tok::comment)) {
1113 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1114 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1115 }
1116
Manuel Klimek1abf7892013-01-04 23:34:14 +00001117 // In case the token starts with escaped newlines, we want to
1118 // take them into account as whitespace - this pattern is quite frequent
1119 // in macro definitions.
1120 // FIXME: What do we want to do with other escaped spaces, and escaped
1121 // spaces or newlines in the middle of tokens?
1122 // FIXME: Add a more explicit test.
1123 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001124 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001125 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001126 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001127 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001128 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001129 }
1130
1131 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001132 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001133 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001134 FormatTok.Tok.setKind(Info.getTokenID());
1135 }
1136
1137 if (FormatTok.Tok.is(tok::greatergreater)) {
1138 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001139 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001140 GreaterStashed = true;
1141 }
1142
1143 return FormatTok;
1144 }
1145
Nico Weber29f9dea2013-02-11 15:32:15 +00001146 IdentifierTable &getIdentTable() { return IdentTable; }
1147
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001148private:
1149 FormatToken FormatTok;
1150 bool GreaterStashed;
1151 Lexer &Lex;
1152 SourceManager &SourceMgr;
1153 IdentifierTable IdentTable;
1154
1155 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001156 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001157 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1158 Tok.getLength());
1159 }
1160};
1161
Daniel Jasperf7935112012-12-03 18:12:45 +00001162class Formatter : public UnwrappedLineConsumer {
1163public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001164 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001165 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001166 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001167 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001168
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001169 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001170
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001171 tooling::Replacements format() {
1172 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001173 UnwrappedLineParser Parser(Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001174 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001175 unsigned PreviousEndOfLineColumn = 0;
1176 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1177 Tokens.getIdentTable().get("in"));
1178 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1179 Annotator.annotate(AnnotatedLines[i]);
1180 }
1181 deriveLocalStyle();
1182 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1183 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1184 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001185
1186 // Adapt level to the next line if this is a comment.
1187 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001188 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001189 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1190 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1191 AnnotatedLines[i].First.Children.empty())
1192 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1193 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001194 NextNoneCommentLine =
1195 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1196 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001197 }
1198
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001199 std::vector<int> IndentForLevel;
1200 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001201 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001202 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001203 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1204 E = AnnotatedLines.end();
1205 I != E; ++I) {
1206 const AnnotatedLine &TheLine = *I;
1207 const FormatToken &FirstTok = TheLine.First.FormatTok;
1208 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001209
1210 // Check whether this line is part of a formatted preprocessor directive.
1211 if (FirstTok.HasUnescapedNewline)
1212 FormatPPDirective = false;
1213 if (!FormatPPDirective && TheLine.InPPDirective &&
1214 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1215 FormatPPDirective = true;
1216
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001217 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001218 while (IndentForLevel.size() <= TheLine.Level)
1219 IndentForLevel.push_back(-1);
1220 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001221 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1222 if (static_cast<int>(Indent) + Offset >= 0)
1223 Indent += Offset;
1224 tryFitMultipleLinesInOne(Indent, I, E);
1225
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001226 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001227 if (TheLine.First.is(tok::eof)) {
1228 if (PreviousLineWasTouched) {
1229 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1230 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001231 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001232 }
1233 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001234 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001235 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001236 if (FirstTok.WhiteSpaceStart.isValid() &&
1237 // Insert a break even if there is a structural error in case where
1238 // we break apart a line consisting of multiple unwrapped lines.
1239 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001240 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1241 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001242 } else {
1243 Indent = LevelIndent =
1244 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001245 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001246 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001247 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001248 PreviousEndOfLineColumn =
1249 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1250 IndentForLevel[TheLine.Level] = LevelIndent;
1251 PreviousLineWasTouched = true;
1252 } else {
1253 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001254 unsigned LevelIndent =
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001255 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001256 // Remove trailing whitespace of the previous line if it was touched.
1257 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1258 formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
1259 TheLine.InPPDirective, PreviousEndOfLineColumn);
1260
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001261 if (static_cast<int>(LevelIndent) - Offset >= 0)
1262 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001263 if (TheLine.First.isNot(tok::comment))
1264 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001265 }
1266 // If we did not reformat this unwrapped line, the column at the end of
1267 // the last token is unchanged - thus, we can calculate the end of the
1268 // last token.
1269 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1270 PreviousEndOfLineColumn =
1271 SourceMgr.getSpellingColumnNumber(LastLoc) +
1272 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1273 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001274 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001275 Whitespaces.addUntouchableComment(
1276 SourceMgr.getSpellingColumnNumber(
1277 TheLine.Last->FormatTok.Tok.getLocation()) -
1278 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001279 else
1280 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001281 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001282 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001283 }
1284 return Whitespaces.generateReplacements();
1285 }
1286
1287private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001288 void deriveLocalStyle() {
1289 unsigned CountBoundToVariable = 0;
1290 unsigned CountBoundToType = 0;
1291 bool HasCpp03IncompatibleFormat = false;
1292 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1293 if (AnnotatedLines[i].First.Children.empty())
1294 continue;
1295 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1296 while (!Tok->Children.empty()) {
1297 if (Tok->Type == TT_PointerOrReference) {
1298 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1299 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1300 if (SpacesBefore && !SpacesAfter)
1301 ++CountBoundToVariable;
1302 else if (!SpacesBefore && SpacesAfter)
1303 ++CountBoundToType;
1304 }
1305
Daniel Jasper400adc62013-02-08 15:28:42 +00001306 if (Tok->Type == TT_TemplateCloser &&
1307 Tok->Parent->Type == TT_TemplateCloser &&
1308 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001309 HasCpp03IncompatibleFormat = true;
1310 Tok = &Tok->Children[0];
1311 }
1312 }
1313 if (Style.DerivePointerBinding) {
1314 if (CountBoundToType > CountBoundToVariable)
1315 Style.PointerBindsToType = true;
1316 else if (CountBoundToType < CountBoundToVariable)
1317 Style.PointerBindsToType = false;
1318 }
1319 if (Style.Standard == FormatStyle::LS_Auto) {
1320 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1321 : FormatStyle::LS_Cpp03;
1322 }
1323 }
1324
Manuel Klimekb95f5452013-02-08 17:38:27 +00001325 /// \brief Get the indent of \p Level from \p IndentForLevel.
1326 ///
1327 /// \p IndentForLevel must contain the indent for the level \c l
1328 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1329 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001330 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001331 if (IndentForLevel[Level] != -1)
1332 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001333 if (Level == 0)
1334 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001335 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001336 }
1337
1338 /// \brief Get the offset of the line relatively to the level.
1339 ///
1340 /// For example, 'public:' labels in classes are offset by 1 or 2
1341 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001342 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001343 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001344 return Style.AccessModifierOffset;
1345 return 0;
1346 }
1347
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001348 /// \brief Tries to merge lines into one.
1349 ///
1350 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1351 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001352 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001353 std::vector<AnnotatedLine>::iterator &I,
1354 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001355 // We can never merge stuff if there are trailing line comments.
1356 if (I->Last->Type == TT_LineComment)
1357 return;
1358
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001359 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001360 // If we already exceed the column limit, we set 'Limit' to 0. The different
1361 // tryMerge..() functions can then decide whether to still do merging.
1362 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001363
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001364 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001365 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001366
Daniel Jasperabca58c2013-05-15 14:09:55 +00001367 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001368 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001369 } else if (Style.AllowShortIfStatementsOnASingleLine &&
1370 I->First.is(tok::kw_if)) {
1371 tryMergeSimpleControlStatement(I, E, Limit);
1372 } else if (Style.AllowShortLoopsOnASingleLine &&
1373 I->First.isOneOf(tok::kw_for, tok::kw_while)) {
1374 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001375 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1376 I->First.FormatTok.IsFirst)) {
1377 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001378 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001379 }
1380
Daniel Jasper39825ea2013-01-14 15:40:57 +00001381 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1382 std::vector<AnnotatedLine>::iterator E,
1383 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001384 if (Limit == 0)
1385 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001386 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001387 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1388 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001389 if (I + 2 != E && (I + 2)->InPPDirective &&
1390 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1391 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001392 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001393 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001394 join(Line, *(++I));
1395 }
1396
Daniel Jasper3a685df2013-05-16 12:12:21 +00001397 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1398 std::vector<AnnotatedLine>::iterator E,
1399 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001400 if (Limit == 0)
1401 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001402 if ((I + 1)->InPPDirective != I->InPPDirective ||
1403 ((I + 1)->InPPDirective &&
1404 (I + 1)->First.FormatTok.HasUnescapedNewline))
1405 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001406 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001407 if (Line.Last->isNot(tok::r_paren))
1408 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001409 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001410 return;
Daniel Jasper3a685df2013-05-16 12:12:21 +00001411 if ((I + 1)->First.isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1412 tok::kw_while) ||
1413 (I + 1)->First.Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001414 return;
1415 // Only inline simple if's (no nested if or else).
Daniel Jasper3a685df2013-05-16 12:12:21 +00001416 if (I + 2 != E && Line.First.is(tok::kw_if) &&
1417 (I + 2)->First.is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001418 return;
1419 join(Line, *(++I));
1420 }
1421
1422 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001423 std::vector<AnnotatedLine>::iterator E,
1424 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001425 // No merging if the brace already is on the next line.
1426 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1427 return;
1428
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001429 // First, check that the current line allows merging. This is the case if
1430 // we're not in a control flow statement and the last token is an opening
1431 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001432 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001433 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1434 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasperabca58c2013-05-15 14:09:55 +00001435 tok::kw_for, tok::kw_namespace,
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001436 // This gets rid of all ObjC @ keywords and methods.
1437 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001438 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001439
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001440 AnnotatedToken *Tok = &(I + 1)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001441 if (Tok->getNextNoneComment() == NULL && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001442 !Tok->MustBreakBefore) {
1443 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001444 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001445 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001446 join(Line, *(I + 1));
1447 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001448 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001449 // Check that we still have three lines and they fit into the limit.
1450 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1451 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001452 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001453
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001454 // Second, check that the next line does not contain any braces - if it
1455 // does, readability declines when putting it into a single line.
1456 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1457 return;
1458 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001459 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001460 return;
1461 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1462 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001463
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001464 // Last, check that the third line contains a single closing brace.
1465 Tok = &(I + 2)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001466 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001467 Tok->MustBreakBefore)
1468 return;
1469
1470 join(Line, *(I + 1));
1471 join(Line, *(I + 2));
1472 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001473 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001474 }
1475
1476 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1477 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001478 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1479 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001480 }
1481
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001482 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001483 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001484 A.Last->Children.push_back(B.First);
1485 while (!A.Last->Children.empty()) {
1486 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001487 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001488 A.Last = &A.Last->Children[0];
1489 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001490 }
1491
Daniel Jasper97b89482013-03-13 07:49:51 +00001492 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001493 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1494 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1495 Ranges[i].getBegin()) &&
1496 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1497 Range.getBegin()))
1498 return true;
1499 }
1500 return false;
1501 }
1502
1503 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001504 const FormatToken *First = &TheLine.First.FormatTok;
1505 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001506 CharSourceRange LineRange = CharSourceRange::getCharRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001507 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
Daniel Jaspercdd06622013-05-14 10:31:09 +00001508 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001509 return touchesRanges(LineRange);
1510 }
1511
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001512 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1513 std::vector<AnnotatedLine>::iterator E) {
1514 for (; I != E; ++I) {
1515 if (I->First.FormatTok.HasUnescapedNewline)
1516 return false;
1517 if (touchesLine(*I))
1518 return true;
1519 }
1520 return false;
1521 }
1522
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001523 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1524 const FormatToken *First = &TheLine.First.FormatTok;
1525 CharSourceRange LineRange = CharSourceRange::getCharRange(
1526 First->WhiteSpaceStart,
1527 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1528 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001529 }
1530
1531 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001532 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 }
1534
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001535 /// \brief Add a new line and the required indent before the first Token
1536 /// of the \c UnwrappedLine if there was no structural parsing error.
1537 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001538 void formatFirstToken(const AnnotatedToken &RootToken,
1539 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001540 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001541 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001542
Daniel Jasperbbc84152013-01-29 11:27:30 +00001543 unsigned Newlines =
1544 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001545 if (Newlines == 0 && !Tok.IsFirst)
1546 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001547
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001548 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001549 // Insert extra new line before access specifiers.
1550 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1551 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1552 ++Newlines;
1553
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001554 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001555 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001556 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001557 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001558 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001559 }
1560
Daniel Jasperf7935112012-12-03 18:12:45 +00001561 FormatStyle Style;
1562 Lexer &Lex;
1563 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001564 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001565 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001566 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001567};
1568
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001569tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1570 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001571 std::vector<CharSourceRange> Ranges) {
1572 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001573 return formatter.format();
1574}
1575
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001576tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1577 std::vector<tooling::Range> Ranges,
1578 StringRef FileName) {
1579 FileManager Files((FileSystemOptions()));
1580 DiagnosticsEngine Diagnostics(
1581 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1582 new DiagnosticOptions);
1583 SourceManager SourceMgr(Diagnostics, Files);
1584 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1585 const clang::FileEntry *Entry =
1586 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1587 SourceMgr.overrideFileContents(Entry, Buf);
1588 FileID ID =
1589 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1590 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1591 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1592 std::vector<CharSourceRange> CharRanges;
1593 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1594 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1595 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1596 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1597 }
1598 return reformat(Style, Lex, SourceMgr, CharRanges);
1599}
1600
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001601LangOptions getFormattingLangOpts() {
1602 LangOptions LangOpts;
1603 LangOpts.CPlusPlus = 1;
1604 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001605 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001606 LangOpts.Bool = 1;
1607 LangOpts.ObjC1 = 1;
1608 LangOpts.ObjC2 = 1;
1609 return LangOpts;
1610}
1611
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001612} // namespace format
1613} // namespace clang