blob: 4c7c405e81e8a6bcfbbadee76d7281999a9ca6bf [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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Alexander Kornienkod6538332013-05-07 15:32:14 +000035namespace llvm {
36namespace yaml {
37template <>
38struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
39 static void enumeration(IO &io,
40 clang::format::FormatStyle::LanguageStandard &value) {
41 io.enumCase(value, "C++03", clang::format::FormatStyle::LS_Cpp03);
42 io.enumCase(value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 io.enumCase(value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
47template <> struct MappingTraits<clang::format::FormatStyle> {
48 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
49 if (!IO.outputting()) {
50 StringRef BasedOnStyle;
51 IO.mapOptional("BasedOnStyle", BasedOnStyle);
52
53 if (!BasedOnStyle.empty())
54 Style = clang::format::getPredefinedStyle(BasedOnStyle);
55 }
56
57 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
58 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
59 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
60 Style.AllowAllParametersOfDeclarationOnNextLine);
61 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
62 Style.AllowShortIfStatementsOnASingleLine);
63 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
64 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
65 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
66 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
67 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
68 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
69 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
70 IO.mapOptional("ObjCSpaceBeforeProtocolList",
71 Style.ObjCSpaceBeforeProtocolList);
72 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
73 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
74 Style.PenaltyReturnTypeOnItsOwnLine);
75 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
76 IO.mapOptional("SpacesBeforeTrailingComments",
77 Style.SpacesBeforeTrailingComments);
78 IO.mapOptional("Standard", Style.Standard);
79 }
80};
81}
82}
83
Daniel Jasperf7935112012-12-03 18:12:45 +000084namespace clang {
85namespace format {
86
Daniel Jasperf7935112012-12-03 18:12:45 +000087FormatStyle getLLVMStyle() {
88 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +000089 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +000090 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000091 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000092 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +000093 LLVMStyle.BinPackParameters = true;
94 LLVMStyle.ColumnLimit = 80;
95 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
96 LLVMStyle.DerivePointerBinding = false;
97 LLVMStyle.IndentCaseLabels = false;
98 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +000099 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000100 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000101 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000102 LLVMStyle.PointerBindsToType = false;
103 LLVMStyle.SpacesBeforeTrailingComments = 1;
104 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 return LLVMStyle;
106}
107
108FormatStyle getGoogleStyle() {
109 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000110 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000111 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000112 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000113 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000114 GoogleStyle.BinPackParameters = true;
115 GoogleStyle.ColumnLimit = 80;
116 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
117 GoogleStyle.DerivePointerBinding = true;
118 GoogleStyle.IndentCaseLabels = true;
119 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000120 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000121 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000122 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000123 GoogleStyle.PointerBindsToType = true;
124 GoogleStyle.SpacesBeforeTrailingComments = 2;
125 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasperf7935112012-12-03 18:12:45 +0000126 return GoogleStyle;
127}
128
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000129FormatStyle getChromiumStyle() {
130 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000131 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000132 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000133 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000134 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
135 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000136 return ChromiumStyle;
137}
138
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000139FormatStyle getMozillaStyle() {
140 FormatStyle MozillaStyle = getLLVMStyle();
141 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
142 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
143 MozillaStyle.DerivePointerBinding = true;
144 MozillaStyle.IndentCaseLabels = true;
145 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
146 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
147 MozillaStyle.PointerBindsToType = true;
148 return MozillaStyle;
149}
150
Alexander Kornienkod6538332013-05-07 15:32:14 +0000151FormatStyle getPredefinedStyle(StringRef Name) {
152 if (Name.equals_lower("llvm"))
153 return getLLVMStyle();
154 if (Name.equals_lower("chromium"))
155 return getChromiumStyle();
156 if (Name.equals_lower("mozilla"))
157 return getMozillaStyle();
158 if (Name.equals_lower("google"))
159 return getGoogleStyle();
160
161 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
162 return getGoogleStyle();
163}
164
165llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
166 llvm::yaml::Input Input(Text);
167 Input >> *Style;
168 return Input.error();
169}
170
171std::string configurationAsText(const FormatStyle &Style) {
172 std::string Text;
173 llvm::raw_string_ostream Stream(Text);
174 llvm::yaml::Output Output(Stream);
175 // We use the same mapping method for input and output, so we need a non-const
176 // reference here.
177 FormatStyle NonConstStyle = Style;
178 Output << NonConstStyle;
179 return Text;
180}
181
Daniel Jasperacc33662013-02-08 08:22:00 +0000182// Returns the length of everything up to the first possible line break after
183// the ), ], } or > matching \c Tok.
184static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
185 if (Tok.MatchingParen == NULL)
186 return 0;
187 AnnotatedToken *End = Tok.MatchingParen;
188 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
189 End = &End->Children[0];
190 }
191 return End->TotalLength - Tok.TotalLength + 1;
192}
193
Daniel Jasperf7935112012-12-03 18:12:45 +0000194class UnwrappedLineFormatter {
195public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000196 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000197 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000198 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000199 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000200 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000201 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000202 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000203
Manuel Klimek1abf7892013-01-04 23:34:14 +0000204 /// \brief Formats an \c UnwrappedLine.
205 ///
206 /// \returns The column after the last token in the last line of the
207 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000208 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000209 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000210 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000211 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000212 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000213 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000214 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000215 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000216 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000217 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000218 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000219 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000220
221 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000222 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000223
Daniel Jasper4b866272013-02-01 11:00:45 +0000224 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000225 unsigned ColumnLimit = Style.ColumnLimit;
226 if (NextLine && NextLine->InPPDirective &&
227 !NextLine->First.FormatTok.HasUnescapedNewline)
228 ColumnLimit = getColumnLimit();
229 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000230 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000231 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000232 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000233 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000234 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000235
Daniel Jasperacc33662013-02-08 08:22:00 +0000236 // If the ObjC method declaration does not fit on a line, we should format
237 // it with one arg per line.
238 if (Line.Type == LT_ObjCMethodDecl)
239 State.Stack.back().BreakBeforeParameter = true;
240
Daniel Jasper4b866272013-02-01 11:00:45 +0000241 // Find best solution in solution space.
242 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000243 }
244
245private:
Manuel Klimek24998102013-01-16 14:55:28 +0000246 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
247 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000248 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
249 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000250 llvm::errs();
251 }
252
Daniel Jasper337816e2013-01-11 10:22:12 +0000253 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000254 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000255 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000256 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
257 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000258 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000259 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
260 NestedNameSpecifierContinuation(0), CallContinuation(0),
261 VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000262
Daniel Jasperf7935112012-12-03 18:12:45 +0000263 /// \brief The position to which a specific parenthesis level needs to be
264 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000265 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000266
Daniel Jaspere9de2602012-12-06 09:56:08 +0000267 /// \brief The position of the last space on each level.
268 ///
269 /// Used e.g. to break like:
270 /// functionCall(Parameter, otherCall(
271 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000272 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000273
Daniel Jaspere9de2602012-12-06 09:56:08 +0000274 /// \brief The position the first "<<" operator encountered on each level.
275 ///
276 /// Used to align "<<" operators. 0 if no such operator has been encountered
277 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000278 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000279
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000280 /// \brief Whether a newline needs to be inserted before the block's closing
281 /// brace.
282 ///
283 /// We only want to insert a newline before the closing brace if there also
284 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 bool BreakBeforeClosingBrace;
286
Daniel Jasperca6623b2013-01-28 12:45:14 +0000287 /// \brief The column of a \c ? in a conditional expression;
288 unsigned QuestionColumn;
289
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000290 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
291 /// lines, in this context.
292 bool AvoidBinPacking;
293
294 /// \brief Break after the next comma (or all the commas in this context if
295 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000296 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000297
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000298 /// \brief Line breaking in this context would break a formatting rule.
299 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000300
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000301 /// \brief The position of the colon in an ObjC method declaration/call.
302 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000303
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000304 /// \brief The start of the most recent function in a builder-type call.
305 unsigned StartOfFunctionCall;
306
Daniel Jasperc238c872013-04-02 14:33:13 +0000307 /// \brief If a nested name specifier was broken over multiple lines, this
308 /// contains the start column of the second line. Otherwise 0.
309 unsigned NestedNameSpecifierContinuation;
310
311 /// \brief If a call expression was broken over multiple lines, this
312 /// contains the start column of the second line. Otherwise 0.
313 unsigned CallContinuation;
314
Daniel Jaspera628c982013-04-03 13:36:17 +0000315 /// \brief The column of the first variable name in a variable declaration.
316 ///
317 /// Used to align further variables if necessary.
318 unsigned VariablePos;
319
Daniel Jasper337816e2013-01-11 10:22:12 +0000320 bool operator<(const ParenState &Other) const {
321 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000322 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000323 if (LastSpace != Other.LastSpace)
324 return LastSpace < Other.LastSpace;
325 if (FirstLessLess != Other.FirstLessLess)
326 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000327 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
328 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000329 if (QuestionColumn != Other.QuestionColumn)
330 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000331 if (AvoidBinPacking != Other.AvoidBinPacking)
332 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000333 if (BreakBeforeParameter != Other.BreakBeforeParameter)
334 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000335 if (NoLineBreak != Other.NoLineBreak)
336 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000337 if (ColonPos != Other.ColonPos)
338 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000339 if (StartOfFunctionCall != Other.StartOfFunctionCall)
340 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000341 if (NestedNameSpecifierContinuation !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000342 Other.NestedNameSpecifierContinuation)
Daniel Jasperc238c872013-04-02 14:33:13 +0000343 return NestedNameSpecifierContinuation <
344 Other.NestedNameSpecifierContinuation;
345 if (CallContinuation != Other.CallContinuation)
346 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000347 if (VariablePos != Other.VariablePos)
348 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000349 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000350 }
351 };
352
353 /// \brief The current state when indenting a unwrapped line.
354 ///
355 /// As the indenting tries different combinations this is copied by value.
356 struct LineState {
357 /// \brief The number of used columns in the current line.
358 unsigned Column;
359
360 /// \brief The token that needs to be next formatted.
361 const AnnotatedToken *NextToken;
362
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000363 /// \brief \c true if this line contains a continued for-loop section.
364 bool LineContainsContinuedForLoopSection;
365
Daniel Jasper400adc62013-02-08 15:28:42 +0000366 /// \brief The level of nesting inside (), [], <> and {}.
367 unsigned ParenLevel;
368
Daniel Jasper40c36c52013-02-18 11:05:07 +0000369 /// \brief The \c ParenLevel at the start of this line.
370 unsigned StartOfLineLevel;
371
Manuel Klimek02f640a2013-02-20 15:25:48 +0000372 /// \brief The start column of the string literal, if we're in a string
373 /// literal sequence, 0 otherwise.
374 unsigned StartOfStringLiteral;
375
Daniel Jasper337816e2013-01-11 10:22:12 +0000376 /// \brief A stack keeping track of properties applying to parenthesis
377 /// levels.
378 std::vector<ParenState> Stack;
379
380 /// \brief Comparison operator to be able to used \c LineState in \c map.
381 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000382 if (NextToken != Other.NextToken)
383 return NextToken < Other.NextToken;
384 if (Column != Other.Column)
385 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000386 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000387 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000388 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000389 if (ParenLevel != Other.ParenLevel)
390 return ParenLevel < Other.ParenLevel;
391 if (StartOfLineLevel != Other.StartOfLineLevel)
392 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000393 if (StartOfStringLiteral != Other.StartOfStringLiteral)
394 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000395 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000396 }
397 };
398
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000399 /// \brief Appends the next token to \p State and updates information
400 /// necessary for indentation.
401 ///
402 /// Puts the token on the current line if \p Newline is \c true and adds a
403 /// line break and necessary indentation otherwise.
404 ///
405 /// If \p DryRun is \c false, also creates and stores the required
406 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000407 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000408 const AnnotatedToken &Current = *State.NextToken;
409 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000410
Daniel Jasper291f9362013-03-20 15:58:10 +0000411 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000412 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
413 State.NextToken->FormatTok.TokenLength;
414 if (State.NextToken->Children.empty())
415 State.NextToken = NULL;
416 else
417 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000418 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000419 }
420
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000421 // If we are continuing an expression, we want to indent an extra 4 spaces.
422 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000423 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000424 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000425 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000426 if (Current.is(tok::r_brace)) {
427 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000428 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000429 State.StartOfStringLiteral != 0) {
430 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000431 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000432 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000433 State.Stack.back().FirstLessLess != 0) {
434 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000435 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000436 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
437 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000438 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000439 } else {
440 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
441 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000442 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000443 if (State.Stack.back().CallContinuation == 0) {
444 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000445 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000446 } else {
447 State.Column = State.Stack.back().CallContinuation;
448 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000449 } else if (Current.Type == TT_ConditionalExpr) {
450 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000451 } else if (Previous.is(tok::comma) &&
452 State.Stack.back().VariablePos != 0) {
453 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000454 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000455 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
456 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000457 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000458 } else if (Current.Type == TT_ObjCSelectorName) {
459 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
460 State.Column =
461 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
462 } else {
463 State.Column = State.Stack.back().Indent;
464 State.Stack.back().ColonPos =
465 State.Column + Current.FormatTok.TokenLength;
466 }
Daniel Jasper6bee6822013-04-08 20:33:42 +0000467 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000468 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000469 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000470 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000471 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000472 // Ensure that we fall back to indenting 4 spaces instead of just
473 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000474 if (State.Column == FirstIndent)
475 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000476 }
477
Daniel Jasper54a86022013-02-15 11:07:25 +0000478 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000479 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000480 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000481 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000482 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000483
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000484 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000485 unsigned NewLines = 1;
486 if (Current.Type == TT_LineComment)
487 NewLines =
488 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
489 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000490 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000491 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000492 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000493 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000494 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000495 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000496 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000497
Daniel Jasper400adc62013-02-08 15:28:42 +0000498 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000499 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000500
501 // Any break on this level means that the parent level has been broken
502 // and we need to avoid bin packing there.
503 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
504 State.Stack[i].BreakBeforeParameter = true;
505 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000506 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
507 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
508 !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000509 State.Stack.back().BreakBeforeParameter = true;
510
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000511 // If we break after {, we should also break before the corresponding }.
512 if (Previous.is(tok::l_brace))
513 State.Stack.back().BreakBeforeClosingBrace = true;
514
515 if (State.Stack.back().AvoidBinPacking) {
516 // If we are breaking after '(', '{', '<', this is not bin packing
517 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000518 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000519 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
520 Line.MustBeDeclaration))
521 State.Stack.back().BreakBeforeParameter = true;
522 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000524 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000525 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
526 State.Stack.back().VariablePos == 0) {
527 State.Stack.back().VariablePos = State.Column;
528 // Move over * and & if they are bound to the variable name.
529 const AnnotatedToken *Tok = &Previous;
530 while (Tok &&
531 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
532 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
533 if (Tok->SpacesRequiredBefore != 0)
534 break;
535 Tok = Tok->Parent;
536 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000537 if (Previous.PartOfMultiVariableDeclStmt)
538 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
539 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000540
Daniel Jaspereef30492013-02-11 12:36:37 +0000541 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000542
Daniel Jasperf7935112012-12-03 18:12:45 +0000543 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000544 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000545
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000546 if (Current.Type == TT_ObjCSelectorName &&
547 State.Stack.back().ColonPos == 0) {
548 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000549 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000550 State.Stack.back().ColonPos =
551 State.Stack.back().Indent + Current.LongestObjCSelectorName;
552 else
553 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000554 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000555 }
556
Daniel Jasperc04baae2013-04-10 09:49:49 +0000557 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000558 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000559 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000560 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
561 State.Stack.back().AvoidBinPacking)
562 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000563
Daniel Jaspere9de2602012-12-06 09:56:08 +0000564 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000565 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000566 // Treat the condition inside an if as if it was a second function
567 // parameter, i.e. let nested calls have an indent of 4.
568 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000569 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000570 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000571 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000572 Previous.Type == TT_ConditionalExpr ||
573 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000574 getPrecedence(Previous) != prec::Assignment)
575 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000576 else if (Previous.Type == TT_InheritanceColon)
577 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000578 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000579 // If this function has multiple parameters, indent nested calls from
580 // the start of the first parameter.
581 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000583
Manuel Klimek1998ea22013-02-20 10:15:13 +0000584 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000585 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000586
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000587 /// \brief Mark the next token as consumed in \p State and modify its stacks
588 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000589 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000591 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000592
Daniel Jaspereead02b2013-02-14 08:42:54 +0000593 if (Current.Type == TT_InheritanceColon)
594 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000595 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
596 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000597 if (Current.is(tok::question))
598 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000599 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000600 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
601 State.Stack.back().StartOfFunctionCall =
602 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000603 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000604 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000605 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
606 State.Stack.back().AvoidBinPacking = true;
607 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000608 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000609
Daniel Jasper6bee6822013-04-08 20:33:42 +0000610 // If return returns a binary expression, align after it.
611 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
612 State.Stack.back().LastSpace = State.Column + 7;
613
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000614 // In ObjC method declaration we align on the ":" of parameters, but we need
615 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000616 if (Current.Type == TT_ObjCMethodSpecifier)
617 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000618
Daniel Jasper400adc62013-02-08 15:28:42 +0000619 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000620 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
621 // Don't add extra indentation for the first fake parenthesis after
622 // 'return', assignements or opening <({[. The indentation for these cases
623 // is special cased.
624 bool SkipFirstExtraIndent =
625 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000626 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000627 getPrecedence(*Previous) == prec::Assignment));
628 for (SmallVector<prec::Level, 4>::const_reverse_iterator
629 I = Current.FakeLParens.rbegin(),
630 E = Current.FakeLParens.rend();
631 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000632 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000633 NewParenState.Indent =
634 std::max(std::max(State.Column, NewParenState.Indent),
635 State.Stack.back().LastSpace);
636
637 // Always indent conditional expressions. Never indent expression where
638 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
639 // prec::Assignment) as those have different indentation rules. Indent
640 // other expression, unless the indentation needs to be skipped.
641 if (*I == prec::Conditional ||
642 (!SkipFirstExtraIndent && *I > prec::Assignment))
643 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000644 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000645 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000646 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000647 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000648 }
649
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000650 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000651 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000652 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000653 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000654 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000655 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000656 NewIndent = 2 + State.Stack.back().LastSpace;
657 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000658 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000659 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
660 State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000661 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000662 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000663 State.Stack.push_back(
664 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000665 State.Stack.back().NoLineBreak));
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000666
667 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
668 // This parenthesis was the last token possibly making use of Indent and
669 // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
670 // better memoization results.
671 State.Stack[State.Stack.size() - 2].Indent = 0;
672 State.Stack[State.Stack.size() - 2].LastSpace = 0;
673 }
674
Daniel Jasper400adc62013-02-08 15:28:42 +0000675 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000676 }
677
Daniel Jasperacc33662013-02-08 08:22:00 +0000678 // If this '[' opens an ObjC call, determine whether all parameters fit into
679 // one line and put one per line if they don't.
680 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
681 Current.MatchingParen != NULL) {
682 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
683 State.Stack.back().BreakBeforeParameter = true;
684 }
685
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000686 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000687 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000688 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000689 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
690 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000691 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000692 --State.ParenLevel;
693 }
694
695 // Remove scopes created by fake parenthesis.
696 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000697 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000698 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000699 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000701
Manuel Klimek0c915712013-02-20 15:32:58 +0000702 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000703 State.StartOfStringLiteral = State.Column;
704 } else if (Current.isNot(tok::comment)) {
705 State.StartOfStringLiteral = 0;
706 }
707
Manuel Klimek1998ea22013-02-20 10:15:13 +0000708 State.Column += Current.FormatTok.TokenLength;
709
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000710 if (State.NextToken->Children.empty())
711 State.NextToken = NULL;
712 else
713 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000714
Manuel Klimek1998ea22013-02-20 10:15:13 +0000715 return breakProtrudingToken(Current, State, DryRun);
716 }
717
718 /// \brief If the current token sticks out over the end of the line, break
719 /// it if possible.
720 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
721 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000722 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000723 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000724 if (Current.is(tok::string_literal)) {
725 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000726 const char *LiteralData = SourceMgr.getCharacterData(
727 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000728 if (!LiteralData || *LiteralData != '"')
729 return 0;
730
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000731 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
732 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000733 } else if (Current.Type == TT_BlockComment) {
734 BreakableBlockComment *BBC =
735 new BreakableBlockComment(SourceMgr, Current, StartColumn);
736 if (!DryRun)
737 BBC->alignLines(Whitespaces);
738 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000739 } else if (Current.Type == TT_LineComment &&
740 (Current.Parent == NULL ||
741 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000742 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000743 } else {
744 return 0;
745 }
746
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000747 bool BreakInserted = false;
748 unsigned Penalty = 0;
749 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
750 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000751 unsigned TailOffset = 0;
752 unsigned RemainingLength =
753 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
754 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000755 BreakableToken::Split Split =
756 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
757 if (Split.first == StringRef::npos)
758 break;
759 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000760 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
761 LineIndex, TailOffset + Split.first + Split.second);
762 if (NewRemainingLength >= RemainingLength)
763 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000764 if (!DryRun) {
765 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
766 Whitespaces);
767 }
768 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000769 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000770 Penalty += Style.PenaltyExcessCharacter;
771 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000772 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000773 State.Column = RemainingLength;
774 if (!DryRun) {
775 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
776 }
777 }
778
779 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000780 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
781 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000782 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000783 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000784 return Penalty;
785 }
786
Daniel Jasper2df93312013-01-09 10:16:05 +0000787 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000788 // In preprocessor directives reserve two chars for trailing " \"
789 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000790 }
791
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000792 /// \brief An edge in the solution space from \c Previous->State to \c State,
793 /// inserting a newline dependent on the \c NewLine.
794 struct StateNode {
795 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000796 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 LineState State;
798 bool NewLine;
799 StateNode *Previous;
800 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000801
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000802 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
803 ///
804 /// In case of equal penalties, we want to prefer states that were inserted
805 /// first. During state generation we make sure that we insert states first
806 /// that break the line as late as possible.
807 typedef std::pair<unsigned, unsigned> OrderedPenalty;
808
809 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
810 /// \c State has the given \c OrderedPenalty.
811 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
812
813 /// \brief The BFS queue type.
814 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
815 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000816
817 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000819 /// This implements a variant of Dijkstra's algorithm on the graph that spans
820 /// the solution space (\c LineStates are the nodes). The algorithm tries to
821 /// find the shortest path (the one with lowest penalty) from \p InitialState
822 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000823 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000824 std::set<LineState> Seen;
825
Daniel Jasper4b866272013-02-01 11:00:45 +0000826 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000827 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000828 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
829 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
830 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000831
832 // While not empty, take first element and follow edges.
833 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000834 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000835 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000836 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000837 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000838 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000839 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000840 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000841
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000842 if (!Seen.insert(Node->State).second)
843 // State already examined with lower penalty.
844 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000845
Manuel Klimekaf491072013-02-13 10:54:19 +0000846 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
847 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000848 }
849
850 if (Queue.empty())
851 // We were unable to find a solution, do nothing.
852 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000853 return 0;
854
Daniel Jasper4b866272013-02-01 11:00:45 +0000855 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000856 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000857 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000858
Daniel Jasper4b866272013-02-01 11:00:45 +0000859 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000860 return Queue.top().second->State.Column;
861 }
862
863 void reconstructPath(LineState &State, StateNode *Current) {
864 // FIXME: This recursive implementation limits the possible number
865 // of tokens per line if compiled into a binary with small stack space.
866 // To become more independent of stack frame limitations we would need
867 // to also change the TokenAnnotator.
868 if (Current->Previous == NULL)
869 return;
870 reconstructPath(State, Current->Previous);
871 DEBUG({
872 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000873 llvm::errs()
874 << "Penalty for splitting before "
875 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
876 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000877 }
878 });
879 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000880 }
881
Manuel Klimekaf491072013-02-13 10:54:19 +0000882 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000883 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000884 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000885 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000886 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
887 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000888 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000889 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000890 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000891 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000892 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000893 Penalty += PreviousNode->State.NextToken->SplitPenalty;
894
895 StateNode *Node = new (Allocator.Allocate())
896 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000897 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000898 if (Node->State.Column > getColumnLimit()) {
899 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000900 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000901 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000902
903 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
904 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000905 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000906
Daniel Jasper4b866272013-02-01 11:00:45 +0000907 /// \brief Returns \c true, if a line break after \p State is allowed.
908 bool canBreak(const LineState &State) {
909 if (!State.NextToken->CanBreakBefore &&
910 !(State.NextToken->is(tok::r_brace) &&
911 State.Stack.back().BreakBeforeClosingBrace))
912 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000913 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000914 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000915
Daniel Jasper4b866272013-02-01 11:00:45 +0000916 /// \brief Returns \c true, if a line break after \p State is mandatory.
917 bool mustBreak(const LineState &State) {
918 if (State.NextToken->MustBreakBefore)
919 return true;
920 if (State.NextToken->is(tok::r_brace) &&
921 State.Stack.back().BreakBeforeClosingBrace)
922 return true;
923 if (State.NextToken->Parent->is(tok::semi) &&
924 State.LineContainsContinuedForLoopSection)
925 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000926 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000927 State.NextToken->is(tok::question) ||
928 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000929 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000930 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000931 State.NextToken->isNot(tok::r_paren) &&
932 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000933 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000934 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
935 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000936 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000937 State.NextToken->LongestObjCSelectorName == 0 &&
938 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000939 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000940 if ((State.NextToken->Type == TT_CtorInitializerColon ||
941 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000942 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000943 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000944 if (State.NextToken->Type == TT_InlineASMColon)
945 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000946 // This prevents breaks like:
947 // ...
948 // SomeParameter, OtherParameter).DoSomething(
949 // ...
950 // As they hide "DoSomething" and generally bad for readability.
951 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
952 getRemainingLength(State) + State.Column > getColumnLimit() &&
953 State.ParenLevel < State.StartOfLineLevel)
954 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000955 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 }
957
Daniel Jasper9b334242013-03-15 14:57:30 +0000958 // Returns the total number of columns required for the remaining tokens.
959 unsigned getRemainingLength(const LineState &State) {
960 if (State.NextToken && State.NextToken->Parent)
961 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
962 return 0;
963 }
964
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 FormatStyle Style;
966 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000967 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000968 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000969 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000970 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000971
972 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
973 QueueType Queue;
974 // Increasing count of \c StateNode items we have created. This is used
975 // to create a deterministic order independent of the container.
976 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000977};
978
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000979class LexerBasedFormatTokenSource : public FormatTokenSource {
980public:
981 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000982 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000983 IdentTable(Lex.getLangOpts()) {
984 Lex.SetKeepWhitespaceMode(true);
985 }
986
987 virtual FormatToken getNextToken() {
988 if (GreaterStashed) {
989 FormatTok.NewlinesBefore = 0;
990 FormatTok.WhiteSpaceStart =
991 FormatTok.Tok.getLocation().getLocWithOffset(1);
992 FormatTok.WhiteSpaceLength = 0;
993 GreaterStashed = false;
994 return FormatTok;
995 }
996
997 FormatTok = FormatToken();
998 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000999 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001000 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001001 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1002 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001003
1004 // Consume and record whitespace until we find a significant token.
1005 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001006 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001007 if (Newlines > 0)
1008 FormatTok.LastNewlineOffset =
1009 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001010 unsigned EscapedNewlines = Text.count("\\\n");
1011 FormatTok.NewlinesBefore += Newlines;
1012 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001013 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1014
1015 if (FormatTok.Tok.is(tok::eof))
1016 return FormatTok;
1017 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001018 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001019 }
Manuel Klimekef920692013-01-07 07:56:50 +00001020
1021 // Now FormatTok is the next non-whitespace token.
1022 FormatTok.TokenLength = Text.size();
1023
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001024 if (FormatTok.Tok.is(tok::comment)) {
1025 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1026 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1027 }
1028
Manuel Klimek1abf7892013-01-04 23:34:14 +00001029 // In case the token starts with escaped newlines, we want to
1030 // take them into account as whitespace - this pattern is quite frequent
1031 // in macro definitions.
1032 // FIXME: What do we want to do with other escaped spaces, and escaped
1033 // spaces or newlines in the middle of tokens?
1034 // FIXME: Add a more explicit test.
1035 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001036 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001037 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001038 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001039 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001040 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001041 }
1042
1043 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001044 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001045 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001046 FormatTok.Tok.setKind(Info.getTokenID());
1047 }
1048
1049 if (FormatTok.Tok.is(tok::greatergreater)) {
1050 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001051 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001052 GreaterStashed = true;
1053 }
1054
1055 return FormatTok;
1056 }
1057
Nico Weber29f9dea2013-02-11 15:32:15 +00001058 IdentifierTable &getIdentTable() { return IdentTable; }
1059
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001060private:
1061 FormatToken FormatTok;
1062 bool GreaterStashed;
1063 Lexer &Lex;
1064 SourceManager &SourceMgr;
1065 IdentifierTable IdentTable;
1066
1067 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001068 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001069 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1070 Tok.getLength());
1071 }
1072};
1073
Daniel Jasperf7935112012-12-03 18:12:45 +00001074class Formatter : public UnwrappedLineConsumer {
1075public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001076 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1077 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001078 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001079 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001080 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001081
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001082 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001083
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001084 tooling::Replacements format() {
1085 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1086 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001087 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001088 unsigned PreviousEndOfLineColumn = 0;
1089 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1090 Tokens.getIdentTable().get("in"));
1091 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1092 Annotator.annotate(AnnotatedLines[i]);
1093 }
1094 deriveLocalStyle();
1095 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1096 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1097 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001098
1099 // Adapt level to the next line if this is a comment.
1100 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001101 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001102 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1103 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1104 AnnotatedLines[i].First.Children.empty())
1105 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1106 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001107 NextNoneCommentLine =
1108 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1109 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001110 }
1111
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001112 std::vector<int> IndentForLevel;
1113 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001114 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001115 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1116 E = AnnotatedLines.end();
1117 I != E; ++I) {
1118 const AnnotatedLine &TheLine = *I;
1119 const FormatToken &FirstTok = TheLine.First.FormatTok;
1120 int Offset = getIndentOffset(TheLine.First);
1121 while (IndentForLevel.size() <= TheLine.Level)
1122 IndentForLevel.push_back(-1);
1123 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001124 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001125 if (TheLine.First.is(tok::eof)) {
1126 if (PreviousLineWasTouched) {
1127 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1128 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001129 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001130 }
1131 } else if (TheLine.Type != LT_Invalid &&
1132 (WasMoved || touchesLine(TheLine))) {
1133 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1134 unsigned Indent = LevelIndent;
1135 if (static_cast<int>(Indent) + Offset >= 0)
1136 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001137 if (FirstTok.WhiteSpaceStart.isValid() &&
1138 // Insert a break even if there is a structural error in case where
1139 // we break apart a line consisting of multiple unwrapped lines.
1140 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001141 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1142 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001143 } else {
1144 Indent = LevelIndent =
1145 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001146 }
1147 tryFitMultipleLinesInOne(Indent, I, E);
1148 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001149 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001150 PreviousEndOfLineColumn =
1151 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1152 IndentForLevel[TheLine.Level] = LevelIndent;
1153 PreviousLineWasTouched = true;
1154 } else {
1155 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1156 unsigned Indent =
1157 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1158 unsigned LevelIndent = Indent;
1159 if (static_cast<int>(LevelIndent) - Offset >= 0)
1160 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001161 if (TheLine.First.isNot(tok::comment))
1162 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001163
1164 // Remove trailing whitespace of the previous line if it was touched.
1165 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001166 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1167 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001168 }
1169 // If we did not reformat this unwrapped line, the column at the end of
1170 // the last token is unchanged - thus, we can calculate the end of the
1171 // last token.
1172 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1173 PreviousEndOfLineColumn =
1174 SourceMgr.getSpellingColumnNumber(LastLoc) +
1175 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1176 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001177 if (TheLine.Last->is(tok::comment))
1178 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1179 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001180 else
1181 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001182 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001183 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001184 }
1185 return Whitespaces.generateReplacements();
1186 }
1187
1188private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001189 void deriveLocalStyle() {
1190 unsigned CountBoundToVariable = 0;
1191 unsigned CountBoundToType = 0;
1192 bool HasCpp03IncompatibleFormat = false;
1193 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1194 if (AnnotatedLines[i].First.Children.empty())
1195 continue;
1196 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1197 while (!Tok->Children.empty()) {
1198 if (Tok->Type == TT_PointerOrReference) {
1199 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1200 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1201 if (SpacesBefore && !SpacesAfter)
1202 ++CountBoundToVariable;
1203 else if (!SpacesBefore && SpacesAfter)
1204 ++CountBoundToType;
1205 }
1206
Daniel Jasper400adc62013-02-08 15:28:42 +00001207 if (Tok->Type == TT_TemplateCloser &&
1208 Tok->Parent->Type == TT_TemplateCloser &&
1209 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001210 HasCpp03IncompatibleFormat = true;
1211 Tok = &Tok->Children[0];
1212 }
1213 }
1214 if (Style.DerivePointerBinding) {
1215 if (CountBoundToType > CountBoundToVariable)
1216 Style.PointerBindsToType = true;
1217 else if (CountBoundToType < CountBoundToVariable)
1218 Style.PointerBindsToType = false;
1219 }
1220 if (Style.Standard == FormatStyle::LS_Auto) {
1221 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1222 : FormatStyle::LS_Cpp03;
1223 }
1224 }
1225
Manuel Klimekb95f5452013-02-08 17:38:27 +00001226 /// \brief Get the indent of \p Level from \p IndentForLevel.
1227 ///
1228 /// \p IndentForLevel must contain the indent for the level \c l
1229 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1230 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001231 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001232 if (IndentForLevel[Level] != -1)
1233 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001234 if (Level == 0)
1235 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001236 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001237 }
1238
1239 /// \brief Get the offset of the line relatively to the level.
1240 ///
1241 /// For example, 'public:' labels in classes are offset by 1 or 2
1242 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001243 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001244 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001245 return Style.AccessModifierOffset;
1246 return 0;
1247 }
1248
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001249 /// \brief Tries to merge lines into one.
1250 ///
1251 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1252 /// if possible; note that \c I will be incremented when lines are merged.
1253 ///
1254 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001255 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001256 std::vector<AnnotatedLine>::iterator &I,
1257 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001258 // We can never merge stuff if there are trailing line comments.
1259 if (I->Last->Type == TT_LineComment)
1260 return;
1261
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001262 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001263 // If we already exceed the column limit, we set 'Limit' to 0. The different
1264 // tryMerge..() functions can then decide whether to still do merging.
1265 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001266
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001267 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001268 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001269
Daniel Jasper25837aa2013-01-14 14:14:23 +00001270 if (I->Last->is(tok::l_brace)) {
1271 tryMergeSimpleBlock(I, E, Limit);
1272 } else if (I->First.is(tok::kw_if)) {
1273 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001274 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1275 I->First.FormatTok.IsFirst)) {
1276 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001277 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001278 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001279 }
1280
Daniel Jasper39825ea2013-01-14 15:40:57 +00001281 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1282 std::vector<AnnotatedLine>::iterator E,
1283 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001284 if (Limit == 0)
1285 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001286 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001287 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1288 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001289 if (I + 2 != E && (I + 2)->InPPDirective &&
1290 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1291 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001292 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001293 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001294 join(Line, *(++I));
1295 }
1296
Daniel Jasper25837aa2013-01-14 14:14:23 +00001297 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1298 std::vector<AnnotatedLine>::iterator E,
1299 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001300 if (Limit == 0)
1301 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001302 if (!Style.AllowShortIfStatementsOnASingleLine)
1303 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001304 if ((I + 1)->InPPDirective != I->InPPDirective ||
1305 ((I + 1)->InPPDirective &&
1306 (I + 1)->First.FormatTok.HasUnescapedNewline))
1307 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001308 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001309 if (Line.Last->isNot(tok::r_paren))
1310 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001311 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001312 return;
1313 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1314 return;
1315 // Only inline simple if's (no nested if or else).
1316 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1317 return;
1318 join(Line, *(++I));
1319 }
1320
1321 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001322 std::vector<AnnotatedLine>::iterator E,
1323 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001324 // First, check that the current line allows merging. This is the case if
1325 // we're not in a control flow statement and the last token is an opening
1326 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001327 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001328 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1329 tok::kw_else, tok::kw_try, tok::kw_catch,
1330 tok::kw_for,
1331 // This gets rid of all ObjC @ keywords and methods.
1332 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001333 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001334
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001335 AnnotatedToken *Tok = &(I + 1)->First;
1336 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001337 !Tok->MustBreakBefore) {
1338 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001339 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001340 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001341 join(Line, *(I + 1));
1342 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001343 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001344 // Check that we still have three lines and they fit into the limit.
1345 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1346 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001347 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001348
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001349 // Second, check that the next line does not contain any braces - if it
1350 // does, readability declines when putting it into a single line.
1351 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1352 return;
1353 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001354 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001355 return;
1356 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1357 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001358
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001359 // Last, check that the third line contains a single closing brace.
1360 Tok = &(I + 2)->First;
1361 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1362 Tok->MustBreakBefore)
1363 return;
1364
1365 join(Line, *(I + 1));
1366 join(Line, *(I + 2));
1367 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001368 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001369 }
1370
1371 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1372 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001373 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1374 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001375 }
1376
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001377 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001378 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001379 A.Last->Children.push_back(B.First);
1380 while (!A.Last->Children.empty()) {
1381 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001382 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001383 A.Last = &A.Last->Children[0];
1384 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001385 }
1386
Daniel Jasper97b89482013-03-13 07:49:51 +00001387 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001388 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1389 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1390 Ranges[i].getBegin()) &&
1391 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1392 Range.getBegin()))
1393 return true;
1394 }
1395 return false;
1396 }
1397
1398 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001399 const FormatToken *First = &TheLine.First.FormatTok;
1400 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001401 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001402 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1403 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001404 return touchesRanges(LineRange);
1405 }
1406
1407 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1408 const FormatToken *First = &TheLine.First.FormatTok;
1409 CharSourceRange LineRange = CharSourceRange::getCharRange(
1410 First->WhiteSpaceStart,
1411 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1412 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001413 }
1414
1415 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001416 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001417 }
1418
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001419 /// \brief Add a new line and the required indent before the first Token
1420 /// of the \c UnwrappedLine if there was no structural parsing error.
1421 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001422 void formatFirstToken(const AnnotatedToken &RootToken,
1423 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001424 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001425 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001426
Daniel Jasperbbc84152013-01-29 11:27:30 +00001427 unsigned Newlines =
1428 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001429 if (Newlines == 0 && !Tok.IsFirst)
1430 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001431
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001432 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001433 // Insert extra new line before access specifiers.
1434 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1435 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1436 ++Newlines;
1437
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001438 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001439 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001440 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001441 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001442 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001443 }
1444
Alexander Kornienko116ba682013-01-14 11:34:14 +00001445 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001446 FormatStyle Style;
1447 Lexer &Lex;
1448 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001449 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001450 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001451 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001452};
1453
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001454tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1455 SourceManager &SourceMgr,
1456 std::vector<CharSourceRange> Ranges,
1457 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001458 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001459 OwningPtr<DiagnosticConsumer> DiagPrinter;
1460 if (DiagClient == 0) {
1461 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1462 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1463 DiagClient = DiagPrinter.get();
1464 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001465 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001466 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001467 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001468 Diagnostics.setSourceManager(&SourceMgr);
1469 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001470 return formatter.format();
1471}
1472
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001473LangOptions getFormattingLangOpts() {
1474 LangOptions LangOpts;
1475 LangOpts.CPlusPlus = 1;
1476 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001477 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001478 LangOpts.Bool = 1;
1479 LangOpts.ObjC1 = 1;
1480 LangOpts.ObjC2 = 1;
1481 return LangOpts;
1482}
1483
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001484} // namespace format
1485} // namespace clang