blob: 14337e9760eb1f7081ba65b97969ea1aef064463 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod6538332013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43 }
44};
45
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000046template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000047struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48 static void
49 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod6538332013-05-07 15:32:14 +000053 }
54};
55
56template <> struct MappingTraits<clang::format::FormatStyle> {
57 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000058 if (IO.outputting()) {
59 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60 ArrayRef<StringRef> Styles(StylesArray);
61 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62 StringRef StyleName(Styles[i]);
Alexander Kornienko006b5c82013-05-19 00:53:30 +000063 clang::format::FormatStyle PredefinedStyle;
64 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000066 IO.mapOptional("# BasedOnStyle", StyleName);
67 break;
68 }
69 }
70 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000071 StringRef BasedOnStyle;
72 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000073 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-05-19 00:53:30 +000074 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
75 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
76 return;
77 }
Alexander Kornienkod6538332013-05-07 15:32:14 +000078 }
79
80 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
81 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
82 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
83 Style.AllowAllParametersOfDeclarationOnNextLine);
84 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
85 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +000086 IO.mapOptional("AllowShortLoopsOnASingleLine",
87 Style.AllowShortLoopsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +000088 IO.mapOptional("AlwaysBreakTemplateDeclarations",
89 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +000090 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
91 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
92 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
93 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
94 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
95 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
96 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
97 IO.mapOptional("ObjCSpaceBeforeProtocolList",
98 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +000099 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
100 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000101 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
102 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
103 Style.PenaltyReturnTypeOnItsOwnLine);
104 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
105 IO.mapOptional("SpacesBeforeTrailingComments",
106 Style.SpacesBeforeTrailingComments);
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000107 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000108 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000109 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000110 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000111 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000112 }
113};
114}
115}
116
Daniel Jasperf7935112012-12-03 18:12:45 +0000117namespace clang {
118namespace format {
119
Daniel Jasperf7935112012-12-03 18:12:45 +0000120FormatStyle getLLVMStyle() {
121 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000122 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000123 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000124 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000125 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000126 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000127 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000128 LLVMStyle.BinPackParameters = true;
129 LLVMStyle.ColumnLimit = 80;
130 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
131 LLVMStyle.DerivePointerBinding = false;
132 LLVMStyle.IndentCaseLabels = false;
133 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000134 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000135 LLVMStyle.PenaltyBreakComment = 45;
136 LLVMStyle.PenaltyBreakString = 1000;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000137 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000138 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000139 LLVMStyle.PointerBindsToType = false;
140 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jaspere5777d22013-05-23 10:15:45 +0000141 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000142 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000143 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000144 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000145 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000146 return LLVMStyle;
147}
148
149FormatStyle getGoogleStyle() {
150 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000151 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000152 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000153 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000154 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000155 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000156 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000157 GoogleStyle.BinPackParameters = true;
158 GoogleStyle.ColumnLimit = 80;
159 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
160 GoogleStyle.DerivePointerBinding = true;
161 GoogleStyle.IndentCaseLabels = true;
162 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000163 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000164 GoogleStyle.PenaltyBreakComment = 45;
165 GoogleStyle.PenaltyBreakString = 1000;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000166 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000167 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000168 GoogleStyle.PointerBindsToType = true;
169 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jaspere5777d22013-05-23 10:15:45 +0000170 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000171 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000172 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000173 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000174 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 return GoogleStyle;
176}
177
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000178FormatStyle getChromiumStyle() {
179 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000180 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000181 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000182 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000183 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000184 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
185 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000186 return ChromiumStyle;
187}
188
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000189FormatStyle getMozillaStyle() {
190 FormatStyle MozillaStyle = getLLVMStyle();
191 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
192 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
193 MozillaStyle.DerivePointerBinding = true;
194 MozillaStyle.IndentCaseLabels = true;
195 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
196 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
197 MozillaStyle.PointerBindsToType = true;
198 return MozillaStyle;
199}
200
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000201bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000203 *Style = getLLVMStyle();
204 else if (Name.equals_lower("chromium"))
205 *Style = getChromiumStyle();
206 else if (Name.equals_lower("mozilla"))
207 *Style = getMozillaStyle();
208 else if (Name.equals_lower("google"))
209 *Style = getGoogleStyle();
210 else
211 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000212
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000213 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000214}
215
216llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000217 if (Text.trim().empty())
218 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000219 llvm::yaml::Input Input(Text);
220 Input >> *Style;
221 return Input.error();
222}
223
224std::string configurationAsText(const FormatStyle &Style) {
225 std::string Text;
226 llvm::raw_string_ostream Stream(Text);
227 llvm::yaml::Output Output(Stream);
228 // We use the same mapping method for input and output, so we need a non-const
229 // reference here.
230 FormatStyle NonConstStyle = Style;
231 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000232 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000233}
234
Daniel Jasperacc33662013-02-08 08:22:00 +0000235// Returns the length of everything up to the first possible line break after
236// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000237static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000238 if (Tok.MatchingParen == NULL)
239 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000240 FormatToken *End = Tok.MatchingParen;
241 while (End->Next && !End->Next->CanBreakBefore) {
242 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000243 }
244 return End->TotalLength - Tok.TotalLength + 1;
245}
246
Daniel Jasperf7935112012-12-03 18:12:45 +0000247class UnwrappedLineFormatter {
248public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000249 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000250 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000251 const FormatToken *RootToken,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000252 WhitespaceManager &Whitespaces,
253 encoding::Encoding Encoding)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000254 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000255 FirstIndent(FirstIndent), RootToken(RootToken),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000256 Whitespaces(Whitespaces), Count(0), Encoding(Encoding) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000257
Manuel Klimek1abf7892013-01-04 23:34:14 +0000258 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000259 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000260 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000261 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000262 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000263 State.NextToken = RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000264 State.Stack.push_back(
Daniel Jasper53e8d852013-05-22 08:55:55 +0000265 ParenState(FirstIndent, FirstIndent, /*AvoidBinPacking=*/ false,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000266 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000267 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000268 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000269 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000270 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper80503952013-06-03 09:54:46 +0000271 State.LowestCallLevel = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000272 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000273
274 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000275 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000276
Daniel Jasper4b866272013-02-01 11:00:45 +0000277 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000278 unsigned ColumnLimit = Style.ColumnLimit;
279 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000280 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000281 ColumnLimit = getColumnLimit();
282 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000283 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000284 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000285 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000286 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000287
Daniel Jasperacc33662013-02-08 08:22:00 +0000288 // If the ObjC method declaration does not fit on a line, we should format
289 // it with one arg per line.
290 if (Line.Type == LT_ObjCMethodDecl)
291 State.Stack.back().BreakBeforeParameter = true;
292
Daniel Jasper4b866272013-02-01 11:00:45 +0000293 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000294 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000295 }
296
297private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000298 void DebugTokenState(const FormatToken &FormatTok) {
299 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000300 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000301 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000302 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000303 }
304
Daniel Jasper337816e2013-01-11 10:22:12 +0000305 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000306 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000307 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000308 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
309 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000310 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000311 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
312 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000313 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000314
Daniel Jasperf7935112012-12-03 18:12:45 +0000315 /// \brief The position to which a specific parenthesis level needs to be
316 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000317 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000318
Daniel Jaspere9de2602012-12-06 09:56:08 +0000319 /// \brief The position of the last space on each level.
320 ///
321 /// Used e.g. to break like:
322 /// functionCall(Parameter, otherCall(
323 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000324 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000325
Daniel Jaspere9de2602012-12-06 09:56:08 +0000326 /// \brief The position the first "<<" operator encountered on each level.
327 ///
328 /// Used to align "<<" operators. 0 if no such operator has been encountered
329 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000330 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000331
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000332 /// \brief Whether a newline needs to be inserted before the block's closing
333 /// brace.
334 ///
335 /// We only want to insert a newline before the closing brace if there also
336 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000337 bool BreakBeforeClosingBrace;
338
Daniel Jasperca6623b2013-01-28 12:45:14 +0000339 /// \brief The column of a \c ? in a conditional expression;
340 unsigned QuestionColumn;
341
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000342 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
343 /// lines, in this context.
344 bool AvoidBinPacking;
345
346 /// \brief Break after the next comma (or all the commas in this context if
347 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000348 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000349
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000350 /// \brief Line breaking in this context would break a formatting rule.
351 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000352
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000353 /// \brief The position of the colon in an ObjC method declaration/call.
354 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000355
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000356 /// \brief The start of the most recent function in a builder-type call.
357 unsigned StartOfFunctionCall;
358
Daniel Jasperc238c872013-04-02 14:33:13 +0000359 /// \brief If a nested name specifier was broken over multiple lines, this
360 /// contains the start column of the second line. Otherwise 0.
361 unsigned NestedNameSpecifierContinuation;
362
363 /// \brief If a call expression was broken over multiple lines, this
364 /// contains the start column of the second line. Otherwise 0.
365 unsigned CallContinuation;
366
Daniel Jaspera628c982013-04-03 13:36:17 +0000367 /// \brief The column of the first variable name in a variable declaration.
368 ///
369 /// Used to align further variables if necessary.
370 unsigned VariablePos;
371
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000372 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
373 ///
374 /// Does not need to be considered for memoization / the comparison function
375 /// as otherwise identical states will have the same fake/non-fake
376 /// \c ParenStates.
377 bool ForFakeParenthesis;
378
Daniel Jasper337816e2013-01-11 10:22:12 +0000379 bool operator<(const ParenState &Other) const {
380 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000381 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000382 if (LastSpace != Other.LastSpace)
383 return LastSpace < Other.LastSpace;
384 if (FirstLessLess != Other.FirstLessLess)
385 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000386 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
387 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000388 if (QuestionColumn != Other.QuestionColumn)
389 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000390 if (AvoidBinPacking != Other.AvoidBinPacking)
391 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000392 if (BreakBeforeParameter != Other.BreakBeforeParameter)
393 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000394 if (NoLineBreak != Other.NoLineBreak)
395 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000396 if (ColonPos != Other.ColonPos)
397 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000398 if (StartOfFunctionCall != Other.StartOfFunctionCall)
399 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000400 if (CallContinuation != Other.CallContinuation)
401 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000402 if (VariablePos != Other.VariablePos)
403 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000404 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000405 }
406 };
407
408 /// \brief The current state when indenting a unwrapped line.
409 ///
410 /// As the indenting tries different combinations this is copied by value.
411 struct LineState {
412 /// \brief The number of used columns in the current line.
413 unsigned Column;
414
415 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000416 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000417
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000418 /// \brief \c true if this line contains a continued for-loop section.
419 bool LineContainsContinuedForLoopSection;
420
Daniel Jasper400adc62013-02-08 15:28:42 +0000421 /// \brief The level of nesting inside (), [], <> and {}.
422 unsigned ParenLevel;
423
Daniel Jasper40c36c52013-02-18 11:05:07 +0000424 /// \brief The \c ParenLevel at the start of this line.
425 unsigned StartOfLineLevel;
426
Daniel Jasper80503952013-06-03 09:54:46 +0000427 /// \brief The lowest \c ParenLevel of "." or "->" on the current line.
428 unsigned LowestCallLevel;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000429
Manuel Klimek02f640a2013-02-20 15:25:48 +0000430 /// \brief The start column of the string literal, if we're in a string
431 /// literal sequence, 0 otherwise.
432 unsigned StartOfStringLiteral;
433
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 /// \brief A stack keeping track of properties applying to parenthesis
435 /// levels.
436 std::vector<ParenState> Stack;
437
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000438 /// \brief Ignore the stack of \c ParenStates for state comparison.
439 ///
440 /// In long and deeply nested unwrapped lines, the current algorithm can
441 /// be insufficient for finding the best formatting with a reasonable amount
442 /// of time and memory. Setting this flag will effectively lead to the
443 /// algorithm not analyzing some combinations. However, these combinations
444 /// rarely contain the optimal solution: In short, accepting a higher
445 /// penalty early would need to lead to different values in the \c
446 /// ParenState stack (in an otherwise identical state) and these different
447 /// values would need to lead to a significant amount of avoided penalty
448 /// later.
449 ///
450 /// FIXME: Come up with a better algorithm instead.
451 bool IgnoreStackForComparison;
452
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 /// \brief Comparison operator to be able to used \c LineState in \c map.
454 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000455 if (NextToken != Other.NextToken)
456 return NextToken < Other.NextToken;
457 if (Column != Other.Column)
458 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000459 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000460 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000461 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000462 if (ParenLevel != Other.ParenLevel)
463 return ParenLevel < Other.ParenLevel;
464 if (StartOfLineLevel != Other.StartOfLineLevel)
465 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper80503952013-06-03 09:54:46 +0000466 if (LowestCallLevel != Other.LowestCallLevel)
467 return LowestCallLevel < Other.LowestCallLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000468 if (StartOfStringLiteral != Other.StartOfStringLiteral)
469 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000470 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
471 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000472 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000473 }
474 };
475
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000476 /// \brief Appends the next token to \p State and updates information
477 /// necessary for indentation.
478 ///
479 /// Puts the token on the current line if \p Newline is \c true and adds a
480 /// line break and necessary indentation otherwise.
481 ///
482 /// If \p DryRun is \c false, also creates and stores the required
483 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000484 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000485 const FormatToken &Current = *State.NextToken;
486 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000487
Daniel Jasper291f9362013-03-20 15:58:10 +0000488 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000489 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000490 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
491 State.NextToken->WhitespaceRange.getEnd()) -
492 SourceMgr.getSpellingColumnNumber(
493 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000494 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000495 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000496 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000497 }
498
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000499 // If we are continuing an expression, we want to indent an extra 4 spaces.
500 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000501 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 if (Newline) {
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000503 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000504 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000505 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000506 State.StartOfStringLiteral != 0) {
507 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000508 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000509 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000510 State.Stack.back().FirstLessLess != 0) {
511 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000512 } else if (Current.isOneOf(tok::period, tok::arrow) &&
513 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000514 if (State.Stack.back().CallContinuation == 0) {
515 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000516 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000517 } else {
518 State.Column = State.Stack.back().CallContinuation;
519 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000520 } else if (Current.Type == TT_ConditionalExpr) {
521 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000522 } else if (Previous.is(tok::comma) &&
523 State.Stack.back().VariablePos != 0) {
524 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000525 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000526 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
527 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000528 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000529 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000530 if (State.Stack.back().ColonPos > Current.CodePointCount) {
531 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000532 } else {
533 State.Column = State.Stack.back().Indent;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000534 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000535 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000536 } else if (Current.Type == TT_StartOfName ||
537 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000538 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000539 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000540 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000541 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000542 // Ensure that we fall back to indenting 4 spaces instead of just
543 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000544 if (State.Column == FirstIndent)
545 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000546 }
547
Daniel Jasper54a86022013-02-15 11:07:25 +0000548 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000549 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000550 if ((Previous.isOneOf(tok::comma, tok::semi) &&
551 !State.Stack.back().AvoidBinPacking) ||
552 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000553 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000554 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
555 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000556
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000557 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000558 unsigned NewLines = 1;
Alexander Kornienkof370ad92013-06-12 19:04:12 +0000559 if (Current.is(tok::comment))
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000560 NewLines = std::max(
561 NewLines,
562 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000563 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
564 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000565 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000566
Daniel Jasper400adc62013-02-08 15:28:42 +0000567 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000568 if (Current.isOneOf(tok::arrow, tok::period) &&
569 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000570 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000571 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper80503952013-06-03 09:54:46 +0000572 State.LowestCallLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000573
574 // Any break on this level means that the parent level has been broken
575 // and we need to avoid bin packing there.
576 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
577 State.Stack[i].BreakBeforeParameter = true;
578 }
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000579 const FormatToken *TokenBefore = Current.getPreviousNoneComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000580 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000581 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000582 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000583 State.Stack.back().BreakBeforeParameter = true;
584
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000585 // If we break after {, we should also break before the corresponding }.
586 if (Previous.is(tok::l_brace))
587 State.Stack.back().BreakBeforeClosingBrace = true;
588
589 if (State.Stack.back().AvoidBinPacking) {
590 // If we are breaking after '(', '{', '<', this is not bin packing
591 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000592 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
593 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000594 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
595 Line.MustBeDeclaration))
596 State.Stack.back().BreakBeforeParameter = true;
597 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000599 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000600 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000601 State.Stack.back().VariablePos == 0) {
602 State.Stack.back().VariablePos = State.Column;
603 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000604 const FormatToken *Tok = &Previous;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000605 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
606 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000607 if (Tok->SpacesRequiredBefore != 0)
608 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000609 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000610 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000611 if (Previous.PartOfMultiVariableDeclStmt)
612 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
613 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000614
Daniel Jaspereef30492013-02-11 12:36:37 +0000615 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000616
Daniel Jasperf7935112012-12-03 18:12:45 +0000617 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000618 Whitespaces.replaceWhitespace(Current, 0, Spaces,
619 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000620
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000621 if (Current.Type == TT_ObjCSelectorName &&
622 State.Stack.back().ColonPos == 0) {
623 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000624 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000625 State.Stack.back().ColonPos =
626 State.Stack.back().Indent + Current.LongestObjCSelectorName;
627 else
628 State.Stack.back().ColonPos =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000629 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000630 }
631
Daniel Jasperc04baae2013-04-10 09:49:49 +0000632 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000633 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000634 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000635 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
636 State.Stack.back().AvoidBinPacking)
637 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000638
Daniel Jaspere9de2602012-12-06 09:56:08 +0000639 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000640 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000641 // Treat the condition inside an if as if it was a second function
642 // parameter, i.e. let nested calls have an indent of 4.
643 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000644 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000645 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000646 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000647 Previous.Type == TT_ConditionalExpr ||
648 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000649 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000650 Current.FakeLParens.empty()))
651 // Always indent relative to the RHS of the expression unless this is a
652 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000653 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000654 else if (Previous.Type == TT_InheritanceColon)
655 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000656 else if (Previous.opensScope() && !Current.FakeLParens.empty())
657 // If this function has multiple parameters or a binary expression
658 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000659 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000661
Manuel Klimek1998ea22013-02-20 10:15:13 +0000662 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000663 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000664
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000665 /// \brief Mark the next token as consumed in \p State and modify its stacks
666 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000667 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000668 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000669 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000670
Daniel Jaspereead02b2013-02-14 08:42:54 +0000671 if (Current.Type == TT_InheritanceColon)
672 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000673 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
674 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000675 if (Current.is(tok::question))
676 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper80503952013-06-03 09:54:46 +0000677 if (Current.isOneOf(tok::period, tok::arrow)) {
678 State.LowestCallLevel = std::min(State.LowestCallLevel, State.ParenLevel);
679 if (Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
680 State.Stack.back().StartOfFunctionCall =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000681 Current.LastInChainOfCalls ? 0
682 : State.Column + Current.CodePointCount;
Daniel Jasper80503952013-06-03 09:54:46 +0000683 }
Daniel Jasper37905f72013-02-21 15:00:29 +0000684 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000685 // Indent 2 from the column, so:
686 // SomeClass::SomeClass()
687 // : First(...), ...
688 // Next(...)
689 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000690 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000691 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
692 State.Stack.back().AvoidBinPacking = true;
693 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000694 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000695
Daniel Jasper6bee6822013-04-08 20:33:42 +0000696 // If return returns a binary expression, align after it.
697 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
698 State.Stack.back().LastSpace = State.Column + 7;
699
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000700 // In ObjC method declaration we align on the ":" of parameters, but we need
701 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000702 if (Current.Type == TT_ObjCMethodSpecifier)
703 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000704
Daniel Jasper400adc62013-02-08 15:28:42 +0000705 // Insert scopes created by fake parenthesis.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000706 const FormatToken *Previous = Current.getPreviousNoneComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000707 // Don't add extra indentation for the first fake parenthesis after
708 // 'return', assignements or opening <({[. The indentation for these cases
709 // is special cased.
710 bool SkipFirstExtraIndent =
711 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000712 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000713 Previous->getPrecedence() == prec::Assignment));
Daniel Jasper6bee6822013-04-08 20:33:42 +0000714 for (SmallVector<prec::Level, 4>::const_reverse_iterator
715 I = Current.FakeLParens.rbegin(),
716 E = Current.FakeLParens.rend();
717 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000718 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000719 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000720 NewParenState.Indent =
721 std::max(std::max(State.Column, NewParenState.Indent),
722 State.Stack.back().LastSpace);
723
724 // Always indent conditional expressions. Never indent expression where
725 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
726 // prec::Assignment) as those have different indentation rules. Indent
727 // other expression, unless the indentation needs to be skipped.
728 if (*I == prec::Conditional ||
729 (!SkipFirstExtraIndent && *I > prec::Assignment))
730 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000731 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000732 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000733 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000734 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000735 }
736
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000737 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000738 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000739 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000740 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000741 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000742 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000743 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000744 NewIndent = Style.IndentWidth + LastSpace;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000745 const FormatToken *NextNoComment = Current.getNextNoneComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000746 AvoidBinPacking = NextNoComment &&
747 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000748 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000749 NewIndent =
750 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000751 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000752 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000753
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000754 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
755 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000756 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000757 }
758
Daniel Jasperacc33662013-02-08 08:22:00 +0000759 // If this '[' opens an ObjC call, determine whether all parameters fit into
760 // one line and put one per line if they don't.
761 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
762 Current.MatchingParen != NULL) {
763 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
764 State.Stack.back().BreakBeforeParameter = true;
765 }
766
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000767 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000768 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000769 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000770 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000771 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000772 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000773 --State.ParenLevel;
774 }
775
776 // Remove scopes created by fake parenthesis.
777 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000778 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000779 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000780 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000782
Daniel Jasper47a04442013-05-13 20:50:15 +0000783 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000784 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000785 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
786 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000787 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000788 }
789
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000790 State.Column += Current.CodePointCount;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000791
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000792 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000793
Manuel Klimek1998ea22013-02-20 10:15:13 +0000794 return breakProtrudingToken(Current, State, DryRun);
795 }
796
797 /// \brief If the current token sticks out over the end of the line, break
798 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000799 ///
800 /// \returns An extra penalty if a token was broken, otherwise 0.
801 ///
802 /// Note that the penalty of the token protruding the allowed line length is
803 /// already handled in \c addNextStateToQueue; the returned penalty will only
804 /// cover the cost of the additional line breaks.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000805 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000806 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000807 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000808 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000809 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000810 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000811 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000812
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000813 if (Current.is(tok::string_literal) &&
814 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000815 // Only break up default narrow strings.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000816 if (!Current.TokenText.startswith("\""))
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000817 return 0;
818
Alexander Kornienkobe633902013-06-14 11:46:10 +0000819 Token.reset(new BreakableStringLiteral(Current, StartColumn,
820 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000821 } else if (Current.Type == TT_BlockComment) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000822 Token.reset(new BreakableBlockComment(
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000823 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000824 Line.InPPDirective, Encoding));
Daniel Jasper4a4be012013-05-06 10:24:51 +0000825 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000826 (Current.Previous == NULL ||
827 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000828 Token.reset(new BreakableLineComment(Current, StartColumn,
829 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000830 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000831 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000832 }
Alexander Kornienkobe633902013-06-14 11:46:10 +0000833 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000834 return 0;
Alexander Kornienkobe633902013-06-14 11:46:10 +0000835 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000836
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000837 bool BreakInserted = false;
838 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000839 unsigned PositionAfterLastLineInToken = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +0000840 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
841 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000842 if (!DryRun)
843 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000844 unsigned TailOffset = 0;
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000845 unsigned RemainingTokenColumns = Token->getLineLengthAfterSplit(
846 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000847 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000848 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000849 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000850 if (Split.first == StringRef::npos)
851 break;
852 assert(Split.first != 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000853 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000854 LineIndex, TailOffset + Split.first + Split.second,
855 StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000856 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienkobe633902013-06-14 11:46:10 +0000857 if (!DryRun)
858 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000859 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
860 : Style.PenaltyBreakComment;
861 unsigned ColumnsUsed =
862 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
863 if (ColumnsUsed > getColumnLimit()) {
864 Penalty +=
865 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
866 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000867 TailOffset += Split.first + Split.second;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000868 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000869 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000870 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000871 PositionAfterLastLineInToken = RemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000872 }
873
874 if (BreakInserted) {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000875 State.Column = PositionAfterLastLineInToken;
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +0000876 // If we break the token inside a parameter list, we need to break before
877 // the next parameter on all levels, so that the next parameter is clearly
878 // visible. Line comments already introduce a break.
879 if (Current.Type != TT_LineComment) {
880 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
881 State.Stack[i].BreakBeforeParameter = true;
882 }
883
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000884 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000885 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000886 return Penalty;
887 }
888
Daniel Jasper2df93312013-01-09 10:16:05 +0000889 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000890 // In preprocessor directives reserve two chars for trailing " \"
891 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000892 }
893
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000894 /// \brief An edge in the solution space from \c Previous->State to \c State,
895 /// inserting a newline dependent on the \c NewLine.
896 struct StateNode {
897 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000898 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000899 LineState State;
900 bool NewLine;
901 StateNode *Previous;
902 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000903
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000904 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
905 ///
906 /// In case of equal penalties, we want to prefer states that were inserted
907 /// first. During state generation we make sure that we insert states first
908 /// that break the line as late as possible.
909 typedef std::pair<unsigned, unsigned> OrderedPenalty;
910
911 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
912 /// \c State has the given \c OrderedPenalty.
913 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
914
915 /// \brief The BFS queue type.
916 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
917 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000918
919 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000921 /// This implements a variant of Dijkstra's algorithm on the graph that spans
922 /// the solution space (\c LineStates are the nodes). The algorithm tries to
923 /// find the shortest path (the one with lowest penalty) from \p InitialState
924 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000925 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000926 std::set<LineState> Seen;
927
Daniel Jasper4b866272013-02-01 11:00:45 +0000928 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000929 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000930 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
931 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
932 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000933
934 // While not empty, take first element and follow edges.
935 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000936 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000937 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000938 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000939 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000940 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000941 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000942 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000943
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000944 // Cut off the analysis of certain solutions if the analysis gets too
945 // complex. See description of IgnoreStackForComparison.
946 if (Count > 10000)
947 Node->State.IgnoreStackForComparison = true;
948
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000949 if (!Seen.insert(Node->State).second)
950 // State already examined with lower penalty.
951 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000952
Manuel Klimekaf491072013-02-13 10:54:19 +0000953 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
954 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000955 }
956
957 if (Queue.empty())
958 // We were unable to find a solution, do nothing.
959 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +0000960 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000961
Daniel Jasper4b866272013-02-01 11:00:45 +0000962 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000963 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000964 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
965 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000966 }
967
968 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000969 std::deque<StateNode *> Path;
970 // We do not need a break before the initial token.
971 while (Current->Previous) {
972 Path.push_front(Current);
973 Current = Current->Previous;
974 }
975 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
976 I != E; ++I) {
977 DEBUG({
978 if ((*I)->NewLine) {
979 llvm::dbgs() << "Penalty for splitting before "
980 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
981 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
982 }
983 });
984 addTokenToState((*I)->NewLine, false, State);
985 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000986 }
987
Manuel Klimekaf491072013-02-13 10:54:19 +0000988 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000989 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000990 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000991 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000992 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
993 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000994 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000995 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000996 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000997 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000998 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000999 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1000
1001 StateNode *Node = new (Allocator.Allocate())
1002 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001003 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001004 if (Node->State.Column > getColumnLimit()) {
1005 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001006 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001007 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001008
1009 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1010 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001011 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001012
Daniel Jasper4b866272013-02-01 11:00:45 +00001013 /// \brief Returns \c true, if a line break after \p State is allowed.
1014 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001015 const FormatToken &Current = *State.NextToken;
1016 const FormatToken &Previous = *Current.Previous;
1017 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001018 if (!Current.CanBreakBefore &&
1019 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001020 State.Stack.back().BreakBeforeClosingBrace))
1021 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001022 // The opening "{" of a braced list has to be on the same line as the first
1023 // element if it is nested in another braced init list or function call.
1024 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001025 Previous.Previous &&
1026 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001027 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001028 // This prevents breaks like:
1029 // ...
1030 // SomeParameter, OtherParameter).DoSomething(
1031 // ...
1032 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper80503952013-06-03 09:54:46 +00001033 if (Previous.opensScope() && State.LowestCallLevel < State.StartOfLineLevel)
Daniel Jasper32a796b2013-05-27 11:50:16 +00001034 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001035 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001036 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001037
Daniel Jasper4b866272013-02-01 11:00:45 +00001038 /// \brief Returns \c true, if a line break after \p State is mandatory.
1039 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001040 const FormatToken &Current = *State.NextToken;
1041 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001042 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001043 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001044 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +00001045 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001046 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001047 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001048 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1049 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001050 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001051 !Current.isTrailingComment() &&
1052 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001053 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001054
1055 // If we need to break somewhere inside the LHS of a binary expression, we
1056 // should also break after the operator.
1057 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper9f82df22013-05-28 07:42:44 +00001058 Current.Type != TT_BinaryOperator && // Special case for ">>".
Daniel Jasper68d888c2013-06-03 08:42:05 +00001059 !Current.isTrailingComment() &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001060 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001061 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001062 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001063 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001064
1065 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1066 // out whether it is the first parameter. Clean this up.
1067 if (Current.Type == TT_ObjCSelectorName &&
1068 Current.LongestObjCSelectorName == 0 &&
1069 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001070 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001071 if ((Current.Type == TT_CtorInitializerColon ||
1072 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001073 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001074
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001075 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1076 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1077 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001078 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 }
1080
Daniel Jasper9b334242013-03-15 14:57:30 +00001081 // Returns the total number of columns required for the remaining tokens.
1082 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001083 if (State.NextToken && State.NextToken->Previous)
1084 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001085 return 0;
1086 }
1087
Daniel Jasperf7935112012-12-03 18:12:45 +00001088 FormatStyle Style;
1089 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001090 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001091 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001092 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001093 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001094
1095 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1096 QueueType Queue;
1097 // Increasing count of \c StateNode items we have created. This is used
1098 // to create a deterministic order independent of the container.
1099 unsigned Count;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001100 encoding::Encoding Encoding;
Daniel Jasperf7935112012-12-03 18:12:45 +00001101};
1102
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001103class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001104public:
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001105 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1106 encoding::Encoding Encoding)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001107 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001108 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1109 Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001110 Lex.SetKeepWhitespaceMode(true);
1111 }
1112
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001113 ArrayRef<FormatToken *> lex() {
1114 assert(Tokens.empty());
1115 do {
1116 Tokens.push_back(getNextToken());
1117 } while (Tokens.back()->Tok.isNot(tok::eof));
1118 return Tokens;
1119 }
1120
1121 IdentifierTable &getIdentTable() { return IdentTable; }
1122
1123private:
1124 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001125 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001126 // Create a synthesized second '>' token.
1127 Token Greater = FormatTok->Tok;
1128 FormatTok = new (Allocator.Allocate()) FormatToken;
1129 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001130 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001131 FormatTok->Tok.getLocation().getLocWithOffset(1);
1132 FormatTok->WhitespaceRange =
1133 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001134 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001135 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001136 GreaterStashed = false;
1137 return FormatTok;
1138 }
1139
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001140 FormatTok = new (Allocator.Allocate()) FormatToken;
1141 Lex.LexFromRawLexer(FormatTok->Tok);
1142 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001143 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001144 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001145 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001146 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001147
1148 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001149 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001150 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001151 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001152 if (Newlines > 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001153 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001154 FormatTok->NewlinesBefore += Newlines;
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001155 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001156 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1157 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001158
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001159 Lex.LexFromRawLexer(FormatTok->Tok);
1160 Text = rawTokenText(FormatTok->Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001161 }
Manuel Klimekef920692013-01-07 07:56:50 +00001162
Manuel Klimek1abf7892013-01-04 23:34:14 +00001163 // In case the token starts with escaped newlines, we want to
1164 // take them into account as whitespace - this pattern is quite frequent
1165 // in macro definitions.
1166 // FIXME: What do we want to do with other escaped spaces, and escaped
1167 // spaces or newlines in the middle of tokens?
1168 // FIXME: Add a more explicit test.
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001169 while (Text.size() > 1 && Text[0] == '\\' && Text[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001170 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001171 WhitespaceLength += 2;
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001172 Text = Text.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001173 }
1174
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001175 TrailingWhitespace = 0;
1176 if (FormatTok->Tok.is(tok::comment)) {
1177 StringRef UntrimmedText = Text;
1178 Text = Text.rtrim();
1179 TrailingWhitespace = UntrimmedText.size() - Text.size();
1180 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001181 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001182 FormatTok->Tok.setIdentifierInfo(&Info);
1183 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001184 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001185 FormatTok->Tok.setKind(tok::greater);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001186 Text = Text.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001187 GreaterStashed = true;
1188 }
1189
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001190 // Now FormatTok is the next non-whitespace token.
1191 FormatTok->TokenText = Text;
1192 FormatTok->CodePointCount = encoding::getCodePointCount(Text, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001193
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001194 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001195 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001196 return FormatTok;
1197 }
1198
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001199 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001200 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001201 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001202 Lexer &Lex;
1203 SourceManager &SourceMgr;
1204 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001205 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001206 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1207 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001208
1209 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001210 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001211 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1212 Tok.getLength());
1213 }
1214};
1215
Daniel Jasperf7935112012-12-03 18:12:45 +00001216class Formatter : public UnwrappedLineConsumer {
1217public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001218 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001219 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001220 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001221 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1222 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1223 DEBUG(llvm::dbgs()
1224 << "File encoding: "
1225 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
1226 << "\n");
1227 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001228
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001229 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001230
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001231 tooling::Replacements format() {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001232 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001233
1234 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001235 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001236 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001237 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1238 Annotator.annotate(AnnotatedLines[i]);
1239 }
1240 deriveLocalStyle();
1241 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1242 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1243 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001244
1245 // Adapt level to the next line if this is a comment.
1246 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001247 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001248 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001249 if (NextNoneCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
1250 !AnnotatedLines[i].First->Next)
Daniel Jasperb67cc422013-04-09 17:46:55 +00001251 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1252 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001253 NextNoneCommentLine =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001254 AnnotatedLines[i].First->isNot(tok::r_brace) ? &AnnotatedLines[i]
1255 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001256 }
1257
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001258 std::vector<int> IndentForLevel;
1259 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001260 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001261 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001262 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1263 E = AnnotatedLines.end();
1264 I != E; ++I) {
1265 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001266 const FormatToken *FirstTok = TheLine.First;
1267 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001268
1269 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001270 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001271 FormatPPDirective = false;
1272 if (!FormatPPDirective && TheLine.InPPDirective &&
1273 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1274 FormatPPDirective = true;
1275
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001276 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001277 while (IndentForLevel.size() <= TheLine.Level)
1278 IndentForLevel.push_back(-1);
1279 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001280 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1281 if (static_cast<int>(Indent) + Offset >= 0)
1282 Indent += Offset;
1283 tryFitMultipleLinesInOne(Indent, I, E);
1284
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001285 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001286 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001287 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001288 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001289 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001290 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001291 }
1292 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001293 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001294 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001295 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001296 // Insert a break even if there is a structural error in case where
1297 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001298 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001299 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001300 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001301 } else {
1302 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001303 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1304 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001305 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001306 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001307 TheLine.First, Whitespaces, Encoding);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001308 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001309 IndentForLevel[TheLine.Level] = LevelIndent;
1310 PreviousLineWasTouched = true;
1311 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001312 // Format the first token if necessary, and notify the WhitespaceManager
1313 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001314 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1315 Tok = Tok->Next) {
1316 if (Tok == TheLine.First &&
1317 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1318 unsigned LevelIndent =
1319 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001320 // Remove trailing whitespace of the previous line if it was
1321 // touched.
1322 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1323 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1324 TheLine.InPPDirective);
1325 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001326 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001327 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001328
Manuel Klimek4fe43002013-05-22 12:51:29 +00001329 if (static_cast<int>(LevelIndent) - Offset >= 0)
1330 LevelIndent -= Offset;
1331 if (Tok->isNot(tok::comment))
1332 IndentForLevel[TheLine.Level] = LevelIndent;
1333 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001334 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001335 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001336 }
1337 // If we did not reformat this unwrapped line, the column at the end of
1338 // the last token is unchanged - thus, we can calculate the end of the
1339 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001340 PreviousLineWasTouched = false;
1341 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001342 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001343 }
1344 return Whitespaces.generateReplacements();
1345 }
1346
1347private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001348 void deriveLocalStyle() {
1349 unsigned CountBoundToVariable = 0;
1350 unsigned CountBoundToType = 0;
1351 bool HasCpp03IncompatibleFormat = false;
1352 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001353 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001354 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001355 FormatToken *Tok = AnnotatedLines[i].First->Next;
1356 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001357 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001358 bool SpacesBefore =
1359 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1360 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1361 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001362 if (SpacesBefore && !SpacesAfter)
1363 ++CountBoundToVariable;
1364 else if (!SpacesBefore && SpacesAfter)
1365 ++CountBoundToType;
1366 }
1367
Daniel Jasper400adc62013-02-08 15:28:42 +00001368 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001369 Tok->Previous->Type == TT_TemplateCloser &&
1370 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001371 HasCpp03IncompatibleFormat = true;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001372 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001373 }
1374 }
1375 if (Style.DerivePointerBinding) {
1376 if (CountBoundToType > CountBoundToVariable)
1377 Style.PointerBindsToType = true;
1378 else if (CountBoundToType < CountBoundToVariable)
1379 Style.PointerBindsToType = false;
1380 }
1381 if (Style.Standard == FormatStyle::LS_Auto) {
1382 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1383 : FormatStyle::LS_Cpp03;
1384 }
1385 }
1386
Manuel Klimekb95f5452013-02-08 17:38:27 +00001387 /// \brief Get the indent of \p Level from \p IndentForLevel.
1388 ///
1389 /// \p IndentForLevel must contain the indent for the level \c l
1390 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1391 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001392 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001393 if (IndentForLevel[Level] != -1)
1394 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001395 if (Level == 0)
1396 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001397 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001398 }
1399
1400 /// \brief Get the offset of the line relatively to the level.
1401 ///
1402 /// For example, 'public:' labels in classes are offset by 1 or 2
1403 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001404 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001405 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001406 return Style.AccessModifierOffset;
1407 return 0;
1408 }
1409
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001410 /// \brief Tries to merge lines into one.
1411 ///
1412 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1413 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001414 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001415 std::vector<AnnotatedLine>::iterator &I,
1416 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001417 // We can never merge stuff if there are trailing line comments.
1418 if (I->Last->Type == TT_LineComment)
1419 return;
1420
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001421 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001422 // If we already exceed the column limit, we set 'Limit' to 0. The different
1423 // tryMerge..() functions can then decide whether to still do merging.
1424 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001425
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001426 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001427 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001428
Daniel Jasperabca58c2013-05-15 14:09:55 +00001429 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001430 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001431 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001432 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001433 tryMergeSimpleControlStatement(I, E, Limit);
1434 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001435 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001436 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001437 } else if (I->InPPDirective &&
1438 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001439 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001440 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001441 }
1442
Daniel Jasper39825ea2013-01-14 15:40:57 +00001443 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1444 std::vector<AnnotatedLine>::iterator E,
1445 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001446 if (Limit == 0)
1447 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001448 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001449 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001450 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001451 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001452 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001453 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001454 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001455 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001456 join(Line, *(++I));
1457 }
1458
Daniel Jasper3a685df2013-05-16 12:12:21 +00001459 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1460 std::vector<AnnotatedLine>::iterator E,
1461 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001462 if (Limit == 0)
1463 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001464 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001465 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001466 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001467 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001468 if (Line.Last->isNot(tok::r_paren))
1469 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001470 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001471 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001472 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1473 tok::kw_while) ||
1474 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001475 return;
1476 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001477 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1478 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001479 return;
1480 join(Line, *(++I));
1481 }
1482
1483 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001484 std::vector<AnnotatedLine>::iterator E,
1485 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001486 // No merging if the brace already is on the next line.
1487 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1488 return;
1489
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001490 // First, check that the current line allows merging. This is the case if
1491 // we're not in a control flow statement and the last token is an opening
1492 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001493 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001494 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1495 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001496 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001497 // This gets rid of all ObjC @ keywords and methods.
1498 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001499 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001500
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001501 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001502 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
1503 (Tok->getNextNoneComment() == NULL ||
1504 Tok->getNextNoneComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001505 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001506 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001507 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001508 join(Line, *(I + 1));
1509 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001510 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001511 // Check that we still have three lines and they fit into the limit.
1512 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1513 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001514 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001515
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001516 // Second, check that the next line does not contain any braces - if it
1517 // does, readability declines when putting it into a single line.
1518 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1519 return;
1520 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001521 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001522 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001523 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001524 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001525
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001526 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001527 Tok = (I + 2)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001528 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001529 Tok->MustBreakBefore)
1530 return;
1531
1532 join(Line, *(I + 1));
1533 join(Line, *(I + 2));
1534 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001535 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001536 }
1537
1538 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1539 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001540 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1541 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001542 }
1543
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001544 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001545 assert(!A.Last->Next);
1546 assert(!B.First->Previous);
1547 A.Last->Next = B.First;
1548 B.First->Previous = A.Last;
1549 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1550 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1551 Tok->TotalLength += LengthA;
1552 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001553 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001554 }
1555
Daniel Jasper97b89482013-03-13 07:49:51 +00001556 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001557 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1558 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1559 Ranges[i].getBegin()) &&
1560 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1561 Range.getBegin()))
1562 return true;
1563 }
1564 return false;
1565 }
1566
1567 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001568 const FormatToken *First = TheLine.First;
1569 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001570 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001571 First->WhitespaceRange.getBegin().getLocWithOffset(
1572 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001573 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001574 return touchesRanges(LineRange);
1575 }
1576
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001577 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1578 std::vector<AnnotatedLine>::iterator E) {
1579 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001580 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001581 return false;
1582 if (touchesLine(*I))
1583 return true;
1584 }
1585 return false;
1586 }
1587
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001588 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001589 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001590 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001591 First->WhitespaceRange.getBegin(),
1592 First->WhitespaceRange.getBegin().getLocWithOffset(
1593 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001594 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001595 }
1596
1597 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001598 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001599 }
1600
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001601 /// \brief Add a new line and the required indent before the first Token
1602 /// of the \c UnwrappedLine if there was no structural parsing error.
1603 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001604 void formatFirstToken(const FormatToken &RootToken,
1605 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001606 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001607 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001608 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001609 // Remove empty lines before "}" where applicable.
1610 if (RootToken.is(tok::r_brace) &&
1611 (!RootToken.Next ||
1612 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1613 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001614 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001615 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001616
Manuel Klimek4fe43002013-05-22 12:51:29 +00001617 // Insert extra new line before access specifiers.
1618 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001619 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001620 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001621
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001622 Whitespaces.replaceWhitespace(
1623 RootToken, Newlines, Indent, Indent,
1624 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001625 }
1626
Daniel Jasperf7935112012-12-03 18:12:45 +00001627 FormatStyle Style;
1628 Lexer &Lex;
1629 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001630 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001631 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001632 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001633
1634 encoding::Encoding Encoding;
Daniel Jasperf7935112012-12-03 18:12:45 +00001635};
1636
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001637tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1638 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001639 std::vector<CharSourceRange> Ranges) {
1640 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001641 return formatter.format();
1642}
1643
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001644tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1645 std::vector<tooling::Range> Ranges,
1646 StringRef FileName) {
1647 FileManager Files((FileSystemOptions()));
1648 DiagnosticsEngine Diagnostics(
1649 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1650 new DiagnosticOptions);
1651 SourceManager SourceMgr(Diagnostics, Files);
1652 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1653 const clang::FileEntry *Entry =
1654 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1655 SourceMgr.overrideFileContents(Entry, Buf);
1656 FileID ID =
1657 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1658 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1659 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1660 std::vector<CharSourceRange> CharRanges;
1661 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1662 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1663 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1664 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1665 }
1666 return reformat(Style, Lex, SourceMgr, CharRanges);
1667}
1668
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001669LangOptions getFormattingLangOpts() {
1670 LangOptions LangOpts;
1671 LangOpts.CPlusPlus = 1;
1672 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001673 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001674 LangOpts.Bool = 1;
1675 LangOpts.ObjC1 = 1;
1676 LangOpts.ObjC2 = 1;
1677 return LangOpts;
1678}
1679
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001680} // namespace format
1681} // namespace clang