blob: e0142db554b7e012db08e8a27fafa771a20c28ce [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod6538332013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43 }
44};
45
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000046template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000047struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48 static void
49 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod6538332013-05-07 15:32:14 +000053 }
54};
55
56template <> struct MappingTraits<clang::format::FormatStyle> {
57 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000058 if (IO.outputting()) {
59 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60 ArrayRef<StringRef> Styles(StylesArray);
61 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62 StringRef StyleName(Styles[i]);
Alexander Kornienko006b5c82013-05-19 00:53:30 +000063 clang::format::FormatStyle PredefinedStyle;
64 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000066 IO.mapOptional("# BasedOnStyle", StyleName);
67 break;
68 }
69 }
70 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000071 StringRef BasedOnStyle;
72 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000073 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-05-19 00:53:30 +000074 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
75 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
76 return;
77 }
Alexander Kornienkod6538332013-05-07 15:32:14 +000078 }
79
80 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
81 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
82 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
83 Style.AllowAllParametersOfDeclarationOnNextLine);
84 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
85 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +000086 IO.mapOptional("AllowShortLoopsOnASingleLine",
87 Style.AllowShortLoopsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +000088 IO.mapOptional("AlwaysBreakTemplateDeclarations",
89 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +000090 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
91 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
92 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
93 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
94 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
95 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
96 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
97 IO.mapOptional("ObjCSpaceBeforeProtocolList",
98 Style.ObjCSpaceBeforeProtocolList);
99 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
100 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
101 Style.PenaltyReturnTypeOnItsOwnLine);
102 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
103 IO.mapOptional("SpacesBeforeTrailingComments",
104 Style.SpacesBeforeTrailingComments);
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000105 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000106 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000107 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000108 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000109 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000110 }
111};
112}
113}
114
Daniel Jasperf7935112012-12-03 18:12:45 +0000115namespace clang {
116namespace format {
117
Daniel Jasperf7935112012-12-03 18:12:45 +0000118FormatStyle getLLVMStyle() {
119 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000120 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000121 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000122 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000123 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000124 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000125 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000126 LLVMStyle.BinPackParameters = true;
127 LLVMStyle.ColumnLimit = 80;
128 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
129 LLVMStyle.DerivePointerBinding = false;
130 LLVMStyle.IndentCaseLabels = false;
131 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000132 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000133 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000134 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000135 LLVMStyle.PointerBindsToType = false;
136 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jaspere5777d22013-05-23 10:15:45 +0000137 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000138 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000139 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000140 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000141 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000142 return LLVMStyle;
143}
144
145FormatStyle getGoogleStyle() {
146 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000147 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000148 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000149 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000150 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000151 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000152 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000153 GoogleStyle.BinPackParameters = true;
154 GoogleStyle.ColumnLimit = 80;
155 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
156 GoogleStyle.DerivePointerBinding = true;
157 GoogleStyle.IndentCaseLabels = true;
158 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000159 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000160 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000161 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000162 GoogleStyle.PointerBindsToType = true;
163 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jaspere5777d22013-05-23 10:15:45 +0000164 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000165 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000166 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000167 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000168 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000169 return GoogleStyle;
170}
171
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000172FormatStyle getChromiumStyle() {
173 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000174 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000175 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000176 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000177 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000178 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
179 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000180 return ChromiumStyle;
181}
182
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000183FormatStyle getMozillaStyle() {
184 FormatStyle MozillaStyle = getLLVMStyle();
185 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
186 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
187 MozillaStyle.DerivePointerBinding = true;
188 MozillaStyle.IndentCaseLabels = true;
189 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
190 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
191 MozillaStyle.PointerBindsToType = true;
192 return MozillaStyle;
193}
194
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000195bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000196 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000197 *Style = getLLVMStyle();
198 else if (Name.equals_lower("chromium"))
199 *Style = getChromiumStyle();
200 else if (Name.equals_lower("mozilla"))
201 *Style = getMozillaStyle();
202 else if (Name.equals_lower("google"))
203 *Style = getGoogleStyle();
204 else
205 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000206
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000207 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000208}
209
210llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000211 if (Text.trim().empty())
212 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 llvm::yaml::Input Input(Text);
214 Input >> *Style;
215 return Input.error();
216}
217
218std::string configurationAsText(const FormatStyle &Style) {
219 std::string Text;
220 llvm::raw_string_ostream Stream(Text);
221 llvm::yaml::Output Output(Stream);
222 // We use the same mapping method for input and output, so we need a non-const
223 // reference here.
224 FormatStyle NonConstStyle = Style;
225 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000226 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000227}
228
Daniel Jasperacc33662013-02-08 08:22:00 +0000229// Returns the length of everything up to the first possible line break after
230// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000231static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000232 if (Tok.MatchingParen == NULL)
233 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000234 FormatToken *End = Tok.MatchingParen;
235 while (End->Next && !End->Next->CanBreakBefore) {
236 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000237 }
238 return End->TotalLength - Tok.TotalLength + 1;
239}
240
Daniel Jasperf7935112012-12-03 18:12:45 +0000241class UnwrappedLineFormatter {
242public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000243 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000244 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000245 const FormatToken *RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000246 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000247 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000248 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000249 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000250
Manuel Klimek1abf7892013-01-04 23:34:14 +0000251 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000252 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000253 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000254 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000255 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000256 State.NextToken = RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000257 State.Stack.push_back(
Daniel Jasper53e8d852013-05-22 08:55:55 +0000258 ParenState(FirstIndent, FirstIndent, /*AvoidBinPacking=*/ false,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000259 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000260 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000261 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000262 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000263 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000264 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000265 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000266
267 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000268 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000269
Daniel Jasper4b866272013-02-01 11:00:45 +0000270 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000271 unsigned ColumnLimit = Style.ColumnLimit;
272 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000273 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000274 ColumnLimit = getColumnLimit();
275 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000276 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000277 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000278 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000279 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000280
Daniel Jasperacc33662013-02-08 08:22:00 +0000281 // If the ObjC method declaration does not fit on a line, we should format
282 // it with one arg per line.
283 if (Line.Type == LT_ObjCMethodDecl)
284 State.Stack.back().BreakBeforeParameter = true;
285
Daniel Jasper4b866272013-02-01 11:00:45 +0000286 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000287 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000288 }
289
290private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000291 void DebugTokenState(const FormatToken &FormatTok) {
292 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000293 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000294 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000295 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000296 }
297
Daniel Jasper337816e2013-01-11 10:22:12 +0000298 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000299 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000300 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000301 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
302 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000303 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000304 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
305 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000306 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000307
Daniel Jasperf7935112012-12-03 18:12:45 +0000308 /// \brief The position to which a specific parenthesis level needs to be
309 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000310 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000311
Daniel Jaspere9de2602012-12-06 09:56:08 +0000312 /// \brief The position of the last space on each level.
313 ///
314 /// Used e.g. to break like:
315 /// functionCall(Parameter, otherCall(
316 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000317 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000318
Daniel Jaspere9de2602012-12-06 09:56:08 +0000319 /// \brief The position the first "<<" operator encountered on each level.
320 ///
321 /// Used to align "<<" operators. 0 if no such operator has been encountered
322 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000323 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000324
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000325 /// \brief Whether a newline needs to be inserted before the block's closing
326 /// brace.
327 ///
328 /// We only want to insert a newline before the closing brace if there also
329 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000330 bool BreakBeforeClosingBrace;
331
Daniel Jasperca6623b2013-01-28 12:45:14 +0000332 /// \brief The column of a \c ? in a conditional expression;
333 unsigned QuestionColumn;
334
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000335 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
336 /// lines, in this context.
337 bool AvoidBinPacking;
338
339 /// \brief Break after the next comma (or all the commas in this context if
340 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000341 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000342
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000343 /// \brief Line breaking in this context would break a formatting rule.
344 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000345
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000346 /// \brief The position of the colon in an ObjC method declaration/call.
347 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000348
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000349 /// \brief The start of the most recent function in a builder-type call.
350 unsigned StartOfFunctionCall;
351
Daniel Jasperc238c872013-04-02 14:33:13 +0000352 /// \brief If a nested name specifier was broken over multiple lines, this
353 /// contains the start column of the second line. Otherwise 0.
354 unsigned NestedNameSpecifierContinuation;
355
356 /// \brief If a call expression was broken over multiple lines, this
357 /// contains the start column of the second line. Otherwise 0.
358 unsigned CallContinuation;
359
Daniel Jaspera628c982013-04-03 13:36:17 +0000360 /// \brief The column of the first variable name in a variable declaration.
361 ///
362 /// Used to align further variables if necessary.
363 unsigned VariablePos;
364
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000365 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
366 ///
367 /// Does not need to be considered for memoization / the comparison function
368 /// as otherwise identical states will have the same fake/non-fake
369 /// \c ParenStates.
370 bool ForFakeParenthesis;
371
Daniel Jasper337816e2013-01-11 10:22:12 +0000372 bool operator<(const ParenState &Other) const {
373 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000374 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000375 if (LastSpace != Other.LastSpace)
376 return LastSpace < Other.LastSpace;
377 if (FirstLessLess != Other.FirstLessLess)
378 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000379 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
380 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000381 if (QuestionColumn != Other.QuestionColumn)
382 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000383 if (AvoidBinPacking != Other.AvoidBinPacking)
384 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000385 if (BreakBeforeParameter != Other.BreakBeforeParameter)
386 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000387 if (NoLineBreak != Other.NoLineBreak)
388 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000389 if (ColonPos != Other.ColonPos)
390 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000391 if (StartOfFunctionCall != Other.StartOfFunctionCall)
392 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000393 if (CallContinuation != Other.CallContinuation)
394 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000395 if (VariablePos != Other.VariablePos)
396 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000397 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000398 }
399 };
400
401 /// \brief The current state when indenting a unwrapped line.
402 ///
403 /// As the indenting tries different combinations this is copied by value.
404 struct LineState {
405 /// \brief The number of used columns in the current line.
406 unsigned Column;
407
408 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000409 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000410
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000411 /// \brief \c true if this line contains a continued for-loop section.
412 bool LineContainsContinuedForLoopSection;
413
Daniel Jasper400adc62013-02-08 15:28:42 +0000414 /// \brief The level of nesting inside (), [], <> and {}.
415 unsigned ParenLevel;
416
Daniel Jasper40c36c52013-02-18 11:05:07 +0000417 /// \brief The \c ParenLevel at the start of this line.
418 unsigned StartOfLineLevel;
419
Daniel Jasper32a796b2013-05-27 11:50:16 +0000420 /// \brief The lowest \c ParenLevel on the current line.
421 unsigned LowestLevelOnLine;
422
Manuel Klimek02f640a2013-02-20 15:25:48 +0000423 /// \brief The start column of the string literal, if we're in a string
424 /// literal sequence, 0 otherwise.
425 unsigned StartOfStringLiteral;
426
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 /// \brief A stack keeping track of properties applying to parenthesis
428 /// levels.
429 std::vector<ParenState> Stack;
430
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000431 /// \brief Ignore the stack of \c ParenStates for state comparison.
432 ///
433 /// In long and deeply nested unwrapped lines, the current algorithm can
434 /// be insufficient for finding the best formatting with a reasonable amount
435 /// of time and memory. Setting this flag will effectively lead to the
436 /// algorithm not analyzing some combinations. However, these combinations
437 /// rarely contain the optimal solution: In short, accepting a higher
438 /// penalty early would need to lead to different values in the \c
439 /// ParenState stack (in an otherwise identical state) and these different
440 /// values would need to lead to a significant amount of avoided penalty
441 /// later.
442 ///
443 /// FIXME: Come up with a better algorithm instead.
444 bool IgnoreStackForComparison;
445
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 /// \brief Comparison operator to be able to used \c LineState in \c map.
447 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000448 if (NextToken != Other.NextToken)
449 return NextToken < Other.NextToken;
450 if (Column != Other.Column)
451 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000452 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000453 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000454 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000455 if (ParenLevel != Other.ParenLevel)
456 return ParenLevel < Other.ParenLevel;
457 if (StartOfLineLevel != Other.StartOfLineLevel)
458 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000459 if (LowestLevelOnLine != Other.LowestLevelOnLine)
460 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000461 if (StartOfStringLiteral != Other.StartOfStringLiteral)
462 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000463 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
464 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000465 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000466 }
467 };
468
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000469 /// \brief Appends the next token to \p State and updates information
470 /// necessary for indentation.
471 ///
472 /// Puts the token on the current line if \p Newline is \c true and adds a
473 /// line break and necessary indentation otherwise.
474 ///
475 /// If \p DryRun is \c false, also creates and stores the required
476 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000477 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000478 const FormatToken &Current = *State.NextToken;
479 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000480
Daniel Jasper291f9362013-03-20 15:58:10 +0000481 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000482 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000483 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
484 State.NextToken->WhitespaceRange.getEnd()) -
485 SourceMgr.getSpellingColumnNumber(
486 State.NextToken->WhitespaceRange.getBegin());
487 State.Column += WhitespaceLength + State.NextToken->TokenLength;
488 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000489 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000490 }
491
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000492 // If we are continuing an expression, we want to indent an extra 4 spaces.
493 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000494 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000495 if (Newline) {
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000496 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000497 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000498 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000499 State.StartOfStringLiteral != 0) {
500 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000501 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000502 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000503 State.Stack.back().FirstLessLess != 0) {
504 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000505 } else if (Current.isOneOf(tok::period, tok::arrow) &&
506 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000507 if (State.Stack.back().CallContinuation == 0) {
508 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000509 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000510 } else {
511 State.Column = State.Stack.back().CallContinuation;
512 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000513 } else if (Current.Type == TT_ConditionalExpr) {
514 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000515 } else if (Previous.is(tok::comma) &&
516 State.Stack.back().VariablePos != 0) {
517 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000518 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000519 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
520 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000521 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000522 } else if (Current.Type == TT_ObjCSelectorName) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000523 if (State.Stack.back().ColonPos > Current.TokenLength) {
524 State.Column = State.Stack.back().ColonPos - Current.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000525 } else {
526 State.Column = State.Stack.back().Indent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000527 State.Stack.back().ColonPos = State.Column + Current.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000528 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000529 } else if (Current.Type == TT_StartOfName ||
530 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000531 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000532 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000533 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000534 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000535 // Ensure that we fall back to indenting 4 spaces instead of just
536 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000537 if (State.Column == FirstIndent)
538 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000539 }
540
Daniel Jasper54a86022013-02-15 11:07:25 +0000541 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000542 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000543 if ((Previous.isOneOf(tok::comma, tok::semi) &&
544 !State.Stack.back().AvoidBinPacking) ||
545 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000546 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000547 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
548 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000549
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000550 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000551 unsigned NewLines = 1;
552 if (Current.Type == TT_LineComment)
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000553 NewLines = std::max(
554 NewLines,
555 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000556 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
557 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000558 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000559
Daniel Jasper400adc62013-02-08 15:28:42 +0000560 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000561 if (Current.isOneOf(tok::arrow, tok::period) &&
562 Current.Type != TT_DesignatedInitializerPeriod)
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000563 State.Stack.back().LastSpace += Current.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000564 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000565 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000566
567 // Any break on this level means that the parent level has been broken
568 // and we need to avoid bin packing there.
569 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
570 State.Stack[i].BreakBeforeParameter = true;
571 }
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000572 const FormatToken *TokenBefore = Current.getPreviousNoneComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000573 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000574 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000575 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000576 State.Stack.back().BreakBeforeParameter = true;
577
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000578 // If we break after {, we should also break before the corresponding }.
579 if (Previous.is(tok::l_brace))
580 State.Stack.back().BreakBeforeClosingBrace = true;
581
582 if (State.Stack.back().AvoidBinPacking) {
583 // If we are breaking after '(', '{', '<', this is not bin packing
584 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000585 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
586 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000587 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
588 Line.MustBeDeclaration))
589 State.Stack.back().BreakBeforeParameter = true;
590 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000592 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000593 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000594 State.Stack.back().VariablePos == 0) {
595 State.Stack.back().VariablePos = State.Column;
596 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000597 const FormatToken *Tok = &Previous;
598 while (Tok && State.Stack.back().VariablePos >= Tok->TokenLength) {
599 State.Stack.back().VariablePos -= Tok->TokenLength;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000600 if (Tok->SpacesRequiredBefore != 0)
601 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000602 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000603 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000604 if (Previous.PartOfMultiVariableDeclStmt)
605 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
606 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000607
Daniel Jaspereef30492013-02-11 12:36:37 +0000608 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000609
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000611 Whitespaces.replaceWhitespace(Current, 0, Spaces,
612 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000614 if (Current.Type == TT_ObjCSelectorName &&
615 State.Stack.back().ColonPos == 0) {
616 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000617 State.Column + Spaces + Current.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000618 State.Stack.back().ColonPos =
619 State.Stack.back().Indent + Current.LongestObjCSelectorName;
620 else
621 State.Stack.back().ColonPos =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000622 State.Column + Spaces + Current.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000623 }
624
Daniel Jasperc04baae2013-04-10 09:49:49 +0000625 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000626 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000627 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000628 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
629 State.Stack.back().AvoidBinPacking)
630 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000631
Daniel Jaspere9de2602012-12-06 09:56:08 +0000632 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000633 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000634 // Treat the condition inside an if as if it was a second function
635 // parameter, i.e. let nested calls have an indent of 4.
636 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000637 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000638 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000639 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000640 Previous.Type == TT_ConditionalExpr ||
641 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000642 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000643 Current.FakeLParens.empty()))
644 // Always indent relative to the RHS of the expression unless this is a
645 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000646 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000647 else if (Previous.Type == TT_InheritanceColon)
648 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000649 else if (Previous.opensScope() && !Current.FakeLParens.empty())
650 // If this function has multiple parameters or a binary expression
651 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000652 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000653 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000654
Manuel Klimek1998ea22013-02-20 10:15:13 +0000655 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000656 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000657
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000658 /// \brief Mark the next token as consumed in \p State and modify its stacks
659 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000660 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000661 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000662 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000663
Daniel Jaspereead02b2013-02-14 08:42:54 +0000664 if (Current.Type == TT_InheritanceColon)
665 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000666 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
667 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000668 if (Current.is(tok::question))
669 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000670 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000671 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
672 State.Stack.back().StartOfFunctionCall =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000673 Current.LastInChainOfCalls ? 0 : State.Column + Current.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000674 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000675 // Indent 2 from the column, so:
676 // SomeClass::SomeClass()
677 // : First(...), ...
678 // Next(...)
679 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000680 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000681 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
682 State.Stack.back().AvoidBinPacking = true;
683 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000684 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000685
Daniel Jasper6bee6822013-04-08 20:33:42 +0000686 // If return returns a binary expression, align after it.
687 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
688 State.Stack.back().LastSpace = State.Column + 7;
689
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000690 // In ObjC method declaration we align on the ":" of parameters, but we need
691 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000692 if (Current.Type == TT_ObjCMethodSpecifier)
693 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000694
Daniel Jasper400adc62013-02-08 15:28:42 +0000695 // Insert scopes created by fake parenthesis.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000696 const FormatToken *Previous = Current.getPreviousNoneComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000697 // Don't add extra indentation for the first fake parenthesis after
698 // 'return', assignements or opening <({[. The indentation for these cases
699 // is special cased.
700 bool SkipFirstExtraIndent =
701 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000702 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000703 Previous->getPrecedence() == prec::Assignment));
Daniel Jasper6bee6822013-04-08 20:33:42 +0000704 for (SmallVector<prec::Level, 4>::const_reverse_iterator
705 I = Current.FakeLParens.rbegin(),
706 E = Current.FakeLParens.rend();
707 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000708 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000709 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000710 NewParenState.Indent =
711 std::max(std::max(State.Column, NewParenState.Indent),
712 State.Stack.back().LastSpace);
713
714 // Always indent conditional expressions. Never indent expression where
715 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
716 // prec::Assignment) as those have different indentation rules. Indent
717 // other expression, unless the indentation needs to be skipped.
718 if (*I == prec::Conditional ||
719 (!SkipFirstExtraIndent && *I > prec::Assignment))
720 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000721 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000722 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000723 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000724 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000725 }
726
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000727 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000728 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000729 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000730 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000731 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000732 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000733 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000734 NewIndent = Style.IndentWidth + LastSpace;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000735 const FormatToken *NextNoComment = Current.getNextNoneComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000736 AvoidBinPacking = NextNoComment &&
737 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000738 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000739 NewIndent =
740 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000741 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000742 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000743
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000744 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
745 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000746 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000747 }
748
Daniel Jasperacc33662013-02-08 08:22:00 +0000749 // If this '[' opens an ObjC call, determine whether all parameters fit into
750 // one line and put one per line if they don't.
751 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
752 Current.MatchingParen != NULL) {
753 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
754 State.Stack.back().BreakBeforeParameter = true;
755 }
756
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000757 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000758 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000759 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000760 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000761 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000762 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000763 --State.ParenLevel;
764 }
Daniel Jasper32a796b2013-05-27 11:50:16 +0000765 State.LowestLevelOnLine =
766 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper400adc62013-02-08 15:28:42 +0000767
768 // Remove scopes created by fake parenthesis.
769 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000770 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000771 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000772 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000773 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000774
Daniel Jasper47a04442013-05-13 20:50:15 +0000775 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000776 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000777 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
778 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000779 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000780 }
781
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000782 State.Column += Current.TokenLength;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000783
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000784 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000785
Manuel Klimek1998ea22013-02-20 10:15:13 +0000786 return breakProtrudingToken(Current, State, DryRun);
787 }
788
789 /// \brief If the current token sticks out over the end of the line, break
790 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000791 ///
792 /// \returns An extra penalty if a token was broken, otherwise 0.
793 ///
794 /// Note that the penalty of the token protruding the allowed line length is
795 /// already handled in \c addNextStateToQueue; the returned penalty will only
796 /// cover the cost of the additional line breaks.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000797 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000798 bool DryRun) {
799 unsigned UnbreakableTailLength = Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000800 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000801 unsigned StartColumn = State.Column - Current.TokenLength;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000802 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000803 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000804 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000805
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000806 if (Current.is(tok::string_literal) &&
807 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000808 // Only break up default narrow strings.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000809 const char *LiteralData =
810 SourceMgr.getCharacterData(Current.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000811 if (!LiteralData || *LiteralData != '"')
812 return 0;
813
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000814 Token.reset(new BreakableStringLiteral(Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000815 } else if (Current.Type == TT_BlockComment) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000816 BreakableBlockComment *BBC = new BreakableBlockComment(
817 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000818 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000819 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000820 (Current.Previous == NULL ||
821 Current.Previous->Type != TT_ImplicitStringLiteral)) {
822 Token.reset(new BreakableLineComment(Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000823 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000824 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000825 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000826 if (UnbreakableTailLength >= getColumnLimit())
827 return 0;
828 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000829
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000830 bool BreakInserted = false;
831 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000832 unsigned PositionAfterLastLineInToken = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +0000833 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
834 LineIndex != EndIndex; ++LineIndex) {
835 if (!DryRun) {
836 Token->replaceWhitespaceBefore(LineIndex, Line.InPPDirective,
837 Whitespaces);
838 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000839 unsigned TailOffset = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000840 unsigned RemainingTokenLength =
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000841 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000842 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000843 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000844 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000845 if (Split.first == StringRef::npos)
846 break;
847 assert(Split.first != 0);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000848 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000849 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek9043c742013-05-27 15:23:34 +0000850 assert(NewRemainingTokenLength < RemainingTokenLength);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000851 if (!DryRun) {
852 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
853 Whitespaces);
854 }
855 TailOffset += Split.first + Split.second;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000856 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000857 Penalty += Style.PenaltyExcessCharacter;
858 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000859 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000860 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000861 }
862
863 if (BreakInserted) {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000864 State.Column = PositionAfterLastLineInToken;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000865 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
866 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000867 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000868 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000869 return Penalty;
870 }
871
Daniel Jasper2df93312013-01-09 10:16:05 +0000872 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000873 // In preprocessor directives reserve two chars for trailing " \"
874 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000875 }
876
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000877 /// \brief An edge in the solution space from \c Previous->State to \c State,
878 /// inserting a newline dependent on the \c NewLine.
879 struct StateNode {
880 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000881 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 LineState State;
883 bool NewLine;
884 StateNode *Previous;
885 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000886
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000887 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
888 ///
889 /// In case of equal penalties, we want to prefer states that were inserted
890 /// first. During state generation we make sure that we insert states first
891 /// that break the line as late as possible.
892 typedef std::pair<unsigned, unsigned> OrderedPenalty;
893
894 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
895 /// \c State has the given \c OrderedPenalty.
896 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
897
898 /// \brief The BFS queue type.
899 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
900 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000901
902 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000903 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000904 /// This implements a variant of Dijkstra's algorithm on the graph that spans
905 /// the solution space (\c LineStates are the nodes). The algorithm tries to
906 /// find the shortest path (the one with lowest penalty) from \p InitialState
907 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000908 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000909 std::set<LineState> Seen;
910
Daniel Jasper4b866272013-02-01 11:00:45 +0000911 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000912 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000913 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
914 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
915 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000916
917 // While not empty, take first element and follow edges.
918 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000919 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000920 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000921 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000922 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000923 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000924 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000925 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000926
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000927 // Cut off the analysis of certain solutions if the analysis gets too
928 // complex. See description of IgnoreStackForComparison.
929 if (Count > 10000)
930 Node->State.IgnoreStackForComparison = true;
931
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000932 if (!Seen.insert(Node->State).second)
933 // State already examined with lower penalty.
934 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000935
Manuel Klimekaf491072013-02-13 10:54:19 +0000936 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
937 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000938 }
939
940 if (Queue.empty())
941 // We were unable to find a solution, do nothing.
942 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +0000943 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000944
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000946 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000947 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
948 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000949 }
950
951 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000952 std::deque<StateNode *> Path;
953 // We do not need a break before the initial token.
954 while (Current->Previous) {
955 Path.push_front(Current);
956 Current = Current->Previous;
957 }
958 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
959 I != E; ++I) {
960 DEBUG({
961 if ((*I)->NewLine) {
962 llvm::dbgs() << "Penalty for splitting before "
963 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
964 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
965 }
966 });
967 addTokenToState((*I)->NewLine, false, State);
968 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000969 }
970
Manuel Klimekaf491072013-02-13 10:54:19 +0000971 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000972 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000973 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000974 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000975 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
976 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000977 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000978 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000979 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000980 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000981 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000982 Penalty += PreviousNode->State.NextToken->SplitPenalty;
983
984 StateNode *Node = new (Allocator.Allocate())
985 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000986 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000987 if (Node->State.Column > getColumnLimit()) {
988 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000989 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000990 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000991
992 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
993 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000994 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000995
Daniel Jasper4b866272013-02-01 11:00:45 +0000996 /// \brief Returns \c true, if a line break after \p State is allowed.
997 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000998 const FormatToken &Current = *State.NextToken;
999 const FormatToken &Previous = *Current.Previous;
1000 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001001 if (!Current.CanBreakBefore &&
1002 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001003 State.Stack.back().BreakBeforeClosingBrace))
1004 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001005 // The opening "{" of a braced list has to be on the same line as the first
1006 // element if it is nested in another braced init list or function call.
1007 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001008 Previous.Previous &&
1009 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001010 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001011 // This prevents breaks like:
1012 // ...
1013 // SomeParameter, OtherParameter).DoSomething(
1014 // ...
1015 // As they hide "DoSomething" and are generally bad for readability.
1016 if (Previous.opensScope() &&
1017 State.LowestLevelOnLine < State.StartOfLineLevel)
1018 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001019 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001020 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001021
Daniel Jasper4b866272013-02-01 11:00:45 +00001022 /// \brief Returns \c true, if a line break after \p State is mandatory.
1023 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001024 const FormatToken &Current = *State.NextToken;
1025 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001026 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001027 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001028 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +00001029 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001030 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001031 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001032 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1033 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001034 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001035 !Current.isTrailingComment() &&
1036 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001037 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001038
1039 // If we need to break somewhere inside the LHS of a binary expression, we
1040 // should also break after the operator.
1041 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper9f82df22013-05-28 07:42:44 +00001042 Current.Type != TT_BinaryOperator && // Special case for ">>".
Daniel Jasper68d888c2013-06-03 08:42:05 +00001043 !Current.isTrailingComment() &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001044 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001045 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001046 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001047 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001048
1049 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1050 // out whether it is the first parameter. Clean this up.
1051 if (Current.Type == TT_ObjCSelectorName &&
1052 Current.LongestObjCSelectorName == 0 &&
1053 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001054 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001055 if ((Current.Type == TT_CtorInitializerColon ||
1056 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001057 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001058
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001059 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1060 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1061 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001062 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001063 }
1064
Daniel Jasper9b334242013-03-15 14:57:30 +00001065 // Returns the total number of columns required for the remaining tokens.
1066 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001067 if (State.NextToken && State.NextToken->Previous)
1068 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001069 return 0;
1070 }
1071
Daniel Jasperf7935112012-12-03 18:12:45 +00001072 FormatStyle Style;
1073 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001074 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001075 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001076 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001077 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001078
1079 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1080 QueueType Queue;
1081 // Increasing count of \c StateNode items we have created. This is used
1082 // to create a deterministic order independent of the container.
1083 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001084};
1085
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001086class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001087public:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001088 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr)
1089 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Manuel Klimek9043c742013-05-27 15:23:34 +00001090 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001091 Lex.SetKeepWhitespaceMode(true);
1092 }
1093
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001094 ArrayRef<FormatToken *> lex() {
1095 assert(Tokens.empty());
1096 do {
1097 Tokens.push_back(getNextToken());
1098 } while (Tokens.back()->Tok.isNot(tok::eof));
1099 return Tokens;
1100 }
1101
1102 IdentifierTable &getIdentTable() { return IdentTable; }
1103
1104private:
1105 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001106 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001107 // Create a synthesized second '>' token.
1108 Token Greater = FormatTok->Tok;
1109 FormatTok = new (Allocator.Allocate()) FormatToken;
1110 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001111 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001112 FormatTok->Tok.getLocation().getLocWithOffset(1);
1113 FormatTok->WhitespaceRange =
1114 SourceRange(GreaterLocation, GreaterLocation);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001115 FormatTok->TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001116 GreaterStashed = false;
1117 return FormatTok;
1118 }
1119
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001120 FormatTok = new (Allocator.Allocate()) FormatToken;
1121 Lex.LexFromRawLexer(FormatTok->Tok);
1122 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001123 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001124 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001125 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001126 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001127
1128 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001129 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001130 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001131 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001132 if (Newlines > 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001133 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001134 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001135 FormatTok->NewlinesBefore += Newlines;
1136 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1137 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001138
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001139 if (FormatTok->Tok.is(tok::eof)) {
1140 FormatTok->WhitespaceRange =
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001141 SourceRange(WhitespaceStart,
1142 WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001143 return FormatTok;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001144 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001145 Lex.LexFromRawLexer(FormatTok->Tok);
1146 Text = rawTokenText(FormatTok->Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001147 }
Manuel Klimekef920692013-01-07 07:56:50 +00001148
1149 // Now FormatTok is the next non-whitespace token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001150 FormatTok->TokenLength = Text.size();
Manuel Klimekef920692013-01-07 07:56:50 +00001151
Manuel Klimek9043c742013-05-27 15:23:34 +00001152 TrailingWhitespace = 0;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001153 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek9043c742013-05-27 15:23:34 +00001154 TrailingWhitespace = Text.size() - Text.rtrim().size();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001155 FormatTok->TokenLength -= TrailingWhitespace;
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001156 }
1157
Manuel Klimek1abf7892013-01-04 23:34:14 +00001158 // In case the token starts with escaped newlines, we want to
1159 // take them into account as whitespace - this pattern is quite frequent
1160 // in macro definitions.
1161 // FIXME: What do we want to do with other escaped spaces, and escaped
1162 // spaces or newlines in the middle of tokens?
1163 // FIXME: Add a more explicit test.
1164 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001165 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001166 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001167 WhitespaceLength += 2;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001168 FormatTok->TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001169 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001170 }
1171
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001172 if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001173 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001174 FormatTok->Tok.setIdentifierInfo(&Info);
1175 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001176 }
1177
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001178 if (FormatTok->Tok.is(tok::greatergreater)) {
1179 FormatTok->Tok.setKind(tok::greater);
1180 FormatTok->TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001181 GreaterStashed = true;
1182 }
1183
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001184 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001185 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001186 FormatTok->TokenText = StringRef(
1187 SourceMgr.getCharacterData(FormatTok->getStartOfNonWhitespace()),
1188 FormatTok->TokenLength);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001189 return FormatTok;
1190 }
1191
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001192 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001193 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001194 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001195 Lexer &Lex;
1196 SourceManager &SourceMgr;
1197 IdentifierTable IdentTable;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001198 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1199 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001200
1201 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001202 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001203 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1204 Tok.getLength());
1205 }
1206};
1207
Daniel Jasperf7935112012-12-03 18:12:45 +00001208class Formatter : public UnwrappedLineConsumer {
1209public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001210 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001211 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001212 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001213 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001214
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001215 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001216
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001217 tooling::Replacements format() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001218 FormatTokenLexer Tokens(Lex, SourceMgr);
1219
1220 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001221 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001222 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1223 Tokens.getIdentTable().get("in"));
1224 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1225 Annotator.annotate(AnnotatedLines[i]);
1226 }
1227 deriveLocalStyle();
1228 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1229 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1230 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001231
1232 // Adapt level to the next line if this is a comment.
1233 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001234 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001235 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001236 if (NextNoneCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
1237 !AnnotatedLines[i].First->Next)
Daniel Jasperb67cc422013-04-09 17:46:55 +00001238 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1239 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001240 NextNoneCommentLine =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001241 AnnotatedLines[i].First->isNot(tok::r_brace) ? &AnnotatedLines[i]
1242 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001243 }
1244
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001245 std::vector<int> IndentForLevel;
1246 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001247 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001248 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001249 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1250 E = AnnotatedLines.end();
1251 I != E; ++I) {
1252 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001253 const FormatToken *FirstTok = TheLine.First;
1254 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001255
1256 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001257 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001258 FormatPPDirective = false;
1259 if (!FormatPPDirective && TheLine.InPPDirective &&
1260 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1261 FormatPPDirective = true;
1262
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001263 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001264 while (IndentForLevel.size() <= TheLine.Level)
1265 IndentForLevel.push_back(-1);
1266 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001267 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1268 if (static_cast<int>(Indent) + Offset >= 0)
1269 Indent += Offset;
1270 tryFitMultipleLinesInOne(Indent, I, E);
1271
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001272 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001273 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001274 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001275 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001276 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001277 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001278 }
1279 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001280 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001281 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001282 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001283 // Insert a break even if there is a structural error in case where
1284 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001285 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001286 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001287 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001288 } else {
1289 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001290 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1291 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001292 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001293 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001294 TheLine.First, Whitespaces);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001295 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001296 IndentForLevel[TheLine.Level] = LevelIndent;
1297 PreviousLineWasTouched = true;
1298 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001299 // Format the first token if necessary, and notify the WhitespaceManager
1300 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001301 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1302 Tok = Tok->Next) {
1303 if (Tok == TheLine.First &&
1304 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1305 unsigned LevelIndent =
1306 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001307 // Remove trailing whitespace of the previous line if it was
1308 // touched.
1309 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1310 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1311 TheLine.InPPDirective);
1312 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001313 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001314 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001315
Manuel Klimek4fe43002013-05-22 12:51:29 +00001316 if (static_cast<int>(LevelIndent) - Offset >= 0)
1317 LevelIndent -= Offset;
1318 if (Tok->isNot(tok::comment))
1319 IndentForLevel[TheLine.Level] = LevelIndent;
1320 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001321 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001322 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001323 }
1324 // If we did not reformat this unwrapped line, the column at the end of
1325 // the last token is unchanged - thus, we can calculate the end of the
1326 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001327 PreviousLineWasTouched = false;
1328 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001329 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001330 }
1331 return Whitespaces.generateReplacements();
1332 }
1333
1334private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001335 void deriveLocalStyle() {
1336 unsigned CountBoundToVariable = 0;
1337 unsigned CountBoundToType = 0;
1338 bool HasCpp03IncompatibleFormat = false;
1339 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001340 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001341 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001342 FormatToken *Tok = AnnotatedLines[i].First->Next;
1343 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001344 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001345 bool SpacesBefore =
1346 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1347 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1348 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001349 if (SpacesBefore && !SpacesAfter)
1350 ++CountBoundToVariable;
1351 else if (!SpacesBefore && SpacesAfter)
1352 ++CountBoundToType;
1353 }
1354
Daniel Jasper400adc62013-02-08 15:28:42 +00001355 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001356 Tok->Previous->Type == TT_TemplateCloser &&
1357 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001358 HasCpp03IncompatibleFormat = true;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001359 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001360 }
1361 }
1362 if (Style.DerivePointerBinding) {
1363 if (CountBoundToType > CountBoundToVariable)
1364 Style.PointerBindsToType = true;
1365 else if (CountBoundToType < CountBoundToVariable)
1366 Style.PointerBindsToType = false;
1367 }
1368 if (Style.Standard == FormatStyle::LS_Auto) {
1369 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1370 : FormatStyle::LS_Cpp03;
1371 }
1372 }
1373
Manuel Klimekb95f5452013-02-08 17:38:27 +00001374 /// \brief Get the indent of \p Level from \p IndentForLevel.
1375 ///
1376 /// \p IndentForLevel must contain the indent for the level \c l
1377 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1378 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001379 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001380 if (IndentForLevel[Level] != -1)
1381 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001382 if (Level == 0)
1383 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001384 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001385 }
1386
1387 /// \brief Get the offset of the line relatively to the level.
1388 ///
1389 /// For example, 'public:' labels in classes are offset by 1 or 2
1390 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001391 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001392 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001393 return Style.AccessModifierOffset;
1394 return 0;
1395 }
1396
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001397 /// \brief Tries to merge lines into one.
1398 ///
1399 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1400 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001401 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001402 std::vector<AnnotatedLine>::iterator &I,
1403 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001404 // We can never merge stuff if there are trailing line comments.
1405 if (I->Last->Type == TT_LineComment)
1406 return;
1407
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001408 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001409 // If we already exceed the column limit, we set 'Limit' to 0. The different
1410 // tryMerge..() functions can then decide whether to still do merging.
1411 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001412
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001413 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001414 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001415
Daniel Jasperabca58c2013-05-15 14:09:55 +00001416 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001417 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001418 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001419 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001420 tryMergeSimpleControlStatement(I, E, Limit);
1421 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001422 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001423 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001424 } else if (I->InPPDirective &&
1425 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001426 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001427 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001428 }
1429
Daniel Jasper39825ea2013-01-14 15:40:57 +00001430 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1431 std::vector<AnnotatedLine>::iterator E,
1432 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001433 if (Limit == 0)
1434 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001435 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001436 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001437 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001438 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001439 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001440 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001441 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001442 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001443 join(Line, *(++I));
1444 }
1445
Daniel Jasper3a685df2013-05-16 12:12:21 +00001446 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1447 std::vector<AnnotatedLine>::iterator E,
1448 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001449 if (Limit == 0)
1450 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001451 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001452 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001453 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001454 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001455 if (Line.Last->isNot(tok::r_paren))
1456 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001457 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001458 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001459 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1460 tok::kw_while) ||
1461 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001462 return;
1463 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001464 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1465 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001466 return;
1467 join(Line, *(++I));
1468 }
1469
1470 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001471 std::vector<AnnotatedLine>::iterator E,
1472 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001473 // No merging if the brace already is on the next line.
1474 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1475 return;
1476
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001477 // First, check that the current line allows merging. This is the case if
1478 // we're not in a control flow statement and the last token is an opening
1479 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001480 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001481 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1482 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001483 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001484 // This gets rid of all ObjC @ keywords and methods.
1485 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001486 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001487
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001488 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001489 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
1490 (Tok->getNextNoneComment() == NULL ||
1491 Tok->getNextNoneComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001492 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001493 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001494 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001495 join(Line, *(I + 1));
1496 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001497 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001498 // Check that we still have three lines and they fit into the limit.
1499 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1500 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001501 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001502
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001503 // Second, check that the next line does not contain any braces - if it
1504 // does, readability declines when putting it into a single line.
1505 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1506 return;
1507 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001508 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001509 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001510 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001511 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001512
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001513 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001514 Tok = (I + 2)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001515 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001516 Tok->MustBreakBefore)
1517 return;
1518
1519 join(Line, *(I + 1));
1520 join(Line, *(I + 2));
1521 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001522 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001523 }
1524
1525 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1526 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001527 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1528 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001529 }
1530
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001531 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001532 assert(!A.Last->Next);
1533 assert(!B.First->Previous);
1534 A.Last->Next = B.First;
1535 B.First->Previous = A.Last;
1536 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1537 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1538 Tok->TotalLength += LengthA;
1539 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001540 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001541 }
1542
Daniel Jasper97b89482013-03-13 07:49:51 +00001543 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001544 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1545 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1546 Ranges[i].getBegin()) &&
1547 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1548 Range.getBegin()))
1549 return true;
1550 }
1551 return false;
1552 }
1553
1554 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001555 const FormatToken *First = TheLine.First;
1556 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001557 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001558 First->WhitespaceRange.getBegin().getLocWithOffset(
1559 First->LastNewlineOffset),
Daniel Jaspercdd06622013-05-14 10:31:09 +00001560 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001561 return touchesRanges(LineRange);
1562 }
1563
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001564 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1565 std::vector<AnnotatedLine>::iterator E) {
1566 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001567 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001568 return false;
1569 if (touchesLine(*I))
1570 return true;
1571 }
1572 return false;
1573 }
1574
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001575 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001576 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001577 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001578 First->WhitespaceRange.getBegin(),
1579 First->WhitespaceRange.getBegin().getLocWithOffset(
1580 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001581 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001582 }
1583
1584 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001585 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001586 }
1587
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001588 /// \brief Add a new line and the required indent before the first Token
1589 /// of the \c UnwrappedLine if there was no structural parsing error.
1590 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001591 void formatFirstToken(const FormatToken &RootToken,
1592 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001593 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001594 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001595 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1596 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001597 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001598
Manuel Klimek4fe43002013-05-22 12:51:29 +00001599 // Insert extra new line before access specifiers.
1600 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001601 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001602 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001603
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001604 Whitespaces.replaceWhitespace(
1605 RootToken, Newlines, Indent, Indent,
1606 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001607 }
1608
Daniel Jasperf7935112012-12-03 18:12:45 +00001609 FormatStyle Style;
1610 Lexer &Lex;
1611 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001612 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001613 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001614 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001615};
1616
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001617tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1618 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001619 std::vector<CharSourceRange> Ranges) {
1620 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001621 return formatter.format();
1622}
1623
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001624tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1625 std::vector<tooling::Range> Ranges,
1626 StringRef FileName) {
1627 FileManager Files((FileSystemOptions()));
1628 DiagnosticsEngine Diagnostics(
1629 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1630 new DiagnosticOptions);
1631 SourceManager SourceMgr(Diagnostics, Files);
1632 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1633 const clang::FileEntry *Entry =
1634 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1635 SourceMgr.overrideFileContents(Entry, Buf);
1636 FileID ID =
1637 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1638 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1639 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1640 std::vector<CharSourceRange> CharRanges;
1641 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1642 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1643 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1644 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1645 }
1646 return reformat(Style, Lex, SourceMgr, CharRanges);
1647}
1648
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001649LangOptions getFormattingLangOpts() {
1650 LangOptions LangOpts;
1651 LangOpts.CPlusPlus = 1;
1652 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001653 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001654 LangOpts.Bool = 1;
1655 LangOpts.ObjC1 = 1;
1656 LangOpts.ObjC2 = 1;
1657 return LangOpts;
1658}
1659
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001660} // namespace format
1661} // namespace clang