blob: 814017a5127287984b5488be32767572ca3c3288 [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 (CallContinuation != Other.CallContinuation)
342 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000343 if (VariablePos != Other.VariablePos)
344 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000345 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000346 }
347 };
348
349 /// \brief The current state when indenting a unwrapped line.
350 ///
351 /// As the indenting tries different combinations this is copied by value.
352 struct LineState {
353 /// \brief The number of used columns in the current line.
354 unsigned Column;
355
356 /// \brief The token that needs to be next formatted.
357 const AnnotatedToken *NextToken;
358
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000359 /// \brief \c true if this line contains a continued for-loop section.
360 bool LineContainsContinuedForLoopSection;
361
Daniel Jasper400adc62013-02-08 15:28:42 +0000362 /// \brief The level of nesting inside (), [], <> and {}.
363 unsigned ParenLevel;
364
Daniel Jasper40c36c52013-02-18 11:05:07 +0000365 /// \brief The \c ParenLevel at the start of this line.
366 unsigned StartOfLineLevel;
367
Manuel Klimek02f640a2013-02-20 15:25:48 +0000368 /// \brief The start column of the string literal, if we're in a string
369 /// literal sequence, 0 otherwise.
370 unsigned StartOfStringLiteral;
371
Daniel Jasper337816e2013-01-11 10:22:12 +0000372 /// \brief A stack keeping track of properties applying to parenthesis
373 /// levels.
374 std::vector<ParenState> Stack;
375
376 /// \brief Comparison operator to be able to used \c LineState in \c map.
377 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000378 if (NextToken != Other.NextToken)
379 return NextToken < Other.NextToken;
380 if (Column != Other.Column)
381 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000382 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000383 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000384 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000385 if (ParenLevel != Other.ParenLevel)
386 return ParenLevel < Other.ParenLevel;
387 if (StartOfLineLevel != Other.StartOfLineLevel)
388 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000389 if (StartOfStringLiteral != Other.StartOfStringLiteral)
390 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000391 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 }
393 };
394
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000395 /// \brief Appends the next token to \p State and updates information
396 /// necessary for indentation.
397 ///
398 /// Puts the token on the current line if \p Newline is \c true and adds a
399 /// line break and necessary indentation otherwise.
400 ///
401 /// If \p DryRun is \c false, also creates and stores the required
402 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000403 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000404 const AnnotatedToken &Current = *State.NextToken;
405 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000406
Daniel Jasper291f9362013-03-20 15:58:10 +0000407 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000408 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
409 State.NextToken->FormatTok.TokenLength;
410 if (State.NextToken->Children.empty())
411 State.NextToken = NULL;
412 else
413 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000414 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000415 }
416
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000417 // If we are continuing an expression, we want to indent an extra 4 spaces.
418 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000419 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000420 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000421 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000422 if (Current.is(tok::r_brace)) {
423 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000424 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000425 State.StartOfStringLiteral != 0) {
426 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000427 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000428 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000429 State.Stack.back().FirstLessLess != 0) {
430 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000431 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000432 if (State.Stack.back().CallContinuation == 0) {
433 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000434 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000435 } else {
436 State.Column = State.Stack.back().CallContinuation;
437 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000438 } else if (Current.Type == TT_ConditionalExpr) {
439 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000440 } else if (Previous.is(tok::comma) &&
441 State.Stack.back().VariablePos != 0) {
442 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000443 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000444 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
445 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000446 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000447 } else if (Current.Type == TT_ObjCSelectorName) {
448 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
449 State.Column =
450 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
451 } else {
452 State.Column = State.Stack.back().Indent;
453 State.Stack.back().ColonPos =
454 State.Column + Current.FormatTok.TokenLength;
455 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000456 } else if (Current.Type == TT_StartOfName ||
457 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000458 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000459 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000460 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000461 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000462 // Ensure that we fall back to indenting 4 spaces instead of just
463 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000464 if (State.Column == FirstIndent)
465 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000466 }
467
Daniel Jasper54a86022013-02-15 11:07:25 +0000468 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000469 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000470 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000471 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000472 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000473
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000474 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000475 unsigned NewLines = 1;
476 if (Current.Type == TT_LineComment)
477 NewLines =
478 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
479 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000480 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000481 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000482 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000483 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000484 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000485 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000486 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000487
Daniel Jasper400adc62013-02-08 15:28:42 +0000488 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000489 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000490
491 // Any break on this level means that the parent level has been broken
492 // and we need to avoid bin packing there.
493 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
494 State.Stack[i].BreakBeforeParameter = true;
495 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000496 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
497 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
498 !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000499 State.Stack.back().BreakBeforeParameter = true;
500
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000501 // If we break after {, we should also break before the corresponding }.
502 if (Previous.is(tok::l_brace))
503 State.Stack.back().BreakBeforeClosingBrace = true;
504
505 if (State.Stack.back().AvoidBinPacking) {
506 // If we are breaking after '(', '{', '<', this is not bin packing
507 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000508 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000509 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
510 Line.MustBeDeclaration))
511 State.Stack.back().BreakBeforeParameter = true;
512 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000514 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000515 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
516 State.Stack.back().VariablePos == 0) {
517 State.Stack.back().VariablePos = State.Column;
518 // Move over * and & if they are bound to the variable name.
519 const AnnotatedToken *Tok = &Previous;
520 while (Tok &&
521 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
522 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
523 if (Tok->SpacesRequiredBefore != 0)
524 break;
525 Tok = Tok->Parent;
526 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000527 if (Previous.PartOfMultiVariableDeclStmt)
528 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
529 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000530
Daniel Jaspereef30492013-02-11 12:36:37 +0000531 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000532
Daniel Jasperf7935112012-12-03 18:12:45 +0000533 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000534 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000535
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000536 if (Current.Type == TT_ObjCSelectorName &&
537 State.Stack.back().ColonPos == 0) {
538 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000539 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000540 State.Stack.back().ColonPos =
541 State.Stack.back().Indent + Current.LongestObjCSelectorName;
542 else
543 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000544 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000545 }
546
Daniel Jasperc04baae2013-04-10 09:49:49 +0000547 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000548 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000549 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000550 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
551 State.Stack.back().AvoidBinPacking)
552 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000553
Daniel Jaspere9de2602012-12-06 09:56:08 +0000554 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000555 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000556 // Treat the condition inside an if as if it was a second function
557 // parameter, i.e. let nested calls have an indent of 4.
558 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000559 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000560 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000561 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000562 Previous.Type == TT_ConditionalExpr ||
563 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000564 getPrecedence(Previous) != prec::Assignment)
565 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000566 else if (Previous.Type == TT_InheritanceColon)
567 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000568 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000569 // If this function has multiple parameters, indent nested calls from
570 // the start of the first parameter.
571 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000573
Manuel Klimek1998ea22013-02-20 10:15:13 +0000574 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000575 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000576
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000577 /// \brief Mark the next token as consumed in \p State and modify its stacks
578 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000579 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000580 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000581 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000582
Daniel Jaspereead02b2013-02-14 08:42:54 +0000583 if (Current.Type == TT_InheritanceColon)
584 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
586 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000587 if (Current.is(tok::question))
588 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000589 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000590 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
591 State.Stack.back().StartOfFunctionCall =
592 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000593 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000594 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000595 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
596 State.Stack.back().AvoidBinPacking = true;
597 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000598 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000599
Daniel Jasper6bee6822013-04-08 20:33:42 +0000600 // If return returns a binary expression, align after it.
601 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
602 State.Stack.back().LastSpace = State.Column + 7;
603
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000604 // In ObjC method declaration we align on the ":" of parameters, but we need
605 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000606 if (Current.Type == TT_ObjCMethodSpecifier)
607 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000608
Daniel Jasper400adc62013-02-08 15:28:42 +0000609 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000610 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
611 // Don't add extra indentation for the first fake parenthesis after
612 // 'return', assignements or opening <({[. The indentation for these cases
613 // is special cased.
614 bool SkipFirstExtraIndent =
615 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000616 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000617 getPrecedence(*Previous) == prec::Assignment));
618 for (SmallVector<prec::Level, 4>::const_reverse_iterator
619 I = Current.FakeLParens.rbegin(),
620 E = Current.FakeLParens.rend();
621 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000622 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000623 NewParenState.Indent =
624 std::max(std::max(State.Column, NewParenState.Indent),
625 State.Stack.back().LastSpace);
626
627 // Always indent conditional expressions. Never indent expression where
628 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
629 // prec::Assignment) as those have different indentation rules. Indent
630 // other expression, unless the indentation needs to be skipped.
631 if (*I == prec::Conditional ||
632 (!SkipFirstExtraIndent && *I > prec::Assignment))
633 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000634 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000635 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000636 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000637 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000638 }
639
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000640 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000641 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000642 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000643 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000644 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000645 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000646 NewIndent = 2 + State.Stack.back().LastSpace;
647 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000648 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000649 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
650 State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000651 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000652 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000653 State.Stack.push_back(
654 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000655 State.Stack.back().NoLineBreak));
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000656
657 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
658 // This parenthesis was the last token possibly making use of Indent and
659 // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
660 // better memoization results.
661 State.Stack[State.Stack.size() - 2].Indent = 0;
662 State.Stack[State.Stack.size() - 2].LastSpace = 0;
663 }
664
Daniel Jasper400adc62013-02-08 15:28:42 +0000665 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000666 }
667
Daniel Jasperacc33662013-02-08 08:22:00 +0000668 // If this '[' opens an ObjC call, determine whether all parameters fit into
669 // one line and put one per line if they don't.
670 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
671 Current.MatchingParen != NULL) {
672 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
673 State.Stack.back().BreakBeforeParameter = true;
674 }
675
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000676 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000677 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000678 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000679 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
680 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000681 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000682 --State.ParenLevel;
683 }
684
685 // Remove scopes created by fake parenthesis.
686 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000687 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000688 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000689 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000690 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000691
Manuel Klimek0c915712013-02-20 15:32:58 +0000692 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000693 State.StartOfStringLiteral = State.Column;
694 } else if (Current.isNot(tok::comment)) {
695 State.StartOfStringLiteral = 0;
696 }
697
Manuel Klimek1998ea22013-02-20 10:15:13 +0000698 State.Column += Current.FormatTok.TokenLength;
699
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000700 if (State.NextToken->Children.empty())
701 State.NextToken = NULL;
702 else
703 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000704
Manuel Klimek1998ea22013-02-20 10:15:13 +0000705 return breakProtrudingToken(Current, State, DryRun);
706 }
707
708 /// \brief If the current token sticks out over the end of the line, break
709 /// it if possible.
710 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
711 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000712 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000713 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000714 if (Current.is(tok::string_literal)) {
715 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000716 const char *LiteralData = SourceMgr.getCharacterData(
717 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000718 if (!LiteralData || *LiteralData != '"')
719 return 0;
720
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000721 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
722 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000723 } else if (Current.Type == TT_BlockComment) {
724 BreakableBlockComment *BBC =
725 new BreakableBlockComment(SourceMgr, Current, StartColumn);
726 if (!DryRun)
727 BBC->alignLines(Whitespaces);
728 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000729 } else if (Current.Type == TT_LineComment &&
730 (Current.Parent == NULL ||
731 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000732 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000733 } else {
734 return 0;
735 }
736
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000737 bool BreakInserted = false;
738 unsigned Penalty = 0;
739 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
740 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000741 unsigned TailOffset = 0;
742 unsigned RemainingLength =
743 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
744 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000745 BreakableToken::Split Split =
746 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
747 if (Split.first == StringRef::npos)
748 break;
749 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000750 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
751 LineIndex, TailOffset + Split.first + Split.second);
752 if (NewRemainingLength >= RemainingLength)
753 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000754 if (!DryRun) {
755 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
756 Whitespaces);
757 }
758 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000759 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000760 Penalty += Style.PenaltyExcessCharacter;
761 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000762 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000763 State.Column = RemainingLength;
764 if (!DryRun) {
765 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
766 }
767 }
768
769 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000770 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
771 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000772 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000773 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000774 return Penalty;
775 }
776
Daniel Jasper2df93312013-01-09 10:16:05 +0000777 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000778 // In preprocessor directives reserve two chars for trailing " \"
779 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000780 }
781
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000782 /// \brief An edge in the solution space from \c Previous->State to \c State,
783 /// inserting a newline dependent on the \c NewLine.
784 struct StateNode {
785 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000786 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000787 LineState State;
788 bool NewLine;
789 StateNode *Previous;
790 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000791
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000792 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
793 ///
794 /// In case of equal penalties, we want to prefer states that were inserted
795 /// first. During state generation we make sure that we insert states first
796 /// that break the line as late as possible.
797 typedef std::pair<unsigned, unsigned> OrderedPenalty;
798
799 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
800 /// \c State has the given \c OrderedPenalty.
801 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
802
803 /// \brief The BFS queue type.
804 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
805 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000806
807 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000809 /// This implements a variant of Dijkstra's algorithm on the graph that spans
810 /// the solution space (\c LineStates are the nodes). The algorithm tries to
811 /// find the shortest path (the one with lowest penalty) from \p InitialState
812 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000813 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000814 std::set<LineState> Seen;
815
Daniel Jasper4b866272013-02-01 11:00:45 +0000816 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000817 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000818 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
819 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
820 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000821
822 // While not empty, take first element and follow edges.
823 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000824 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000825 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000826 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000827 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000828 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000829 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000830 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000831
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000832 if (!Seen.insert(Node->State).second)
833 // State already examined with lower penalty.
834 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000835
Manuel Klimekaf491072013-02-13 10:54:19 +0000836 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
837 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000838 }
839
840 if (Queue.empty())
841 // We were unable to find a solution, do nothing.
842 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000843 return 0;
844
Daniel Jasper4b866272013-02-01 11:00:45 +0000845 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000847 DEBUG(llvm::errs() << "Total number of analyzed states: " << Count << "\n");
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000848 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000849
Daniel Jasper4b866272013-02-01 11:00:45 +0000850 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 return Queue.top().second->State.Column;
852 }
853
854 void reconstructPath(LineState &State, StateNode *Current) {
855 // FIXME: This recursive implementation limits the possible number
856 // of tokens per line if compiled into a binary with small stack space.
857 // To become more independent of stack frame limitations we would need
858 // to also change the TokenAnnotator.
859 if (Current->Previous == NULL)
860 return;
861 reconstructPath(State, Current->Previous);
862 DEBUG({
863 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000864 llvm::errs()
865 << "Penalty for splitting before "
866 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
867 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000868 }
869 });
870 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000871 }
872
Manuel Klimekaf491072013-02-13 10:54:19 +0000873 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000874 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000875 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000876 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000877 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
878 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000879 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000880 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000881 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000882 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000883 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000884 Penalty += PreviousNode->State.NextToken->SplitPenalty;
885
886 StateNode *Node = new (Allocator.Allocate())
887 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000888 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000889 if (Node->State.Column > getColumnLimit()) {
890 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000891 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000892 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000893
894 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
895 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000896 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000897
Daniel Jasper4b866272013-02-01 11:00:45 +0000898 /// \brief Returns \c true, if a line break after \p State is allowed.
899 bool canBreak(const LineState &State) {
900 if (!State.NextToken->CanBreakBefore &&
901 !(State.NextToken->is(tok::r_brace) &&
902 State.Stack.back().BreakBeforeClosingBrace))
903 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000904 return !State.Stack.back().NoLineBreak;
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 mandatory.
908 bool mustBreak(const LineState &State) {
909 if (State.NextToken->MustBreakBefore)
910 return true;
911 if (State.NextToken->is(tok::r_brace) &&
912 State.Stack.back().BreakBeforeClosingBrace)
913 return true;
914 if (State.NextToken->Parent->is(tok::semi) &&
915 State.LineContainsContinuedForLoopSection)
916 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000917 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000918 State.NextToken->is(tok::question) ||
919 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000920 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000921 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000922 State.NextToken->isNot(tok::r_paren) &&
923 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000924 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000925 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
926 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000927 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000928 State.NextToken->LongestObjCSelectorName == 0 &&
929 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000930 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000931 if ((State.NextToken->Type == TT_CtorInitializerColon ||
932 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000933 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000934 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000935 if (State.NextToken->Type == TT_InlineASMColon)
936 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000937 // This prevents breaks like:
938 // ...
939 // SomeParameter, OtherParameter).DoSomething(
940 // ...
941 // As they hide "DoSomething" and generally bad for readability.
942 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
943 getRemainingLength(State) + State.Column > getColumnLimit() &&
944 State.ParenLevel < State.StartOfLineLevel)
945 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000946 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000947 }
948
Daniel Jasper9b334242013-03-15 14:57:30 +0000949 // Returns the total number of columns required for the remaining tokens.
950 unsigned getRemainingLength(const LineState &State) {
951 if (State.NextToken && State.NextToken->Parent)
952 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
953 return 0;
954 }
955
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 FormatStyle Style;
957 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000958 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000959 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000960 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000961 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000962
963 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
964 QueueType Queue;
965 // Increasing count of \c StateNode items we have created. This is used
966 // to create a deterministic order independent of the container.
967 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000968};
969
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000970class LexerBasedFormatTokenSource : public FormatTokenSource {
971public:
972 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000973 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000974 IdentTable(Lex.getLangOpts()) {
975 Lex.SetKeepWhitespaceMode(true);
976 }
977
978 virtual FormatToken getNextToken() {
979 if (GreaterStashed) {
980 FormatTok.NewlinesBefore = 0;
981 FormatTok.WhiteSpaceStart =
982 FormatTok.Tok.getLocation().getLocWithOffset(1);
983 FormatTok.WhiteSpaceLength = 0;
984 GreaterStashed = false;
985 return FormatTok;
986 }
987
988 FormatTok = FormatToken();
989 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000990 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000991 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000992 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
993 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000994
995 // Consume and record whitespace until we find a significant token.
996 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000997 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +0000998 if (Newlines > 0)
999 FormatTok.LastNewlineOffset =
1000 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001001 unsigned EscapedNewlines = Text.count("\\\n");
1002 FormatTok.NewlinesBefore += Newlines;
1003 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001004 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1005
1006 if (FormatTok.Tok.is(tok::eof))
1007 return FormatTok;
1008 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001009 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001010 }
Manuel Klimekef920692013-01-07 07:56:50 +00001011
1012 // Now FormatTok is the next non-whitespace token.
1013 FormatTok.TokenLength = Text.size();
1014
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001015 if (FormatTok.Tok.is(tok::comment)) {
1016 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1017 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1018 }
1019
Manuel Klimek1abf7892013-01-04 23:34:14 +00001020 // In case the token starts with escaped newlines, we want to
1021 // take them into account as whitespace - this pattern is quite frequent
1022 // in macro definitions.
1023 // FIXME: What do we want to do with other escaped spaces, and escaped
1024 // spaces or newlines in the middle of tokens?
1025 // FIXME: Add a more explicit test.
1026 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001027 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001028 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001029 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001030 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001031 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001032 }
1033
1034 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001035 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001036 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001037 FormatTok.Tok.setKind(Info.getTokenID());
1038 }
1039
1040 if (FormatTok.Tok.is(tok::greatergreater)) {
1041 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001042 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001043 GreaterStashed = true;
1044 }
1045
1046 return FormatTok;
1047 }
1048
Nico Weber29f9dea2013-02-11 15:32:15 +00001049 IdentifierTable &getIdentTable() { return IdentTable; }
1050
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001051private:
1052 FormatToken FormatTok;
1053 bool GreaterStashed;
1054 Lexer &Lex;
1055 SourceManager &SourceMgr;
1056 IdentifierTable IdentTable;
1057
1058 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001059 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001060 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1061 Tok.getLength());
1062 }
1063};
1064
Daniel Jasperf7935112012-12-03 18:12:45 +00001065class Formatter : public UnwrappedLineConsumer {
1066public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001067 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1068 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001069 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001070 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001071 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001072
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001073 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001074
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001075 tooling::Replacements format() {
1076 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1077 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001078 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001079 unsigned PreviousEndOfLineColumn = 0;
1080 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1081 Tokens.getIdentTable().get("in"));
1082 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1083 Annotator.annotate(AnnotatedLines[i]);
1084 }
1085 deriveLocalStyle();
1086 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1087 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1088 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001089
1090 // Adapt level to the next line if this is a comment.
1091 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001092 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001093 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1094 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1095 AnnotatedLines[i].First.Children.empty())
1096 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1097 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001098 NextNoneCommentLine =
1099 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1100 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001101 }
1102
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001103 std::vector<int> IndentForLevel;
1104 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001105 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001106 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1107 E = AnnotatedLines.end();
1108 I != E; ++I) {
1109 const AnnotatedLine &TheLine = *I;
1110 const FormatToken &FirstTok = TheLine.First.FormatTok;
1111 int Offset = getIndentOffset(TheLine.First);
1112 while (IndentForLevel.size() <= TheLine.Level)
1113 IndentForLevel.push_back(-1);
1114 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001115 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001116 if (TheLine.First.is(tok::eof)) {
1117 if (PreviousLineWasTouched) {
1118 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1119 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001120 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001121 }
1122 } else if (TheLine.Type != LT_Invalid &&
1123 (WasMoved || touchesLine(TheLine))) {
1124 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1125 unsigned Indent = LevelIndent;
1126 if (static_cast<int>(Indent) + Offset >= 0)
1127 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001128 if (FirstTok.WhiteSpaceStart.isValid() &&
1129 // Insert a break even if there is a structural error in case where
1130 // we break apart a line consisting of multiple unwrapped lines.
1131 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001132 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1133 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001134 } else {
1135 Indent = LevelIndent =
1136 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001137 }
1138 tryFitMultipleLinesInOne(Indent, I, E);
1139 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001140 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001141 PreviousEndOfLineColumn =
1142 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1143 IndentForLevel[TheLine.Level] = LevelIndent;
1144 PreviousLineWasTouched = true;
1145 } else {
1146 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1147 unsigned Indent =
1148 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1149 unsigned LevelIndent = Indent;
1150 if (static_cast<int>(LevelIndent) - Offset >= 0)
1151 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001152 if (TheLine.First.isNot(tok::comment))
1153 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001154
1155 // Remove trailing whitespace of the previous line if it was touched.
1156 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001157 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1158 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001159 }
1160 // If we did not reformat this unwrapped line, the column at the end of
1161 // the last token is unchanged - thus, we can calculate the end of the
1162 // last token.
1163 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1164 PreviousEndOfLineColumn =
1165 SourceMgr.getSpellingColumnNumber(LastLoc) +
1166 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1167 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001168 if (TheLine.Last->is(tok::comment))
1169 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1170 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001171 else
1172 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001173 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001174 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001175 }
1176 return Whitespaces.generateReplacements();
1177 }
1178
1179private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001180 void deriveLocalStyle() {
1181 unsigned CountBoundToVariable = 0;
1182 unsigned CountBoundToType = 0;
1183 bool HasCpp03IncompatibleFormat = false;
1184 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1185 if (AnnotatedLines[i].First.Children.empty())
1186 continue;
1187 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1188 while (!Tok->Children.empty()) {
1189 if (Tok->Type == TT_PointerOrReference) {
1190 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1191 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1192 if (SpacesBefore && !SpacesAfter)
1193 ++CountBoundToVariable;
1194 else if (!SpacesBefore && SpacesAfter)
1195 ++CountBoundToType;
1196 }
1197
Daniel Jasper400adc62013-02-08 15:28:42 +00001198 if (Tok->Type == TT_TemplateCloser &&
1199 Tok->Parent->Type == TT_TemplateCloser &&
1200 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001201 HasCpp03IncompatibleFormat = true;
1202 Tok = &Tok->Children[0];
1203 }
1204 }
1205 if (Style.DerivePointerBinding) {
1206 if (CountBoundToType > CountBoundToVariable)
1207 Style.PointerBindsToType = true;
1208 else if (CountBoundToType < CountBoundToVariable)
1209 Style.PointerBindsToType = false;
1210 }
1211 if (Style.Standard == FormatStyle::LS_Auto) {
1212 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1213 : FormatStyle::LS_Cpp03;
1214 }
1215 }
1216
Manuel Klimekb95f5452013-02-08 17:38:27 +00001217 /// \brief Get the indent of \p Level from \p IndentForLevel.
1218 ///
1219 /// \p IndentForLevel must contain the indent for the level \c l
1220 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1221 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001222 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001223 if (IndentForLevel[Level] != -1)
1224 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001225 if (Level == 0)
1226 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001227 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001228 }
1229
1230 /// \brief Get the offset of the line relatively to the level.
1231 ///
1232 /// For example, 'public:' labels in classes are offset by 1 or 2
1233 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001234 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001235 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001236 return Style.AccessModifierOffset;
1237 return 0;
1238 }
1239
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001240 /// \brief Tries to merge lines into one.
1241 ///
1242 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1243 /// if possible; note that \c I will be incremented when lines are merged.
1244 ///
1245 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001246 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001247 std::vector<AnnotatedLine>::iterator &I,
1248 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001249 // We can never merge stuff if there are trailing line comments.
1250 if (I->Last->Type == TT_LineComment)
1251 return;
1252
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001253 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001254 // If we already exceed the column limit, we set 'Limit' to 0. The different
1255 // tryMerge..() functions can then decide whether to still do merging.
1256 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001257
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001258 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001259 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001260
Daniel Jasper25837aa2013-01-14 14:14:23 +00001261 if (I->Last->is(tok::l_brace)) {
1262 tryMergeSimpleBlock(I, E, Limit);
1263 } else if (I->First.is(tok::kw_if)) {
1264 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001265 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1266 I->First.FormatTok.IsFirst)) {
1267 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001268 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001269 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001270 }
1271
Daniel Jasper39825ea2013-01-14 15:40:57 +00001272 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1273 std::vector<AnnotatedLine>::iterator E,
1274 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001275 if (Limit == 0)
1276 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001277 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001278 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1279 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001280 if (I + 2 != E && (I + 2)->InPPDirective &&
1281 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1282 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001283 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001284 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001285 join(Line, *(++I));
1286 }
1287
Daniel Jasper25837aa2013-01-14 14:14:23 +00001288 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1289 std::vector<AnnotatedLine>::iterator E,
1290 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001291 if (Limit == 0)
1292 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001293 if (!Style.AllowShortIfStatementsOnASingleLine)
1294 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001295 if ((I + 1)->InPPDirective != I->InPPDirective ||
1296 ((I + 1)->InPPDirective &&
1297 (I + 1)->First.FormatTok.HasUnescapedNewline))
1298 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001299 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001300 if (Line.Last->isNot(tok::r_paren))
1301 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001302 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001303 return;
1304 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1305 return;
1306 // Only inline simple if's (no nested if or else).
1307 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1308 return;
1309 join(Line, *(++I));
1310 }
1311
1312 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001313 std::vector<AnnotatedLine>::iterator E,
1314 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001315 // First, check that the current line allows merging. This is the case if
1316 // we're not in a control flow statement and the last token is an opening
1317 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001318 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001319 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1320 tok::kw_else, tok::kw_try, tok::kw_catch,
1321 tok::kw_for,
1322 // This gets rid of all ObjC @ keywords and methods.
1323 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001324 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001325
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001326 AnnotatedToken *Tok = &(I + 1)->First;
1327 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001328 !Tok->MustBreakBefore) {
1329 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001330 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001331 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001332 join(Line, *(I + 1));
1333 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001334 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001335 // Check that we still have three lines and they fit into the limit.
1336 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1337 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001338 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001339
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001340 // Second, check that the next line does not contain any braces - if it
1341 // does, readability declines when putting it into a single line.
1342 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1343 return;
1344 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001345 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001346 return;
1347 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1348 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001349
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001350 // Last, check that the third line contains a single closing brace.
1351 Tok = &(I + 2)->First;
1352 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1353 Tok->MustBreakBefore)
1354 return;
1355
1356 join(Line, *(I + 1));
1357 join(Line, *(I + 2));
1358 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001359 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001360 }
1361
1362 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1363 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001364 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1365 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001366 }
1367
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001368 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001369 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001370 A.Last->Children.push_back(B.First);
1371 while (!A.Last->Children.empty()) {
1372 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001373 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001374 A.Last = &A.Last->Children[0];
1375 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001376 }
1377
Daniel Jasper97b89482013-03-13 07:49:51 +00001378 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001379 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1380 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1381 Ranges[i].getBegin()) &&
1382 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1383 Range.getBegin()))
1384 return true;
1385 }
1386 return false;
1387 }
1388
1389 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001390 const FormatToken *First = &TheLine.First.FormatTok;
1391 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001392 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001393 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1394 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001395 return touchesRanges(LineRange);
1396 }
1397
1398 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1399 const FormatToken *First = &TheLine.First.FormatTok;
1400 CharSourceRange LineRange = CharSourceRange::getCharRange(
1401 First->WhiteSpaceStart,
1402 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1403 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001404 }
1405
1406 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001407 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001408 }
1409
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001410 /// \brief Add a new line and the required indent before the first Token
1411 /// of the \c UnwrappedLine if there was no structural parsing error.
1412 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001413 void formatFirstToken(const AnnotatedToken &RootToken,
1414 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001415 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001416 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001417
Daniel Jasperbbc84152013-01-29 11:27:30 +00001418 unsigned Newlines =
1419 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001420 if (Newlines == 0 && !Tok.IsFirst)
1421 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001422
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001423 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001424 // Insert extra new line before access specifiers.
1425 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1426 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1427 ++Newlines;
1428
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001429 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001430 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001431 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001432 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001433 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001434 }
1435
Alexander Kornienko116ba682013-01-14 11:34:14 +00001436 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001437 FormatStyle Style;
1438 Lexer &Lex;
1439 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001440 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001441 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001442 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001443};
1444
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001445tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1446 SourceManager &SourceMgr,
1447 std::vector<CharSourceRange> Ranges,
1448 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001449 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001450 OwningPtr<DiagnosticConsumer> DiagPrinter;
1451 if (DiagClient == 0) {
1452 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1453 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1454 DiagClient = DiagPrinter.get();
1455 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001456 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001457 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001458 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001459 Diagnostics.setSourceManager(&SourceMgr);
1460 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001461 return formatter.format();
1462}
1463
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001464LangOptions getFormattingLangOpts() {
1465 LangOptions LangOpts;
1466 LangOpts.CPlusPlus = 1;
1467 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001468 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001469 LangOpts.Bool = 1;
1470 LangOpts.ObjC1 = 1;
1471 LangOpts.ObjC2 = 1;
1472 return LangOpts;
1473}
1474
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001475} // namespace format
1476} // namespace clang