blob: 3ae279216f8ee1dec8af567a8e19ebd5073af0b8 [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod71ec162013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-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 Jasper1fb8d882013-05-14 09:30:02 +000046template <>
Manuel Klimek44135b82013-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 Kornienkod71ec162013-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 Kornienkodd256312013-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 Kornienko885f87b2013-05-19 00:53:30 +000063 clang::format::FormatStyle PredefinedStyle;
64 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000066 IO.mapOptional("# BasedOnStyle", StyleName);
67 break;
68 }
69 }
70 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000071 StringRef BasedOnStyle;
72 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000073 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-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 Kornienkod71ec162013-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 Jasperf11bbb92013-05-16 12:12:21 +000086 IO.mapOptional("AllowShortLoopsOnASingleLine",
87 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +000088 IO.mapOptional("AlwaysBreakTemplateDeclarations",
89 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienkod71ec162013-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 Jasper1bee0732013-05-23 18:05:18 +0000105 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000106 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000107 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000108 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000109 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000110 }
111};
112}
113}
114
Daniel Jasperbac016b2012-12-03 18:12:45 +0000115namespace clang {
116namespace format {
117
Daniel Jasperbac016b2012-12-03 18:12:45 +0000118FormatStyle getLLVMStyle() {
119 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000120 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000121 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000122 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000123 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000124 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000125 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-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 Weber5f500df2013-01-10 20:12:55 +0000132 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000133 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000134 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000135 LLVMStyle.PointerBindsToType = false;
136 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000137 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000138 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000139 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000140 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000141 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000142 return LLVMStyle;
143}
144
145FormatStyle getGoogleStyle() {
146 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000147 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000148 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000149 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000150 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000151 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000152 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-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 Weber5f500df2013-01-10 20:12:55 +0000159 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +0000160 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000161 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000162 GoogleStyle.PointerBindsToType = true;
163 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000164 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000165 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000166 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000167 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000168 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000169 return GoogleStyle;
170}
171
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000172FormatStyle getChromiumStyle() {
173 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000174 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000175 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000176 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000177 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000178 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
179 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000180 return ChromiumStyle;
181}
182
Alexander Kornienkofb594862013-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 Kornienko885f87b2013-05-19 00:53:30 +0000195bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000196 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-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 Kornienkod71ec162013-05-07 15:32:14 +0000206
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000207 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000208}
209
210llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000211 if (Text.trim().empty())
212 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-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 Kornienko2b6acb62013-05-13 12:56:35 +0000226 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000227}
228
Daniel Jasperce3d1a62013-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 Klimekb3987012013-05-29 14:47:47 +0000231static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000232 if (Tok.MatchingParen == NULL)
233 return 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000234 FormatToken *End = Tok.MatchingParen;
235 while (End->Next && !End->Next->CanBreakBefore) {
236 End = End->Next;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000237 }
238 return End->TotalLength - Tok.TotalLength + 1;
239}
240
Daniel Jasperbac016b2012-12-03 18:12:45 +0000241class UnwrappedLineFormatter {
242public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000243 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000244 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimekb3987012013-05-29 14:47:47 +0000245 const FormatToken *RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000246 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000247 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000248 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000249 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250
Manuel Klimekd4397b92013-01-04 23:34:14 +0000251 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000252 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000253 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000254 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000255 State.Column = FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000256 State.NextToken = RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000257 State.Stack.push_back(
Daniel Jasper24e19e42013-05-22 08:55:55 +0000258 ParenState(FirstIndent, FirstIndent, /*AvoidBinPacking=*/ false,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000259 /*NoLineBreak=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000260 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000261 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000262 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000263 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper259a0382013-05-27 11:50:16 +0000264 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000265 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000266
267 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000268 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000270 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000271 unsigned ColumnLimit = Style.ColumnLimit;
272 if (NextLine && NextLine->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000273 !NextLine->First->HasUnescapedNewline)
Daniel Jaspera4d46212013-02-28 11:05:57 +0000274 ColumnLimit = getColumnLimit();
275 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000276 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000277 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000278 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000279 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000280
Daniel Jasperce3d1a62013-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 Jasper68ef0df2013-02-01 11:00:45 +0000286 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000287 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000288 }
289
290private:
Manuel Klimekb3987012013-05-29 14:47:47 +0000291 void DebugTokenState(const FormatToken &FormatTok) {
292 const Token &Tok = FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000293 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000294 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000295 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000296 }
297
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000298 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000299 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000300 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000301 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
302 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000303 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000304 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
305 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000306 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000307
Daniel Jasperbac016b2012-12-03 18:12:45 +0000308 /// \brief The position to which a specific parenthesis level needs to be
309 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000310 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000317 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000318
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000323 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000324
Manuel Klimekc8c8a472013-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 Jasper604eb4c2013-01-11 10:22:12 +0000330 bool BreakBeforeClosingBrace;
331
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000332 /// \brief The column of a \c ? in a conditional expression;
333 unsigned QuestionColumn;
334
Daniel Jasperf343cab2013-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 Jasperce3d1a62013-02-08 08:22:00 +0000341 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000342
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000343 /// \brief Line breaking in this context would break a formatting rule.
344 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000345
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000346 /// \brief The position of the colon in an ObjC method declaration/call.
347 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000348
Daniel Jasper24849712013-03-01 16:48:32 +0000349 /// \brief The start of the most recent function in a builder-type call.
350 unsigned StartOfFunctionCall;
351
Daniel Jasper37911302013-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 Jasper8ed9f2b2013-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 Jasperc3df5ff2013-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 Jasper604eb4c2013-01-11 10:22:12 +0000372 bool operator<(const ParenState &Other) const {
373 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000374 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-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 Jasper7e9bf8c2013-01-11 11:37:55 +0000379 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
380 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000381 if (QuestionColumn != Other.QuestionColumn)
382 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000383 if (AvoidBinPacking != Other.AvoidBinPacking)
384 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000385 if (BreakBeforeParameter != Other.BreakBeforeParameter)
386 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000387 if (NoLineBreak != Other.NoLineBreak)
388 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000389 if (ColonPos != Other.ColonPos)
390 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000391 if (StartOfFunctionCall != Other.StartOfFunctionCall)
392 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000393 if (CallContinuation != Other.CallContinuation)
394 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000395 if (VariablePos != Other.VariablePos)
396 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000397 return false;
Daniel Jasper604eb4c2013-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 Klimekb3987012013-05-29 14:47:47 +0000409 const FormatToken *NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000410
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000411 /// \brief \c true if this line contains a continued for-loop section.
412 bool LineContainsContinuedForLoopSection;
413
Daniel Jasper29f123b2013-02-08 15:28:42 +0000414 /// \brief The level of nesting inside (), [], <> and {}.
415 unsigned ParenLevel;
416
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000417 /// \brief The \c ParenLevel at the start of this line.
418 unsigned StartOfLineLevel;
419
Daniel Jasper259a0382013-05-27 11:50:16 +0000420 /// \brief The lowest \c ParenLevel on the current line.
421 unsigned LowestLevelOnLine;
422
Manuel Klimekb56b6d12013-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 Jasper604eb4c2013-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 Jasper54b4e442013-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 Jasper604eb4c2013-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 Jasperd7896702013-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 Jasperd7896702013-02-19 09:28:55 +0000452 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000453 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000454 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-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 Jasper259a0382013-05-27 11:50:16 +0000459 if (LowestLevelOnLine != Other.LowestLevelOnLine)
460 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000461 if (StartOfStringLiteral != Other.StartOfStringLiteral)
462 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000463 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
464 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000465 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000466 }
467 };
468
Daniel Jasper20409152012-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 Klimek8092a942013-02-20 10:15:13 +0000477 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000478 const FormatToken &Current = *State.NextToken;
479 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000480
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000481 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000482 // FIXME: Is this correct?
Manuel Klimekb3987012013-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 Klimek8092a942013-02-20 10:15:13 +0000489 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000490 }
491
Daniel Jasper3776ef32013-04-03 07:21:51 +0000492 // If we are continuing an expression, we want to indent an extra 4 spaces.
493 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000494 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 if (Newline) {
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000496 if (Current.is(tok::r_brace)) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000497 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000498 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000499 State.StartOfStringLiteral != 0) {
500 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000501 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000502 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000503 State.Stack.back().FirstLessLess != 0) {
504 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000505 } else if (Current.isOneOf(tok::period, tok::arrow) &&
506 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000507 if (State.Stack.back().CallContinuation == 0) {
508 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000509 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000510 } else {
511 State.Column = State.Stack.back().CallContinuation;
512 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000513 } else if (Current.Type == TT_ConditionalExpr) {
514 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-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 Jasper3c08a812013-02-24 18:54:32 +0000518 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000519 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
520 Line.StartsDefinition)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000521 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000522 } else if (Current.Type == TT_ObjCSelectorName) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000523 if (State.Stack.back().ColonPos > Current.TokenLength) {
524 State.Column = State.Stack.back().ColonPos - Current.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000525 } else {
526 State.Column = State.Stack.back().Indent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000527 State.Stack.back().ColonPos = State.Column + Current.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000528 }
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000529 } else if (Current.Type == TT_StartOfName ||
530 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000531 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000532 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000533 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000534 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000535 // Ensure that we fall back to indenting 4 spaces instead of just
536 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000537 if (State.Column == FirstIndent)
538 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000539 }
540
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000541 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000542 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000543 if ((Previous.isOneOf(tok::comma, tok::semi) &&
544 !State.Stack.back().AvoidBinPacking) ||
545 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000546 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000547 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
548 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000549
Manuel Klimek060143e2013-01-02 18:33:23 +0000550 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000551 unsigned NewLines = 1;
552 if (Current.Type == TT_LineComment)
Manuel Klimekb3987012013-05-29 14:47:47 +0000553 NewLines = std::max(
554 NewLines,
555 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000556 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
557 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000558 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000559
Daniel Jasper29f123b2013-02-08 15:28:42 +0000560 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000561 if (Current.isOneOf(tok::arrow, tok::period) &&
562 Current.Type != TT_DesignatedInitializerPeriod)
Manuel Klimekb3987012013-05-29 14:47:47 +0000563 State.Stack.back().LastSpace += Current.TokenLength;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000564 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper259a0382013-05-27 11:50:16 +0000565 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-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 Klimekb3987012013-05-29 14:47:47 +0000572 const FormatToken *TokenBefore = Current.getPreviousNoneComment();
Daniel Jasper01218ff2013-04-15 22:36:37 +0000573 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000574 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000575 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000576 State.Stack.back().BreakBeforeParameter = true;
577
Daniel Jasper237d4c12013-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 Jasperd741f022013-05-14 20:39:56 +0000585 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
586 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000587 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
588 Line.MustBeDeclaration))
589 State.Stack.back().BreakBeforeParameter = true;
590 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000592 if (Current.is(tok::equal) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000593 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasperadc0f092013-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 Klimekb3987012013-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 Jasperadc0f092013-04-05 09:38:50 +0000600 if (Tok->SpacesRequiredBefore != 0)
601 break;
Manuel Klimekb3987012013-05-29 14:47:47 +0000602 Tok = Tok->Previous;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000603 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000604 if (Previous.PartOfMultiVariableDeclStmt)
605 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
606 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000607
Daniel Jasper729a7432013-02-11 12:36:37 +0000608 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000609
Daniel Jasperbac016b2012-12-03 18:12:45 +0000610 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000611 Whitespaces.replaceWhitespace(Current, 0, Spaces,
612 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000613
Daniel Jasper63d7ced2013-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 Klimekb3987012013-05-29 14:47:47 +0000617 State.Column + Spaces + Current.TokenLength)
Daniel Jasper63d7ced2013-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 Klimekb3987012013-05-29 14:47:47 +0000622 State.Column + Spaces + Current.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000623 }
624
Daniel Jasperac3223e2013-04-10 09:49:49 +0000625 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000626 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000627 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-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 Jasper0df6acd2013-01-16 14:59:02 +0000631
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000632 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000633 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-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 Jasperf9955d32013-03-20 12:37:50 +0000637 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000638 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000639 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000640 Previous.Type == TT_ConditionalExpr ||
641 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000642 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper512843a2013-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 Jasperae8699b2013-01-28 09:35:24 +0000646 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000647 else if (Previous.Type == TT_InheritanceColon)
648 State.Stack.back().Indent = State.Column;
Daniel Jasper11e13802013-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 Jasper986e17f2013-01-28 07:35:34 +0000652 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000653 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000654
Manuel Klimek8092a942013-02-20 10:15:13 +0000655 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000656 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000657
Daniel Jasper20409152012-12-04 14:54:30 +0000658 /// \brief Mark the next token as consumed in \p State and modify its stacks
659 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000660 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000661 const FormatToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000662 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000663
Daniel Jasper6cabab42013-02-14 08:42:54 +0000664 if (Current.Type == TT_InheritanceColon)
665 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000666 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
667 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000668 if (Current.is(tok::question))
669 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000670 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000671 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
672 State.Stack.back().StartOfFunctionCall =
Manuel Klimekb3987012013-05-29 14:47:47 +0000673 Current.LastInChainOfCalls ? 0 : State.Column + Current.TokenLength;
Daniel Jasper7d812812013-02-21 15:00:29 +0000674 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000675 // Indent 2 from the column, so:
676 // SomeClass::SomeClass()
677 // : First(...), ...
678 // Next(...)
679 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000680 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000681 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
682 State.Stack.back().AvoidBinPacking = true;
683 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000684 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000685
Daniel Jasperbf71ba22013-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 Jasper3776ef32013-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 Jasper37911302013-04-02 14:33:13 +0000692 if (Current.Type == TT_ObjCMethodSpecifier)
693 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000694
Daniel Jasper29f123b2013-02-08 15:28:42 +0000695 // Insert scopes created by fake parenthesis.
Manuel Klimekb3987012013-05-29 14:47:47 +0000696 const FormatToken *Previous = Current.getPreviousNoneComment();
Daniel Jasperbf71ba22013-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 Jasperac3223e2013-04-10 09:49:49 +0000702 (Previous && (Previous->opensScope() ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000703 Previous->getPrecedence() == prec::Assignment));
Daniel Jasperbf71ba22013-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 Jasper29f123b2013-02-08 15:28:42 +0000708 ParenState NewParenState = State.Stack.back();
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000709 NewParenState.ForFakeParenthesis = true;
Daniel Jasperbf71ba22013-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 Jasperac3223e2013-04-10 09:49:49 +0000721 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000722 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000723 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000724 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000725 }
726
Daniel Jaspercf225b62012-12-24 13:43:52 +0000727 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000728 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000729 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000730 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000731 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000732 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000733 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000734 NewIndent = Style.IndentWidth + LastSpace;
Manuel Klimekb3987012013-05-29 14:47:47 +0000735 const FormatToken *NextNoComment = Current.getNextNoneComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000736 AvoidBinPacking = NextNoComment &&
737 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000738 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000739 NewIndent =
740 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000741 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000742 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000743
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000744 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
745 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000746 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000747 }
748
Daniel Jasperce3d1a62013-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 Jaspercf225b62012-12-24 13:43:52 +0000757 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000758 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000759 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000760 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000761 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000762 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000763 --State.ParenLevel;
764 }
Daniel Jasper259a0382013-05-27 11:50:16 +0000765 State.LowestLevelOnLine =
766 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper29f123b2013-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 Jasperabfc9c12013-04-04 19:31:00 +0000770 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000771 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000772 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000773 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000774
Daniel Jasper27c7f542013-05-13 20:50:15 +0000775 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000776 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000777 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
778 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000779 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000780 }
781
Manuel Klimekb3987012013-05-29 14:47:47 +0000782 State.Column += Current.TokenLength;
Manuel Klimek8092a942013-02-20 10:15:13 +0000783
Manuel Klimekb3987012013-05-29 14:47:47 +0000784 State.NextToken = State.NextToken->Next;
Manuel Klimek2851c162013-01-10 14:36:46 +0000785
Manuel Klimek8092a942013-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 Klimek2a9805d2013-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 Klimekb3987012013-05-29 14:47:47 +0000797 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000798 bool DryRun) {
799 unsigned UnbreakableTailLength = Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000800 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimekb3987012013-05-29 14:47:47 +0000801 unsigned StartColumn = State.Column - Current.TokenLength;
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000802 unsigned OriginalStartColumn =
Manuel Klimekb3987012013-05-29 14:47:47 +0000803 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000804 1;
Manuel Klimekde008c02013-05-27 15:23:34 +0000805
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000806 if (Current.is(tok::string_literal) &&
807 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000808 // Only break up default narrow strings.
Manuel Klimekb3987012013-05-29 14:47:47 +0000809 const char *LiteralData =
810 SourceMgr.getCharacterData(Current.getStartOfNonWhitespace());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000811 if (!LiteralData || *LiteralData != '"')
812 return 0;
813
Manuel Klimekb3987012013-05-29 14:47:47 +0000814 Token.reset(new BreakableStringLiteral(Current, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000815 } else if (Current.Type == TT_BlockComment) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000816 BreakableBlockComment *BBC = new BreakableBlockComment(
817 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000818 Token.reset(BBC);
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000819 } else if (Current.Type == TT_LineComment &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000820 (Current.Previous == NULL ||
821 Current.Previous->Type != TT_ImplicitStringLiteral)) {
822 Token.reset(new BreakableLineComment(Current, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000823 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000824 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000825 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000826 if (UnbreakableTailLength >= getColumnLimit())
827 return 0;
828 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000829
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000830 bool BreakInserted = false;
831 unsigned Penalty = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000832 unsigned PositionAfterLastLineInToken = 0;
Manuel Klimekde008c02013-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 Kornienko70ce7882013-04-15 14:28:00 +0000839 unsigned TailOffset = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000840 unsigned RemainingTokenLength =
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000841 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000842 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000843 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000844 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000845 if (Split.first == StringRef::npos)
846 break;
847 assert(Split.first != 0);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000848 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko919398b2013-04-17 17:34:05 +0000849 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimekde008c02013-05-27 15:23:34 +0000850 assert(NewRemainingTokenLength < RemainingTokenLength);
Alexander Kornienko70ce7882013-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 Klimek2a9805d2013-05-14 09:04:24 +0000856 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000857 Penalty += Style.PenaltyExcessCharacter;
858 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000859 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000860 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000861 }
862
863 if (BreakInserted) {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000864 State.Column = PositionAfterLastLineInToken;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000865 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
866 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000867 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000868 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000869 return Penalty;
870 }
871
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000872 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000873 // In preprocessor directives reserve two chars for trailing " \"
874 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000875 }
876
Manuel Klimek32a2fd72013-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 Jasperf11a7052013-02-21 21:33:55 +0000881 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000882 LineState State;
883 bool NewLine;
884 StateNode *Previous;
885 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000886
Manuel Klimek32a2fd72013-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 Jasper68ef0df2013-02-01 11:00:45 +0000901
902 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000903 ///
Daniel Jasper68ef0df2013-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 Klimeke573c3f2013-05-22 12:51:29 +0000908 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000909 std::set<LineState> Seen;
910
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000911 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000912 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000913 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
914 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
915 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000916
917 // While not empty, take first element and follow edges.
918 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000919 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000920 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000921 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000922 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000923 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000924 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000925 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000926
Daniel Jasper54b4e442013-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 Klimek32a2fd72013-02-13 10:46:36 +0000932 if (!Seen.insert(Node->State).second)
933 // State already examined with lower penalty.
934 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000935
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000936 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
937 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-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 Klimeke573c3f2013-05-22 12:51:29 +0000943 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000944
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000945 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000946 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000947 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
948 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000949 }
950
951 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-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 Jasper68ef0df2013-02-01 11:00:45 +0000969 }
970
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000971 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000972 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000973 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000974 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000975 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
976 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000977 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000978 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000979 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000980 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000981 if (NewLine)
Manuel Klimek32a2fd72013-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 Klimek8092a942013-02-20 10:15:13 +0000986 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000987 if (Node->State.Column > getColumnLimit()) {
988 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000989 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000990 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000991
992 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
993 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000994 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000995
Daniel Jasper68ef0df2013-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 Klimekb3987012013-05-29 14:47:47 +0000998 const FormatToken &Current = *State.NextToken;
999 const FormatToken &Previous = *Current.Previous;
1000 assert(&Previous == Current.Previous);
Daniel Jasper399914b2013-05-17 09:35:01 +00001001 if (!Current.CanBreakBefore &&
1002 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001003 State.Stack.back().BreakBeforeClosingBrace))
1004 return false;
Daniel Jasper399914b2013-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 Klimekb3987012013-05-29 14:47:47 +00001008 Previous.Previous &&
1009 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper399914b2013-05-17 09:35:01 +00001010 return false;
Daniel Jasper259a0382013-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 Jasper001bf4e2013-04-22 07:59:53 +00001019 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001020 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001021
Daniel Jasper68ef0df2013-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 Klimekb3987012013-05-29 14:47:47 +00001024 const FormatToken &Current = *State.NextToken;
1025 const FormatToken &Previous = *Current.Previous;
Daniel Jasper11e13802013-05-08 14:12:04 +00001026 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001027 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001028 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001029 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001030 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001031 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001032 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1033 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001034 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001035 !Current.isTrailingComment() &&
1036 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001037 return true;
Daniel Jasper11e13802013-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 Jasper69c43712013-05-28 07:42:44 +00001042 Current.Type != TT_BinaryOperator && // Special case for ">>".
Daniel Jasper11e13802013-05-08 14:12:04 +00001043 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001044 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001045 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001046 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001047
1048 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1049 // out whether it is the first parameter. Clean this up.
1050 if (Current.Type == TT_ObjCSelectorName &&
1051 Current.LongestObjCSelectorName == 0 &&
1052 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001053 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001054 if ((Current.Type == TT_CtorInitializerColon ||
1055 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001056 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001057
Daniel Jasper33f4b902013-05-15 09:35:08 +00001058 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1059 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1060 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001061 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001062 }
1063
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001064 // Returns the total number of columns required for the remaining tokens.
1065 unsigned getRemainingLength(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001066 if (State.NextToken && State.NextToken->Previous)
1067 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001068 return 0;
1069 }
1070
Daniel Jasperbac016b2012-12-03 18:12:45 +00001071 FormatStyle Style;
1072 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001073 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001074 const unsigned FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +00001075 const FormatToken *RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001076 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001077
1078 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1079 QueueType Queue;
1080 // Increasing count of \c StateNode items we have created. This is used
1081 // to create a deterministic order independent of the container.
1082 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001083};
1084
Manuel Klimek96e888b2013-05-28 11:55:06 +00001085class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001086public:
Manuel Klimek96e888b2013-05-28 11:55:06 +00001087 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr)
1088 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Manuel Klimekde008c02013-05-27 15:23:34 +00001089 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001090 Lex.SetKeepWhitespaceMode(true);
1091 }
1092
Manuel Klimek96e888b2013-05-28 11:55:06 +00001093 ArrayRef<FormatToken *> lex() {
1094 assert(Tokens.empty());
1095 do {
1096 Tokens.push_back(getNextToken());
1097 } while (Tokens.back()->Tok.isNot(tok::eof));
1098 return Tokens;
1099 }
1100
1101 IdentifierTable &getIdentTable() { return IdentTable; }
1102
1103private:
1104 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001105 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001106 // Create a synthesized second '>' token.
1107 Token Greater = FormatTok->Tok;
1108 FormatTok = new (Allocator.Allocate()) FormatToken;
1109 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001110 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001111 FormatTok->Tok.getLocation().getLocWithOffset(1);
1112 FormatTok->WhitespaceRange =
1113 SourceRange(GreaterLocation, GreaterLocation);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001114 FormatTok->TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001115 GreaterStashed = false;
1116 return FormatTok;
1117 }
1118
Manuel Klimek96e888b2013-05-28 11:55:06 +00001119 FormatTok = new (Allocator.Allocate()) FormatToken;
1120 Lex.LexFromRawLexer(FormatTok->Tok);
1121 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001122 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001123 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001124 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001125 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001126
1127 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001128 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001129 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001130 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001131 if (Newlines > 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001132 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001133 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001134 FormatTok->NewlinesBefore += Newlines;
1135 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1136 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001137
Manuel Klimek96e888b2013-05-28 11:55:06 +00001138 if (FormatTok->Tok.is(tok::eof)) {
1139 FormatTok->WhitespaceRange =
Manuel Klimekad3094b2013-05-23 10:56:37 +00001140 SourceRange(WhitespaceStart,
1141 WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001142 return FormatTok;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001143 }
Manuel Klimek96e888b2013-05-28 11:55:06 +00001144 Lex.LexFromRawLexer(FormatTok->Tok);
1145 Text = rawTokenText(FormatTok->Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001146 }
Manuel Klimek95419382013-01-07 07:56:50 +00001147
1148 // Now FormatTok is the next non-whitespace token.
Manuel Klimek96e888b2013-05-28 11:55:06 +00001149 FormatTok->TokenLength = Text.size();
Manuel Klimek95419382013-01-07 07:56:50 +00001150
Manuel Klimekde008c02013-05-27 15:23:34 +00001151 TrailingWhitespace = 0;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001152 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekde008c02013-05-27 15:23:34 +00001153 TrailingWhitespace = Text.size() - Text.rtrim().size();
Manuel Klimek96e888b2013-05-28 11:55:06 +00001154 FormatTok->TokenLength -= TrailingWhitespace;
Alexander Kornienko919398b2013-04-17 17:34:05 +00001155 }
1156
Manuel Klimekd4397b92013-01-04 23:34:14 +00001157 // In case the token starts with escaped newlines, we want to
1158 // take them into account as whitespace - this pattern is quite frequent
1159 // in macro definitions.
1160 // FIXME: What do we want to do with other escaped spaces, and escaped
1161 // spaces or newlines in the middle of tokens?
1162 // FIXME: Add a more explicit test.
1163 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001164 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001165 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001166 WhitespaceLength += 2;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001167 FormatTok->TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001168 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001169 }
1170
Manuel Klimek96e888b2013-05-28 11:55:06 +00001171 if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001172 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001173 FormatTok->Tok.setIdentifierInfo(&Info);
1174 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001175 }
1176
Manuel Klimek96e888b2013-05-28 11:55:06 +00001177 if (FormatTok->Tok.is(tok::greatergreater)) {
1178 FormatTok->Tok.setKind(tok::greater);
1179 FormatTok->TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001180 GreaterStashed = true;
1181 }
1182
Manuel Klimek96e888b2013-05-28 11:55:06 +00001183 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001184 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Manuel Klimek96e888b2013-05-28 11:55:06 +00001185 FormatTok->TokenText = StringRef(
1186 SourceMgr.getCharacterData(FormatTok->getStartOfNonWhitespace()),
1187 FormatTok->TokenLength);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001188 return FormatTok;
1189 }
1190
Manuel Klimek96e888b2013-05-28 11:55:06 +00001191 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001192 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001193 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001194 Lexer &Lex;
1195 SourceManager &SourceMgr;
1196 IdentifierTable IdentTable;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001197 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1198 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001199
1200 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001201 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001202 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1203 Tok.getLength());
1204 }
1205};
1206
Daniel Jasperbac016b2012-12-03 18:12:45 +00001207class Formatter : public UnwrappedLineConsumer {
1208public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001209 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001210 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001211 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +00001212 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001213
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001214 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001215
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001216 tooling::Replacements format() {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001217 FormatTokenLexer Tokens(Lex, SourceMgr);
1218
1219 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001220 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001221 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1222 Tokens.getIdentTable().get("in"));
1223 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1224 Annotator.annotate(AnnotatedLines[i]);
1225 }
1226 deriveLocalStyle();
1227 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1228 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1229 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001230
1231 // Adapt level to the next line if this is a comment.
1232 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001233 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001234 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001235 if (NextNoneCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
1236 !AnnotatedLines[i].First->Next)
Daniel Jasper5999f762013-04-09 17:46:55 +00001237 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1238 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001239 NextNoneCommentLine =
Manuel Klimekb3987012013-05-29 14:47:47 +00001240 AnnotatedLines[i].First->isNot(tok::r_brace) ? &AnnotatedLines[i]
1241 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001242 }
1243
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001244 std::vector<int> IndentForLevel;
1245 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001246 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001247 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001248 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1249 E = AnnotatedLines.end();
1250 I != E; ++I) {
1251 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001252 const FormatToken *FirstTok = TheLine.First;
1253 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001254
1255 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001256 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001257 FormatPPDirective = false;
1258 if (!FormatPPDirective && TheLine.InPPDirective &&
1259 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1260 FormatPPDirective = true;
1261
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001262 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001263 while (IndentForLevel.size() <= TheLine.Level)
1264 IndentForLevel.push_back(-1);
1265 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001266 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1267 if (static_cast<int>(Indent) + Offset >= 0)
1268 Indent += Offset;
1269 tryFitMultipleLinesInOne(Indent, I, E);
1270
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001271 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001272 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001273 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001274 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001275 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001276 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001277 }
1278 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001279 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001280 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001281 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001282 // Insert a break even if there is a structural error in case where
1283 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001284 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001285 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001286 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001287 } else {
1288 Indent = LevelIndent =
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001289 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1290 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001291 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001292 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001293 TheLine.First, Whitespaces);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001294 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001295 IndentForLevel[TheLine.Level] = LevelIndent;
1296 PreviousLineWasTouched = true;
1297 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001298 // Format the first token if necessary, and notify the WhitespaceManager
1299 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001300 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1301 Tok = Tok->Next) {
1302 if (Tok == TheLine.First &&
1303 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1304 unsigned LevelIndent =
1305 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001306 // Remove trailing whitespace of the previous line if it was
1307 // touched.
1308 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1309 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1310 TheLine.InPPDirective);
1311 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001312 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001313 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001314
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001315 if (static_cast<int>(LevelIndent) - Offset >= 0)
1316 LevelIndent -= Offset;
1317 if (Tok->isNot(tok::comment))
1318 IndentForLevel[TheLine.Level] = LevelIndent;
1319 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001320 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001321 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001322 }
1323 // If we did not reformat this unwrapped line, the column at the end of
1324 // the last token is unchanged - thus, we can calculate the end of the
1325 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001326 PreviousLineWasTouched = false;
1327 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001328 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001329 }
1330 return Whitespaces.generateReplacements();
1331 }
1332
1333private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001334 void deriveLocalStyle() {
1335 unsigned CountBoundToVariable = 0;
1336 unsigned CountBoundToType = 0;
1337 bool HasCpp03IncompatibleFormat = false;
1338 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001339 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001340 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +00001341 FormatToken *Tok = AnnotatedLines[i].First->Next;
1342 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001343 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001344 bool SpacesBefore =
1345 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1346 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1347 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001348 if (SpacesBefore && !SpacesAfter)
1349 ++CountBoundToVariable;
1350 else if (!SpacesBefore && SpacesAfter)
1351 ++CountBoundToType;
1352 }
1353
Daniel Jasper29f123b2013-02-08 15:28:42 +00001354 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001355 Tok->Previous->Type == TT_TemplateCloser &&
1356 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001357 HasCpp03IncompatibleFormat = true;
Manuel Klimekb3987012013-05-29 14:47:47 +00001358 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001359 }
1360 }
1361 if (Style.DerivePointerBinding) {
1362 if (CountBoundToType > CountBoundToVariable)
1363 Style.PointerBindsToType = true;
1364 else if (CountBoundToType < CountBoundToVariable)
1365 Style.PointerBindsToType = false;
1366 }
1367 if (Style.Standard == FormatStyle::LS_Auto) {
1368 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1369 : FormatStyle::LS_Cpp03;
1370 }
1371 }
1372
Manuel Klimek547d5db2013-02-08 17:38:27 +00001373 /// \brief Get the indent of \p Level from \p IndentForLevel.
1374 ///
1375 /// \p IndentForLevel must contain the indent for the level \c l
1376 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1377 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001378 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001379 if (IndentForLevel[Level] != -1)
1380 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001381 if (Level == 0)
1382 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001383 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001384 }
1385
1386 /// \brief Get the offset of the line relatively to the level.
1387 ///
1388 /// For example, 'public:' labels in classes are offset by 1 or 2
1389 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001390 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001391 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001392 return Style.AccessModifierOffset;
1393 return 0;
1394 }
1395
Manuel Klimek517e8942013-01-11 17:54:10 +00001396 /// \brief Tries to merge lines into one.
1397 ///
1398 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1399 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001400 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001401 std::vector<AnnotatedLine>::iterator &I,
1402 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001403 // We can never merge stuff if there are trailing line comments.
1404 if (I->Last->Type == TT_LineComment)
1405 return;
1406
Daniel Jaspera4d46212013-02-28 11:05:57 +00001407 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001408 // If we already exceed the column limit, we set 'Limit' to 0. The different
1409 // tryMerge..() functions can then decide whether to still do merging.
1410 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001411
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001412 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001413 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001414
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001415 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001416 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001417 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001418 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001419 tryMergeSimpleControlStatement(I, E, Limit);
1420 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001421 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001422 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +00001423 } else if (I->InPPDirective &&
1424 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001425 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001426 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001427 }
1428
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001429 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1430 std::vector<AnnotatedLine>::iterator E,
1431 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001432 if (Limit == 0)
1433 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001434 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001435 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001436 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001437 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001438 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001439 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001440 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001441 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001442 join(Line, *(++I));
1443 }
1444
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001445 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1446 std::vector<AnnotatedLine>::iterator E,
1447 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001448 if (Limit == 0)
1449 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001450 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001451 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001452 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001453 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001454 if (Line.Last->isNot(tok::r_paren))
1455 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001456 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001457 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001458 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1459 tok::kw_while) ||
1460 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001461 return;
1462 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001463 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1464 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001465 return;
1466 join(Line, *(++I));
1467 }
1468
1469 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001470 std::vector<AnnotatedLine>::iterator E,
1471 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001472 // No merging if the brace already is on the next line.
1473 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1474 return;
1475
Manuel Klimek517e8942013-01-11 17:54:10 +00001476 // First, check that the current line allows merging. This is the case if
1477 // we're not in a control flow statement and the last token is an opening
1478 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001479 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001480 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1481 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001482 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001483 // This gets rid of all ObjC @ keywords and methods.
1484 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001485 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001486
Manuel Klimekb3987012013-05-29 14:47:47 +00001487 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001488 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
1489 (Tok->getNextNoneComment() == NULL ||
1490 Tok->getNextNoneComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001491 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001492 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001493 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001494 join(Line, *(I + 1));
1495 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001496 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001497 // Check that we still have three lines and they fit into the limit.
1498 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1499 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001500 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001501
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001502 // Second, check that the next line does not contain any braces - if it
1503 // does, readability declines when putting it into a single line.
1504 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1505 return;
1506 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001507 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001508 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001509 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001510 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001511
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001512 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001513 Tok = (I + 2)->First;
Daniel Jasper058f6f82013-05-16 10:17:39 +00001514 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001515 Tok->MustBreakBefore)
1516 return;
1517
1518 join(Line, *(I + 1));
1519 join(Line, *(I + 2));
1520 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001521 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001522 }
1523
1524 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1525 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001526 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1527 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001528 }
1529
Daniel Jasper995e8202013-01-14 13:08:07 +00001530 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001531 assert(!A.Last->Next);
1532 assert(!B.First->Previous);
1533 A.Last->Next = B.First;
1534 B.First->Previous = A.Last;
1535 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1536 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1537 Tok->TotalLength += LengthA;
1538 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001539 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001540 }
1541
Daniel Jasper6f21a982013-03-13 07:49:51 +00001542 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001543 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1544 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1545 Ranges[i].getBegin()) &&
1546 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1547 Range.getBegin()))
1548 return true;
1549 }
1550 return false;
1551 }
1552
1553 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001554 const FormatToken *First = TheLine.First;
1555 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001556 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001557 First->WhitespaceRange.getBegin().getLocWithOffset(
1558 First->LastNewlineOffset),
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001559 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001560 return touchesRanges(LineRange);
1561 }
1562
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001563 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1564 std::vector<AnnotatedLine>::iterator E) {
1565 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001566 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001567 return false;
1568 if (touchesLine(*I))
1569 return true;
1570 }
1571 return false;
1572 }
1573
Daniel Jasperf3023542013-03-07 20:50:00 +00001574 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001575 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001576 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001577 First->WhitespaceRange.getBegin(),
1578 First->WhitespaceRange.getBegin().getLocWithOffset(
1579 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001580 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001581 }
1582
1583 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001584 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001585 }
1586
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001587 /// \brief Add a new line and the required indent before the first Token
1588 /// of the \c UnwrappedLine if there was no structural parsing error.
1589 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001590 void formatFirstToken(const FormatToken &RootToken,
1591 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001592 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001593 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001594 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1595 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001596 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001597
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001598 // Insert extra new line before access specifiers.
1599 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001600 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001601 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001602
Manuel Klimekb3987012013-05-29 14:47:47 +00001603 Whitespaces.replaceWhitespace(
1604 RootToken, Newlines, Indent, Indent,
1605 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001606 }
1607
Daniel Jasperbac016b2012-12-03 18:12:45 +00001608 FormatStyle Style;
1609 Lexer &Lex;
1610 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001611 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001612 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001613 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001614};
1615
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001616tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1617 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001618 std::vector<CharSourceRange> Ranges) {
1619 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001620 return formatter.format();
1621}
1622
Daniel Jasper8a999452013-05-16 10:40:07 +00001623tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1624 std::vector<tooling::Range> Ranges,
1625 StringRef FileName) {
1626 FileManager Files((FileSystemOptions()));
1627 DiagnosticsEngine Diagnostics(
1628 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1629 new DiagnosticOptions);
1630 SourceManager SourceMgr(Diagnostics, Files);
1631 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1632 const clang::FileEntry *Entry =
1633 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1634 SourceMgr.overrideFileContents(Entry, Buf);
1635 FileID ID =
1636 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1637 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1638 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1639 std::vector<CharSourceRange> CharRanges;
1640 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1641 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1642 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1643 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1644 }
1645 return reformat(Style, Lex, SourceMgr, CharRanges);
1646}
1647
Daniel Jasper46ef8522013-01-10 13:08:12 +00001648LangOptions getFormattingLangOpts() {
1649 LangOptions LangOpts;
1650 LangOpts.CPlusPlus = 1;
1651 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001652 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001653 LangOpts.Bool = 1;
1654 LangOpts.ObjC1 = 1;
1655 LangOpts.ObjC2 = 1;
1656 return LangOpts;
1657}
1658
Daniel Jaspercd162382013-01-07 13:26:07 +00001659} // namespace format
1660} // namespace clang