blob: e85ecd21c2eea37bf437861172e4a3008d6812c4 [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> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000039 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
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000047template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000048struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
49 static void
50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod6538332013-05-07 15:32:14 +000054 }
55};
56
57template <> struct MappingTraits<clang::format::FormatStyle> {
58 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000059 if (IO.outputting()) {
60 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
61 ArrayRef<StringRef> Styles(StylesArray);
62 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
63 StringRef StyleName(Styles[i]);
64 if (Style == clang::format::getPredefinedStyle(StyleName)) {
65 IO.mapOptional("# BasedOnStyle", StyleName);
66 break;
67 }
68 }
69 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000070 StringRef BasedOnStyle;
71 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000072 if (!BasedOnStyle.empty())
73 Style = clang::format::getPredefinedStyle(BasedOnStyle);
74 }
75
76 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
77 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
78 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
79 Style.AllowAllParametersOfDeclarationOnNextLine);
80 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
81 Style.AllowShortIfStatementsOnASingleLine);
82 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
83 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
84 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
85 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
86 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
87 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
88 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
89 IO.mapOptional("ObjCSpaceBeforeProtocolList",
90 Style.ObjCSpaceBeforeProtocolList);
91 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
92 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
93 Style.PenaltyReturnTypeOnItsOwnLine);
94 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
95 IO.mapOptional("SpacesBeforeTrailingComments",
96 Style.SpacesBeforeTrailingComments);
97 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +000098 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +000099 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000100 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000101 }
102};
103}
104}
105
Daniel Jasperf7935112012-12-03 18:12:45 +0000106namespace clang {
107namespace format {
108
Daniel Jasperf7935112012-12-03 18:12:45 +0000109FormatStyle getLLVMStyle() {
110 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000111 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000112 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000113 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000114 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000115 LLVMStyle.BinPackParameters = true;
116 LLVMStyle.ColumnLimit = 80;
117 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
118 LLVMStyle.DerivePointerBinding = false;
119 LLVMStyle.IndentCaseLabels = false;
120 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000121 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000122 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000123 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000124 LLVMStyle.PointerBindsToType = false;
125 LLVMStyle.SpacesBeforeTrailingComments = 1;
126 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000127 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000128 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000129 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000130 return LLVMStyle;
131}
132
133FormatStyle getGoogleStyle() {
134 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000135 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000136 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000137 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000138 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000139 GoogleStyle.BinPackParameters = true;
140 GoogleStyle.ColumnLimit = 80;
141 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
142 GoogleStyle.DerivePointerBinding = true;
143 GoogleStyle.IndentCaseLabels = true;
144 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000145 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000146 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000147 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000148 GoogleStyle.PointerBindsToType = true;
149 GoogleStyle.SpacesBeforeTrailingComments = 2;
150 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000151 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000152 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000153 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000154 return GoogleStyle;
155}
156
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000157FormatStyle getChromiumStyle() {
158 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000159 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000160 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000161 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000162 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
163 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000164 return ChromiumStyle;
165}
166
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000167FormatStyle getMozillaStyle() {
168 FormatStyle MozillaStyle = getLLVMStyle();
169 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
170 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
171 MozillaStyle.DerivePointerBinding = true;
172 MozillaStyle.IndentCaseLabels = true;
173 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
174 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
175 MozillaStyle.PointerBindsToType = true;
176 return MozillaStyle;
177}
178
Alexander Kornienkod6538332013-05-07 15:32:14 +0000179FormatStyle getPredefinedStyle(StringRef Name) {
180 if (Name.equals_lower("llvm"))
181 return getLLVMStyle();
182 if (Name.equals_lower("chromium"))
183 return getChromiumStyle();
184 if (Name.equals_lower("mozilla"))
185 return getMozillaStyle();
186 if (Name.equals_lower("google"))
187 return getGoogleStyle();
188
189 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
190 return getGoogleStyle();
191}
192
193llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
194 llvm::yaml::Input Input(Text);
195 Input >> *Style;
196 return Input.error();
197}
198
199std::string configurationAsText(const FormatStyle &Style) {
200 std::string Text;
201 llvm::raw_string_ostream Stream(Text);
202 llvm::yaml::Output Output(Stream);
203 // We use the same mapping method for input and output, so we need a non-const
204 // reference here.
205 FormatStyle NonConstStyle = Style;
206 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000207 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000208}
209
Daniel Jasperacc33662013-02-08 08:22:00 +0000210// Returns the length of everything up to the first possible line break after
211// the ), ], } or > matching \c Tok.
212static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
213 if (Tok.MatchingParen == NULL)
214 return 0;
215 AnnotatedToken *End = Tok.MatchingParen;
216 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
217 End = &End->Children[0];
218 }
219 return End->TotalLength - Tok.TotalLength + 1;
220}
221
Daniel Jasperf7935112012-12-03 18:12:45 +0000222class UnwrappedLineFormatter {
223public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000224 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000225 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000226 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000227 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000228 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000229 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000230 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000231
Manuel Klimek1abf7892013-01-04 23:34:14 +0000232 /// \brief Formats an \c UnwrappedLine.
233 ///
234 /// \returns The column after the last token in the last line of the
235 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000236 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000237 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000238 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000239 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000240 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000241 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000242 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000243 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000244 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000245 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000246 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000247 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000248
249 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000250 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000251
Daniel Jasper4b866272013-02-01 11:00:45 +0000252 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000253 unsigned ColumnLimit = Style.ColumnLimit;
254 if (NextLine && NextLine->InPPDirective &&
255 !NextLine->First.FormatTok.HasUnescapedNewline)
256 ColumnLimit = getColumnLimit();
257 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000258 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000259 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000260 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000261 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000262 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000263
Daniel Jasperacc33662013-02-08 08:22:00 +0000264 // If the ObjC method declaration does not fit on a line, we should format
265 // it with one arg per line.
266 if (Line.Type == LT_ObjCMethodDecl)
267 State.Stack.back().BreakBeforeParameter = true;
268
Daniel Jasper4b866272013-02-01 11:00:45 +0000269 // Find best solution in solution space.
270 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000271 }
272
273private:
Manuel Klimek24998102013-01-16 14:55:28 +0000274 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
275 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000276 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000277 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000278 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000279 }
280
Daniel Jasper337816e2013-01-11 10:22:12 +0000281 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000282 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000283 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000284 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
285 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000286 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000287 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
288 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000289 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000290
Daniel Jasperf7935112012-12-03 18:12:45 +0000291 /// \brief The position to which a specific parenthesis level needs to be
292 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000293 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000294
Daniel Jaspere9de2602012-12-06 09:56:08 +0000295 /// \brief The position of the last space on each level.
296 ///
297 /// Used e.g. to break like:
298 /// functionCall(Parameter, otherCall(
299 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000300 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000301
Daniel Jaspere9de2602012-12-06 09:56:08 +0000302 /// \brief The position the first "<<" operator encountered on each level.
303 ///
304 /// Used to align "<<" operators. 0 if no such operator has been encountered
305 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000306 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000307
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000308 /// \brief Whether a newline needs to be inserted before the block's closing
309 /// brace.
310 ///
311 /// We only want to insert a newline before the closing brace if there also
312 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000313 bool BreakBeforeClosingBrace;
314
Daniel Jasperca6623b2013-01-28 12:45:14 +0000315 /// \brief The column of a \c ? in a conditional expression;
316 unsigned QuestionColumn;
317
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000318 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
319 /// lines, in this context.
320 bool AvoidBinPacking;
321
322 /// \brief Break after the next comma (or all the commas in this context if
323 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000324 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000325
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000326 /// \brief Line breaking in this context would break a formatting rule.
327 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000328
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000329 /// \brief The position of the colon in an ObjC method declaration/call.
330 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000331
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000332 /// \brief The start of the most recent function in a builder-type call.
333 unsigned StartOfFunctionCall;
334
Daniel Jasperc238c872013-04-02 14:33:13 +0000335 /// \brief If a nested name specifier was broken over multiple lines, this
336 /// contains the start column of the second line. Otherwise 0.
337 unsigned NestedNameSpecifierContinuation;
338
339 /// \brief If a call expression was broken over multiple lines, this
340 /// contains the start column of the second line. Otherwise 0.
341 unsigned CallContinuation;
342
Daniel Jaspera628c982013-04-03 13:36:17 +0000343 /// \brief The column of the first variable name in a variable declaration.
344 ///
345 /// Used to align further variables if necessary.
346 unsigned VariablePos;
347
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000348 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
349 ///
350 /// Does not need to be considered for memoization / the comparison function
351 /// as otherwise identical states will have the same fake/non-fake
352 /// \c ParenStates.
353 bool ForFakeParenthesis;
354
Daniel Jasper337816e2013-01-11 10:22:12 +0000355 bool operator<(const ParenState &Other) const {
356 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000357 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000358 if (LastSpace != Other.LastSpace)
359 return LastSpace < Other.LastSpace;
360 if (FirstLessLess != Other.FirstLessLess)
361 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000362 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
363 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000364 if (QuestionColumn != Other.QuestionColumn)
365 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000366 if (AvoidBinPacking != Other.AvoidBinPacking)
367 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000368 if (BreakBeforeParameter != Other.BreakBeforeParameter)
369 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000370 if (NoLineBreak != Other.NoLineBreak)
371 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000372 if (ColonPos != Other.ColonPos)
373 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000374 if (StartOfFunctionCall != Other.StartOfFunctionCall)
375 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000376 if (CallContinuation != Other.CallContinuation)
377 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000378 if (VariablePos != Other.VariablePos)
379 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000380 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 }
382 };
383
384 /// \brief The current state when indenting a unwrapped line.
385 ///
386 /// As the indenting tries different combinations this is copied by value.
387 struct LineState {
388 /// \brief The number of used columns in the current line.
389 unsigned Column;
390
391 /// \brief The token that needs to be next formatted.
392 const AnnotatedToken *NextToken;
393
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000394 /// \brief \c true if this line contains a continued for-loop section.
395 bool LineContainsContinuedForLoopSection;
396
Daniel Jasper400adc62013-02-08 15:28:42 +0000397 /// \brief The level of nesting inside (), [], <> and {}.
398 unsigned ParenLevel;
399
Daniel Jasper40c36c52013-02-18 11:05:07 +0000400 /// \brief The \c ParenLevel at the start of this line.
401 unsigned StartOfLineLevel;
402
Manuel Klimek02f640a2013-02-20 15:25:48 +0000403 /// \brief The start column of the string literal, if we're in a string
404 /// literal sequence, 0 otherwise.
405 unsigned StartOfStringLiteral;
406
Daniel Jasper337816e2013-01-11 10:22:12 +0000407 /// \brief A stack keeping track of properties applying to parenthesis
408 /// levels.
409 std::vector<ParenState> Stack;
410
411 /// \brief Comparison operator to be able to used \c LineState in \c map.
412 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000413 if (NextToken != Other.NextToken)
414 return NextToken < Other.NextToken;
415 if (Column != Other.Column)
416 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000417 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000418 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000419 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000420 if (ParenLevel != Other.ParenLevel)
421 return ParenLevel < Other.ParenLevel;
422 if (StartOfLineLevel != Other.StartOfLineLevel)
423 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000424 if (StartOfStringLiteral != Other.StartOfStringLiteral)
425 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000426 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000427 }
428 };
429
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000430 /// \brief Appends the next token to \p State and updates information
431 /// necessary for indentation.
432 ///
433 /// Puts the token on the current line if \p Newline is \c true and adds a
434 /// line break and necessary indentation otherwise.
435 ///
436 /// If \p DryRun is \c false, also creates and stores the required
437 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000438 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000439 const AnnotatedToken &Current = *State.NextToken;
440 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000441
Daniel Jasper291f9362013-03-20 15:58:10 +0000442 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000443 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
444 State.NextToken->FormatTok.TokenLength;
445 if (State.NextToken->Children.empty())
446 State.NextToken = NULL;
447 else
448 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000449 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000450 }
451
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000452 // If we are continuing an expression, we want to indent an extra 4 spaces.
453 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000454 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000455 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000456 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000457 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000458 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000459 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000460 State.StartOfStringLiteral != 0) {
461 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000462 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000463 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000464 State.Stack.back().FirstLessLess != 0) {
465 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000466 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000467 if (State.Stack.back().CallContinuation == 0) {
468 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000469 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000470 } else {
471 State.Column = State.Stack.back().CallContinuation;
472 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000473 } else if (Current.Type == TT_ConditionalExpr) {
474 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000475 } else if (Previous.is(tok::comma) &&
476 State.Stack.back().VariablePos != 0) {
477 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000478 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000479 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
480 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000481 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000482 } else if (Current.Type == TT_ObjCSelectorName) {
483 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
484 State.Column =
485 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
486 } else {
487 State.Column = State.Stack.back().Indent;
488 State.Stack.back().ColonPos =
489 State.Column + Current.FormatTok.TokenLength;
490 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000491 } else if (Current.Type == TT_StartOfName ||
492 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000493 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000494 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000495 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000496 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000497 // Ensure that we fall back to indenting 4 spaces instead of just
498 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000499 if (State.Column == FirstIndent)
500 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000501 }
502
Daniel Jasper54a86022013-02-15 11:07:25 +0000503 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000504 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000505 if ((Previous.isOneOf(tok::comma, tok::semi) &&
506 !State.Stack.back().AvoidBinPacking) ||
507 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000508 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000509
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000510 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000511 unsigned NewLines = 1;
512 if (Current.Type == TT_LineComment)
513 NewLines =
514 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
515 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000516 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000517 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000518 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000519 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000520 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000521 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000522 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000523
Daniel Jasper400adc62013-02-08 15:28:42 +0000524 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000525 if (Current.isOneOf(tok::arrow, tok::period))
526 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000527 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000528
529 // Any break on this level means that the parent level has been broken
530 // and we need to avoid bin packing there.
531 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
532 State.Stack[i].BreakBeforeParameter = true;
533 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000534 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
535 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000536 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000537 State.Stack.back().BreakBeforeParameter = true;
538
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000539 // If we break after {, we should also break before the corresponding }.
540 if (Previous.is(tok::l_brace))
541 State.Stack.back().BreakBeforeClosingBrace = true;
542
543 if (State.Stack.back().AvoidBinPacking) {
544 // If we are breaking after '(', '{', '<', this is not bin packing
545 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000546 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
547 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000548 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
549 Line.MustBeDeclaration))
550 State.Stack.back().BreakBeforeParameter = true;
551 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000552 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000553 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000554 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
555 State.Stack.back().VariablePos == 0) {
556 State.Stack.back().VariablePos = State.Column;
557 // Move over * and & if they are bound to the variable name.
558 const AnnotatedToken *Tok = &Previous;
559 while (Tok &&
560 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
561 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
562 if (Tok->SpacesRequiredBefore != 0)
563 break;
564 Tok = Tok->Parent;
565 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000566 if (Previous.PartOfMultiVariableDeclStmt)
567 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
568 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000569
Daniel Jaspereef30492013-02-11 12:36:37 +0000570 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000573 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000574
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000575 if (Current.Type == TT_ObjCSelectorName &&
576 State.Stack.back().ColonPos == 0) {
577 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000578 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000579 State.Stack.back().ColonPos =
580 State.Stack.back().Indent + Current.LongestObjCSelectorName;
581 else
582 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000583 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000584 }
585
Daniel Jasperc04baae2013-04-10 09:49:49 +0000586 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000587 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000588 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000589 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
590 State.Stack.back().AvoidBinPacking)
591 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000592
Daniel Jaspere9de2602012-12-06 09:56:08 +0000593 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000594 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000595 // Treat the condition inside an if as if it was a second function
596 // parameter, i.e. let nested calls have an indent of 4.
597 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000598 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000599 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000600 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000601 Previous.Type == TT_ConditionalExpr ||
602 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000603 getPrecedence(Previous) != prec::Assignment)
604 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000605 else if (Previous.Type == TT_InheritanceColon)
606 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000607 else if (Previous.opensScope() && !Current.FakeLParens.empty())
608 // If this function has multiple parameters or a binary expression
609 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000610 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000612
Manuel Klimek1998ea22013-02-20 10:15:13 +0000613 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000614 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000615
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000616 /// \brief Mark the next token as consumed in \p State and modify its stacks
617 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000618 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000620 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000621
Daniel Jaspereead02b2013-02-14 08:42:54 +0000622 if (Current.Type == TT_InheritanceColon)
623 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000624 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
625 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000626 if (Current.is(tok::question))
627 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000628 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000629 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
630 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000631 Current.LastInChainOfCalls ? 0 : State.Column +
632 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000633 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000634 // Indent 2 from the column, so:
635 // SomeClass::SomeClass()
636 // : First(...), ...
637 // Next(...)
638 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000639 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000640 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
641 State.Stack.back().AvoidBinPacking = true;
642 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000643 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000644
Daniel Jasper6bee6822013-04-08 20:33:42 +0000645 // If return returns a binary expression, align after it.
646 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
647 State.Stack.back().LastSpace = State.Column + 7;
648
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000649 // In ObjC method declaration we align on the ":" of parameters, but we need
650 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000651 if (Current.Type == TT_ObjCMethodSpecifier)
652 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000653
Daniel Jasper400adc62013-02-08 15:28:42 +0000654 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000655 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
656 // Don't add extra indentation for the first fake parenthesis after
657 // 'return', assignements or opening <({[. The indentation for these cases
658 // is special cased.
659 bool SkipFirstExtraIndent =
660 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000661 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000662 getPrecedence(*Previous) == prec::Assignment));
663 for (SmallVector<prec::Level, 4>::const_reverse_iterator
664 I = Current.FakeLParens.rbegin(),
665 E = Current.FakeLParens.rend();
666 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000667 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000668 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000669 NewParenState.Indent =
670 std::max(std::max(State.Column, NewParenState.Indent),
671 State.Stack.back().LastSpace);
672
673 // Always indent conditional expressions. Never indent expression where
674 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
675 // prec::Assignment) as those have different indentation rules. Indent
676 // other expression, unless the indentation needs to be skipped.
677 if (*I == prec::Conditional ||
678 (!SkipFirstExtraIndent && *I > prec::Assignment))
679 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000680 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000681 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000682 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000683 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000684 }
685
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000686 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000687 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000688 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000689 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000690 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000691 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000692 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000693 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000694 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000695 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000696 NewIndent =
697 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000698 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000699 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000700
701 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
702 // This parenthesis was the last token possibly making use of Indent and
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000703 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000704 // better memoization results.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000705 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
706 State.Stack[i].Indent = 0;
707 State.Stack[i].LastSpace = 0;
708 if (!State.Stack[i].ForFakeParenthesis)
709 break;
710 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000711 }
712
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000713 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
714 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000715 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000716 }
717
Daniel Jasperacc33662013-02-08 08:22:00 +0000718 // If this '[' opens an ObjC call, determine whether all parameters fit into
719 // one line and put one per line if they don't.
720 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
721 Current.MatchingParen != NULL) {
722 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
723 State.Stack.back().BreakBeforeParameter = true;
724 }
725
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000726 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000727 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000728 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000729 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
730 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000731 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000732 --State.ParenLevel;
733 }
734
735 // Remove scopes created by fake parenthesis.
736 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000737 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000738 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000739 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000741
Daniel Jasper47a04442013-05-13 20:50:15 +0000742 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000743 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000744 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
745 tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000746 }
747
Manuel Klimek1998ea22013-02-20 10:15:13 +0000748 State.Column += Current.FormatTok.TokenLength;
749
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000750 if (State.NextToken->Children.empty())
751 State.NextToken = NULL;
752 else
753 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000754
Manuel Klimek1998ea22013-02-20 10:15:13 +0000755 return breakProtrudingToken(Current, State, DryRun);
756 }
757
758 /// \brief If the current token sticks out over the end of the line, break
759 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000760 ///
761 /// \returns An extra penalty if a token was broken, otherwise 0.
762 ///
763 /// Note that the penalty of the token protruding the allowed line length is
764 /// already handled in \c addNextStateToQueue; the returned penalty will only
765 /// cover the cost of the additional line breaks.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000766 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000767 bool DryRun,
768 unsigned UnbreakableTailLength = 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000769 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000770 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
771 UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000772 if (Current.is(tok::string_literal)) {
773 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000774 const char *LiteralData = SourceMgr.getCharacterData(
775 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000776 if (!LiteralData || *LiteralData != '"')
777 return 0;
778
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000779 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
780 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000781 } else if (Current.Type == TT_BlockComment) {
782 BreakableBlockComment *BBC =
783 new BreakableBlockComment(SourceMgr, Current, StartColumn);
784 if (!DryRun)
785 BBC->alignLines(Whitespaces);
786 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000787 } else if (Current.Type == TT_LineComment &&
788 (Current.Parent == NULL ||
789 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000790 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000791 } else {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000792 // If a token that we cannot breaks protrudes, it means we were unable to
793 // break a sequence of tokens due to disallowed breaks between the tokens.
794 // Thus, we recursively search backwards to try to find a breakable token.
795 if (State.Column <= getColumnLimit() ||
796 Current.CanBreakBefore || !Current.Parent)
797 return 0;
798 return breakProtrudingToken(
799 *Current.Parent, State, DryRun,
800 UnbreakableTailLength + Current.FormatTok.TokenLength);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000801 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000802 if (UnbreakableTailLength >= getColumnLimit())
803 return 0;
804 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000805
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000806 bool BreakInserted = false;
807 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000808 unsigned PositionAfterLastLineInToken = 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000809 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
810 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000811 unsigned TailOffset = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000812 unsigned RemainingTokenLength =
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000813 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000814 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000815 BreakableToken::Split Split =
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000816 Token->getSplit(LineIndex, TailOffset, RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000817 if (Split.first == StringRef::npos)
818 break;
819 assert(Split.first != 0);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000820 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000821 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000822 if (NewRemainingTokenLength >= RemainingTokenLength)
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000823 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000824 if (!DryRun) {
825 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
826 Whitespaces);
827 }
828 TailOffset += Split.first + Split.second;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000829 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000830 Penalty += Style.PenaltyExcessCharacter;
831 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000832 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000833 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000834 if (!DryRun) {
835 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
836 }
837 }
838
839 if (BreakInserted) {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000840 State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000841 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
842 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000843 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000844 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000845 return Penalty;
846 }
847
Daniel Jasper2df93312013-01-09 10:16:05 +0000848 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000849 // In preprocessor directives reserve two chars for trailing " \"
850 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000851 }
852
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000853 /// \brief An edge in the solution space from \c Previous->State to \c State,
854 /// inserting a newline dependent on the \c NewLine.
855 struct StateNode {
856 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000857 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000858 LineState State;
859 bool NewLine;
860 StateNode *Previous;
861 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000862
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000863 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
864 ///
865 /// In case of equal penalties, we want to prefer states that were inserted
866 /// first. During state generation we make sure that we insert states first
867 /// that break the line as late as possible.
868 typedef std::pair<unsigned, unsigned> OrderedPenalty;
869
870 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
871 /// \c State has the given \c OrderedPenalty.
872 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
873
874 /// \brief The BFS queue type.
875 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
876 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000877
878 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000879 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000880 /// This implements a variant of Dijkstra's algorithm on the graph that spans
881 /// the solution space (\c LineStates are the nodes). The algorithm tries to
882 /// find the shortest path (the one with lowest penalty) from \p InitialState
883 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000884 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000885 std::set<LineState> Seen;
886
Daniel Jasper4b866272013-02-01 11:00:45 +0000887 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000888 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000889 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
890 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
891 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000892
893 // While not empty, take first element and follow edges.
894 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000895 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000896 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000897 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000898 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000899 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000900 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000901 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000902
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000903 if (!Seen.insert(Node->State).second)
904 // State already examined with lower penalty.
905 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000906
Manuel Klimekaf491072013-02-13 10:54:19 +0000907 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
908 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000909 }
910
911 if (Queue.empty())
912 // We were unable to find a solution, do nothing.
913 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000914 return 0;
915
Daniel Jasper4b866272013-02-01 11:00:45 +0000916 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000917 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000918 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
919 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000920
Daniel Jasper4b866272013-02-01 11:00:45 +0000921 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000922 return Queue.top().second->State.Column;
923 }
924
925 void reconstructPath(LineState &State, StateNode *Current) {
926 // FIXME: This recursive implementation limits the possible number
927 // of tokens per line if compiled into a binary with small stack space.
928 // To become more independent of stack frame limitations we would need
929 // to also change the TokenAnnotator.
930 if (Current->Previous == NULL)
931 return;
932 reconstructPath(State, Current->Previous);
933 DEBUG({
934 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000935 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000936 << "Penalty for splitting before "
937 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
938 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000939 }
940 });
941 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000942 }
943
Manuel Klimekaf491072013-02-13 10:54:19 +0000944 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000946 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000947 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000948 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
949 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000950 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000951 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000952 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000953 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000954 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000955 Penalty += PreviousNode->State.NextToken->SplitPenalty;
956
957 StateNode *Node = new (Allocator.Allocate())
958 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000959 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000960 if (Node->State.Column > getColumnLimit()) {
961 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000962 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000963 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000964
965 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
966 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000967 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000968
Daniel Jasper4b866272013-02-01 11:00:45 +0000969 /// \brief Returns \c true, if a line break after \p State is allowed.
970 bool canBreak(const LineState &State) {
971 if (!State.NextToken->CanBreakBefore &&
972 !(State.NextToken->is(tok::r_brace) &&
973 State.Stack.back().BreakBeforeClosingBrace))
974 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000975 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000976 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000977
Daniel Jasper4b866272013-02-01 11:00:45 +0000978 /// \brief Returns \c true, if a line break after \p State is mandatory.
979 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000980 const AnnotatedToken &Current = *State.NextToken;
981 const AnnotatedToken &Previous = *Current.Parent;
982 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +0000983 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000984 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +0000985 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000986 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +0000987 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000988 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
989 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000990 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000991 !Current.isTrailingComment() &&
992 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000993 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000994
995 // If we need to break somewhere inside the LHS of a binary expression, we
996 // should also break after the operator.
997 if (Previous.Type == TT_BinaryOperator &&
998 !Previous.isOneOf(tok::lessless, tok::question) &&
999 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001000 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001001 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001002
1003 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1004 // out whether it is the first parameter. Clean this up.
1005 if (Current.Type == TT_ObjCSelectorName &&
1006 Current.LongestObjCSelectorName == 0 &&
1007 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001008 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001009 if ((Current.Type == TT_CtorInitializerColon ||
1010 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001011 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001012
Daniel Jasper9b334242013-03-15 14:57:30 +00001013 // This prevents breaks like:
1014 // ...
1015 // SomeParameter, OtherParameter).DoSomething(
1016 // ...
1017 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +00001018 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +00001019 getRemainingLength(State) + State.Column > getColumnLimit() &&
1020 State.ParenLevel < State.StartOfLineLevel)
1021 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001022 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 }
1024
Daniel Jasper9b334242013-03-15 14:57:30 +00001025 // Returns the total number of columns required for the remaining tokens.
1026 unsigned getRemainingLength(const LineState &State) {
1027 if (State.NextToken && State.NextToken->Parent)
1028 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1029 return 0;
1030 }
1031
Daniel Jasperf7935112012-12-03 18:12:45 +00001032 FormatStyle Style;
1033 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001034 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001035 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001037 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001038
1039 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1040 QueueType Queue;
1041 // Increasing count of \c StateNode items we have created. This is used
1042 // to create a deterministic order independent of the container.
1043 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044};
1045
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001046class LexerBasedFormatTokenSource : public FormatTokenSource {
1047public:
1048 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001049 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001050 IdentTable(Lex.getLangOpts()) {
1051 Lex.SetKeepWhitespaceMode(true);
1052 }
1053
1054 virtual FormatToken getNextToken() {
1055 if (GreaterStashed) {
1056 FormatTok.NewlinesBefore = 0;
1057 FormatTok.WhiteSpaceStart =
1058 FormatTok.Tok.getLocation().getLocWithOffset(1);
1059 FormatTok.WhiteSpaceLength = 0;
1060 GreaterStashed = false;
1061 return FormatTok;
1062 }
1063
1064 FormatTok = FormatToken();
1065 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001066 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001067 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001068 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1069 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001070
1071 // Consume and record whitespace until we find a significant token.
1072 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001073 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001074 if (Newlines > 0)
1075 FormatTok.LastNewlineOffset =
1076 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001077 unsigned EscapedNewlines = Text.count("\\\n");
1078 FormatTok.NewlinesBefore += Newlines;
1079 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001080 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1081
1082 if (FormatTok.Tok.is(tok::eof))
1083 return FormatTok;
1084 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001085 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001086 }
Manuel Klimekef920692013-01-07 07:56:50 +00001087
1088 // Now FormatTok is the next non-whitespace token.
1089 FormatTok.TokenLength = Text.size();
1090
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001091 if (FormatTok.Tok.is(tok::comment)) {
1092 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1093 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1094 }
1095
Manuel Klimek1abf7892013-01-04 23:34:14 +00001096 // In case the token starts with escaped newlines, we want to
1097 // take them into account as whitespace - this pattern is quite frequent
1098 // in macro definitions.
1099 // FIXME: What do we want to do with other escaped spaces, and escaped
1100 // spaces or newlines in the middle of tokens?
1101 // FIXME: Add a more explicit test.
1102 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001103 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001104 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001105 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001106 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001107 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001108 }
1109
1110 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001111 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001112 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001113 FormatTok.Tok.setKind(Info.getTokenID());
1114 }
1115
1116 if (FormatTok.Tok.is(tok::greatergreater)) {
1117 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001118 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001119 GreaterStashed = true;
1120 }
1121
1122 return FormatTok;
1123 }
1124
Nico Weber29f9dea2013-02-11 15:32:15 +00001125 IdentifierTable &getIdentTable() { return IdentTable; }
1126
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001127private:
1128 FormatToken FormatTok;
1129 bool GreaterStashed;
1130 Lexer &Lex;
1131 SourceManager &SourceMgr;
1132 IdentifierTable IdentTable;
1133
1134 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001135 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001136 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1137 Tok.getLength());
1138 }
1139};
1140
Daniel Jasperf7935112012-12-03 18:12:45 +00001141class Formatter : public UnwrappedLineConsumer {
1142public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001143 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1144 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001145 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001146 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001147 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001148
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001149 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001150
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001151 tooling::Replacements format() {
1152 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1153 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001154 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001155 unsigned PreviousEndOfLineColumn = 0;
1156 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1157 Tokens.getIdentTable().get("in"));
1158 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1159 Annotator.annotate(AnnotatedLines[i]);
1160 }
1161 deriveLocalStyle();
1162 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1163 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1164 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001165
1166 // Adapt level to the next line if this is a comment.
1167 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001168 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001169 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1170 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1171 AnnotatedLines[i].First.Children.empty())
1172 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1173 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001174 NextNoneCommentLine =
1175 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1176 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001177 }
1178
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001179 std::vector<int> IndentForLevel;
1180 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001181 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001182 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001183 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1184 E = AnnotatedLines.end();
1185 I != E; ++I) {
1186 const AnnotatedLine &TheLine = *I;
1187 const FormatToken &FirstTok = TheLine.First.FormatTok;
1188 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001189
1190 // Check whether this line is part of a formatted preprocessor directive.
1191 if (FirstTok.HasUnescapedNewline)
1192 FormatPPDirective = false;
1193 if (!FormatPPDirective && TheLine.InPPDirective &&
1194 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1195 FormatPPDirective = true;
1196
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001197 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001198 while (IndentForLevel.size() <= TheLine.Level)
1199 IndentForLevel.push_back(-1);
1200 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001201 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1202 if (static_cast<int>(Indent) + Offset >= 0)
1203 Indent += Offset;
1204 tryFitMultipleLinesInOne(Indent, I, E);
1205
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001206 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001207 if (TheLine.First.is(tok::eof)) {
1208 if (PreviousLineWasTouched) {
1209 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1210 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001211 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001212 }
1213 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001214 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001215 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001216 if (FirstTok.WhiteSpaceStart.isValid() &&
1217 // Insert a break even if there is a structural error in case where
1218 // we break apart a line consisting of multiple unwrapped lines.
1219 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001220 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1221 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001222 } else {
1223 Indent = LevelIndent =
1224 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001225 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001226 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001227 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001228 PreviousEndOfLineColumn =
1229 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1230 IndentForLevel[TheLine.Level] = LevelIndent;
1231 PreviousLineWasTouched = true;
1232 } else {
1233 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001234 unsigned LevelIndent =
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001235 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001236 // Remove trailing whitespace of the previous line if it was touched.
1237 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1238 formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
1239 TheLine.InPPDirective, PreviousEndOfLineColumn);
1240
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001241 if (static_cast<int>(LevelIndent) - Offset >= 0)
1242 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001243 if (TheLine.First.isNot(tok::comment))
1244 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001245 }
1246 // If we did not reformat this unwrapped line, the column at the end of
1247 // the last token is unchanged - thus, we can calculate the end of the
1248 // last token.
1249 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1250 PreviousEndOfLineColumn =
1251 SourceMgr.getSpellingColumnNumber(LastLoc) +
1252 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1253 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001254 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001255 Whitespaces.addUntouchableComment(
1256 SourceMgr.getSpellingColumnNumber(
1257 TheLine.Last->FormatTok.Tok.getLocation()) -
1258 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001259 else
1260 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001261 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001262 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001263 }
1264 return Whitespaces.generateReplacements();
1265 }
1266
1267private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001268 void deriveLocalStyle() {
1269 unsigned CountBoundToVariable = 0;
1270 unsigned CountBoundToType = 0;
1271 bool HasCpp03IncompatibleFormat = false;
1272 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1273 if (AnnotatedLines[i].First.Children.empty())
1274 continue;
1275 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1276 while (!Tok->Children.empty()) {
1277 if (Tok->Type == TT_PointerOrReference) {
1278 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1279 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1280 if (SpacesBefore && !SpacesAfter)
1281 ++CountBoundToVariable;
1282 else if (!SpacesBefore && SpacesAfter)
1283 ++CountBoundToType;
1284 }
1285
Daniel Jasper400adc62013-02-08 15:28:42 +00001286 if (Tok->Type == TT_TemplateCloser &&
1287 Tok->Parent->Type == TT_TemplateCloser &&
1288 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001289 HasCpp03IncompatibleFormat = true;
1290 Tok = &Tok->Children[0];
1291 }
1292 }
1293 if (Style.DerivePointerBinding) {
1294 if (CountBoundToType > CountBoundToVariable)
1295 Style.PointerBindsToType = true;
1296 else if (CountBoundToType < CountBoundToVariable)
1297 Style.PointerBindsToType = false;
1298 }
1299 if (Style.Standard == FormatStyle::LS_Auto) {
1300 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1301 : FormatStyle::LS_Cpp03;
1302 }
1303 }
1304
Manuel Klimekb95f5452013-02-08 17:38:27 +00001305 /// \brief Get the indent of \p Level from \p IndentForLevel.
1306 ///
1307 /// \p IndentForLevel must contain the indent for the level \c l
1308 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1309 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001310 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001311 if (IndentForLevel[Level] != -1)
1312 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001313 if (Level == 0)
1314 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001315 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001316 }
1317
1318 /// \brief Get the offset of the line relatively to the level.
1319 ///
1320 /// For example, 'public:' labels in classes are offset by 1 or 2
1321 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001322 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001323 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001324 return Style.AccessModifierOffset;
1325 return 0;
1326 }
1327
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001328 /// \brief Tries to merge lines into one.
1329 ///
1330 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1331 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001332 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001333 std::vector<AnnotatedLine>::iterator &I,
1334 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001335 // We can never merge stuff if there are trailing line comments.
1336 if (I->Last->Type == TT_LineComment)
1337 return;
1338
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001339 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001340 // If we already exceed the column limit, we set 'Limit' to 0. The different
1341 // tryMerge..() functions can then decide whether to still do merging.
1342 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001343
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001344 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001345 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001346
Daniel Jasper25837aa2013-01-14 14:14:23 +00001347 if (I->Last->is(tok::l_brace)) {
1348 tryMergeSimpleBlock(I, E, Limit);
1349 } else if (I->First.is(tok::kw_if)) {
1350 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001351 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1352 I->First.FormatTok.IsFirst)) {
1353 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001354 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001355 }
1356
Daniel Jasper39825ea2013-01-14 15:40:57 +00001357 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1358 std::vector<AnnotatedLine>::iterator E,
1359 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001360 if (Limit == 0)
1361 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001362 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001363 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1364 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001365 if (I + 2 != E && (I + 2)->InPPDirective &&
1366 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1367 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001368 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001369 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001370 join(Line, *(++I));
1371 }
1372
Daniel Jasper25837aa2013-01-14 14:14:23 +00001373 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1374 std::vector<AnnotatedLine>::iterator E,
1375 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001376 if (Limit == 0)
1377 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001378 if (!Style.AllowShortIfStatementsOnASingleLine)
1379 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001380 if ((I + 1)->InPPDirective != I->InPPDirective ||
1381 ((I + 1)->InPPDirective &&
1382 (I + 1)->First.FormatTok.HasUnescapedNewline))
1383 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001384 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001385 if (Line.Last->isNot(tok::r_paren))
1386 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001387 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001388 return;
1389 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1390 return;
1391 // Only inline simple if's (no nested if or else).
1392 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1393 return;
1394 join(Line, *(++I));
1395 }
1396
1397 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001398 std::vector<AnnotatedLine>::iterator E,
1399 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001400 // First, check that the current line allows merging. This is the case if
1401 // we're not in a control flow statement and the last token is an opening
1402 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001403 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001404 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1405 tok::kw_else, tok::kw_try, tok::kw_catch,
1406 tok::kw_for,
1407 // This gets rid of all ObjC @ keywords and methods.
1408 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001409 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001410
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001411 AnnotatedToken *Tok = &(I + 1)->First;
1412 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001413 !Tok->MustBreakBefore) {
1414 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001415 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001416 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001417 join(Line, *(I + 1));
1418 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001419 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001420 // Check that we still have three lines and they fit into the limit.
1421 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1422 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001423 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001424
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001425 // Second, check that the next line does not contain any braces - if it
1426 // does, readability declines when putting it into a single line.
1427 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1428 return;
1429 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001430 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001431 return;
1432 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1433 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001434
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001435 // Last, check that the third line contains a single closing brace.
1436 Tok = &(I + 2)->First;
1437 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1438 Tok->MustBreakBefore)
1439 return;
1440
1441 join(Line, *(I + 1));
1442 join(Line, *(I + 2));
1443 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001444 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001445 }
1446
1447 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1448 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001449 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1450 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001451 }
1452
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001453 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001454 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001455 A.Last->Children.push_back(B.First);
1456 while (!A.Last->Children.empty()) {
1457 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001458 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001459 A.Last = &A.Last->Children[0];
1460 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001461 }
1462
Daniel Jasper97b89482013-03-13 07:49:51 +00001463 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001464 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1465 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1466 Ranges[i].getBegin()) &&
1467 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1468 Range.getBegin()))
1469 return true;
1470 }
1471 return false;
1472 }
1473
1474 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001475 const FormatToken *First = &TheLine.First.FormatTok;
1476 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001477 CharSourceRange LineRange = CharSourceRange::getCharRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001478 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
Daniel Jaspercdd06622013-05-14 10:31:09 +00001479 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001480 return touchesRanges(LineRange);
1481 }
1482
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001483 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1484 std::vector<AnnotatedLine>::iterator E) {
1485 for (; I != E; ++I) {
1486 if (I->First.FormatTok.HasUnescapedNewline)
1487 return false;
1488 if (touchesLine(*I))
1489 return true;
1490 }
1491 return false;
1492 }
1493
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001494 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1495 const FormatToken *First = &TheLine.First.FormatTok;
1496 CharSourceRange LineRange = CharSourceRange::getCharRange(
1497 First->WhiteSpaceStart,
1498 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1499 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001500 }
1501
1502 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001503 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001504 }
1505
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001506 /// \brief Add a new line and the required indent before the first Token
1507 /// of the \c UnwrappedLine if there was no structural parsing error.
1508 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001509 void formatFirstToken(const AnnotatedToken &RootToken,
1510 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001511 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001512 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001513
Daniel Jasperbbc84152013-01-29 11:27:30 +00001514 unsigned Newlines =
1515 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001516 if (Newlines == 0 && !Tok.IsFirst)
1517 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001518
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001519 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001520 // Insert extra new line before access specifiers.
1521 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1522 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1523 ++Newlines;
1524
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001525 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001526 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001527 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001528 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001529 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001530 }
1531
Alexander Kornienko116ba682013-01-14 11:34:14 +00001532 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 FormatStyle Style;
1534 Lexer &Lex;
1535 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001536 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001537 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001538 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001539};
1540
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001541tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1542 SourceManager &SourceMgr,
1543 std::vector<CharSourceRange> Ranges,
1544 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001545 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001546 OwningPtr<DiagnosticConsumer> DiagPrinter;
1547 if (DiagClient == 0) {
1548 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1549 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1550 DiagClient = DiagPrinter.get();
1551 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001552 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001553 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001554 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001555 Diagnostics.setSourceManager(&SourceMgr);
1556 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001557 return formatter.format();
1558}
1559
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001560LangOptions getFormattingLangOpts() {
1561 LangOptions LangOpts;
1562 LangOpts.CPlusPlus = 1;
1563 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001564 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001565 LangOpts.Bool = 1;
1566 LangOpts.ObjC1 = 1;
1567 LangOpts.ObjC2 = 1;
1568 return LangOpts;
1569}
1570
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001571} // namespace format
1572} // namespace clang