blob: 008693619cd5c5983fc4ddfda5efc09996abbfe2 [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 Kornienko58611712013-07-04 12:02:44 +000090 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
91 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +000092 IO.mapOptional("BreakBeforeBinaryOperators",
93 Style.BreakBeforeBinaryOperators);
94 IO.mapOptional("BreakConstructorInitializersBeforeComma",
95 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +000096 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
97 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
98 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
99 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
100 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000101 IO.mapOptional("ExperimentalAutoDetectBinPacking",
102 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000103 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
104 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
105 IO.mapOptional("ObjCSpaceBeforeProtocolList",
106 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000107 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
108 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000109 IO.mapOptional("PenaltyBreakFirstLessLess",
110 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000111 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
112 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
113 Style.PenaltyReturnTypeOnItsOwnLine);
114 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
115 IO.mapOptional("SpacesBeforeTrailingComments",
116 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000117 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000118 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000119 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000120 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000121 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000122 IO.mapOptional("IndentFunctionDeclarationAfterType",
123 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000124 }
125};
126}
127}
128
Daniel Jasperf7935112012-12-03 18:12:45 +0000129namespace clang {
130namespace format {
131
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000132void setDefaultPenalties(FormatStyle &Style) {
133 Style.PenaltyBreakComment = 45;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000134 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000135 Style.PenaltyBreakString = 1000;
136 Style.PenaltyExcessCharacter = 1000000;
137}
138
Daniel Jasperf7935112012-12-03 18:12:45 +0000139FormatStyle getLLVMStyle() {
140 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000141 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000142 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000143 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000144 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000145 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000146 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000147 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000148 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000149 LLVMStyle.BreakBeforeBinaryOperators = false;
150 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
151 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000152 LLVMStyle.ColumnLimit = 80;
153 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000154 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000155 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000156 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000157 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000158 LLVMStyle.IndentFunctionDeclarationAfterType = false;
159 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000160 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000161 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000162 LLVMStyle.PointerBindsToType = false;
163 LLVMStyle.SpacesBeforeTrailingComments = 1;
164 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000165 LLVMStyle.UseTab = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000166
167 setDefaultPenalties(LLVMStyle);
168 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
169
Daniel Jasperf7935112012-12-03 18:12:45 +0000170 return LLVMStyle;
171}
172
173FormatStyle getGoogleStyle() {
174 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000176 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000177 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000178 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000179 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000180 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000181 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000182 GoogleStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000183 GoogleStyle.BreakBeforeBinaryOperators = false;
184 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
185 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000186 GoogleStyle.ColumnLimit = 80;
187 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000188 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000189 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000190 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000191 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000192 GoogleStyle.IndentFunctionDeclarationAfterType = true;
193 GoogleStyle.IndentWidth = 2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000194 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000195 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000196 GoogleStyle.PointerBindsToType = true;
197 GoogleStyle.SpacesBeforeTrailingComments = 2;
198 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000199 GoogleStyle.UseTab = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000200
201 setDefaultPenalties(GoogleStyle);
202 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
203
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 return GoogleStyle;
205}
206
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000207FormatStyle getChromiumStyle() {
208 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000209 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000210 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000211 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000212 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000213 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000214 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000215 return ChromiumStyle;
216}
217
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000218FormatStyle getMozillaStyle() {
219 FormatStyle MozillaStyle = getLLVMStyle();
220 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
221 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
222 MozillaStyle.DerivePointerBinding = true;
223 MozillaStyle.IndentCaseLabels = true;
224 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
225 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
226 MozillaStyle.PointerBindsToType = true;
227 return MozillaStyle;
228}
229
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000230FormatStyle getWebKitStyle() {
231 FormatStyle Style = getLLVMStyle();
232 Style.ColumnLimit = 0;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000233 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000234 Style.BreakBeforeBinaryOperators = true;
235 Style.BreakConstructorInitializersBeforeComma = true;
236 Style.IndentWidth = 4;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000237 Style.PointerBindsToType = true;
238 return Style;
239}
240
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000241bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000242 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000243 *Style = getLLVMStyle();
244 else if (Name.equals_lower("chromium"))
245 *Style = getChromiumStyle();
246 else if (Name.equals_lower("mozilla"))
247 *Style = getMozillaStyle();
248 else if (Name.equals_lower("google"))
249 *Style = getGoogleStyle();
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000250 else if (Name.equals_lower("webkit"))
251 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000252 else
253 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000254
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000255 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000256}
257
258llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000259 if (Text.trim().empty())
260 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000261 llvm::yaml::Input Input(Text);
262 Input >> *Style;
263 return Input.error();
264}
265
266std::string configurationAsText(const FormatStyle &Style) {
267 std::string Text;
268 llvm::raw_string_ostream Stream(Text);
269 llvm::yaml::Output Output(Stream);
270 // We use the same mapping method for input and output, so we need a non-const
271 // reference here.
272 FormatStyle NonConstStyle = Style;
273 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000274 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000275}
276
Daniel Jasperacc33662013-02-08 08:22:00 +0000277// Returns the length of everything up to the first possible line break after
278// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000279static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000280 if (Tok.MatchingParen == NULL)
281 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000282 FormatToken *End = Tok.MatchingParen;
283 while (End->Next && !End->Next->CanBreakBefore) {
284 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000285 }
286 return End->TotalLength - Tok.TotalLength + 1;
287}
288
Craig Topperaf35e852013-06-30 22:29:28 +0000289namespace {
290
Daniel Jasperf7935112012-12-03 18:12:45 +0000291class UnwrappedLineFormatter {
292public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000293 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000294 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000295 const FormatToken *RootToken,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000296 WhitespaceManager &Whitespaces,
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000297 encoding::Encoding Encoding,
298 bool BinPackInconclusiveFunctions)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000299 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000300 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000301 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
302 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000303
Manuel Klimek1abf7892013-01-04 23:34:14 +0000304 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000305 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000306 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000307 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000308 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000309 State.NextToken = RootToken;
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000310 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
311 /*AvoidBinPacking=*/false,
312 /*NoLineBreak=*/false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000313 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000314 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000315 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000316 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000317 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000318 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000319
320 // The first token has already been indented and thus consumed.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000321 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000322
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000323 if (Style.ColumnLimit == 0) {
324 formatWithoutColumnLimit(State);
325 return;
326 }
327
Daniel Jasper4b866272013-02-01 11:00:45 +0000328 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000329 unsigned ColumnLimit = Style.ColumnLimit;
330 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000331 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000332 ColumnLimit = getColumnLimit();
333 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000334 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000335 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000336 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000337 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000338
Daniel Jasperacc33662013-02-08 08:22:00 +0000339 // If the ObjC method declaration does not fit on a line, we should format
340 // it with one arg per line.
341 if (Line.Type == LT_ObjCMethodDecl)
342 State.Stack.back().BreakBeforeParameter = true;
343
Daniel Jasper4b866272013-02-01 11:00:45 +0000344 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000345 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000346 }
347
348private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000349 void DebugTokenState(const FormatToken &FormatTok) {
350 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000351 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000352 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000353 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000354 }
355
Daniel Jasper337816e2013-01-11 10:22:12 +0000356 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000357 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000358 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000359 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
360 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000361 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000362 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000363 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
364 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000365
Daniel Jasperf7935112012-12-03 18:12:45 +0000366 /// \brief The position to which a specific parenthesis level needs to be
367 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000368 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000369
Daniel Jaspere9de2602012-12-06 09:56:08 +0000370 /// \brief The position of the last space on each level.
371 ///
372 /// Used e.g. to break like:
373 /// functionCall(Parameter, otherCall(
374 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000375 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000376
Daniel Jaspere9de2602012-12-06 09:56:08 +0000377 /// \brief The position the first "<<" operator encountered on each level.
378 ///
379 /// Used to align "<<" operators. 0 if no such operator has been encountered
380 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000382
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000383 /// \brief Whether a newline needs to be inserted before the block's closing
384 /// brace.
385 ///
386 /// We only want to insert a newline before the closing brace if there also
387 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000388 bool BreakBeforeClosingBrace;
389
Daniel Jasperca6623b2013-01-28 12:45:14 +0000390 /// \brief The column of a \c ? in a conditional expression;
391 unsigned QuestionColumn;
392
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000393 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
394 /// lines, in this context.
395 bool AvoidBinPacking;
396
397 /// \brief Break after the next comma (or all the commas in this context if
398 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000399 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000400
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000401 /// \brief Line breaking in this context would break a formatting rule.
402 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000403
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000404 /// \brief The position of the colon in an ObjC method declaration/call.
405 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000406
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000407 /// \brief The start of the most recent function in a builder-type call.
408 unsigned StartOfFunctionCall;
409
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000410 /// \brief Contains the start of array subscript expressions, so that they
411 /// can be aligned.
412 unsigned StartOfArraySubscripts;
413
Daniel Jasperc238c872013-04-02 14:33:13 +0000414 /// \brief If a nested name specifier was broken over multiple lines, this
415 /// contains the start column of the second line. Otherwise 0.
416 unsigned NestedNameSpecifierContinuation;
417
418 /// \brief If a call expression was broken over multiple lines, this
419 /// contains the start column of the second line. Otherwise 0.
420 unsigned CallContinuation;
421
Daniel Jaspera628c982013-04-03 13:36:17 +0000422 /// \brief The column of the first variable name in a variable declaration.
423 ///
424 /// Used to align further variables if necessary.
425 unsigned VariablePos;
426
Daniel Jasperee7539a2013-07-08 14:25:23 +0000427 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000428 ///
Daniel Jasperee7539a2013-07-08 14:25:23 +0000429 /// The first line break in a certain \c ParenState causes extra penalty so
430 /// that clang-format prefers similar breaks, i.e. breaks in the same
431 /// parenthesis.
432 bool ContainsLineBreak;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000433
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 bool operator<(const ParenState &Other) const {
435 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000436 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 if (LastSpace != Other.LastSpace)
438 return LastSpace < Other.LastSpace;
439 if (FirstLessLess != Other.FirstLessLess)
440 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000441 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
442 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000443 if (QuestionColumn != Other.QuestionColumn)
444 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000445 if (AvoidBinPacking != Other.AvoidBinPacking)
446 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000447 if (BreakBeforeParameter != Other.BreakBeforeParameter)
448 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000449 if (NoLineBreak != Other.NoLineBreak)
450 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000451 if (ColonPos != Other.ColonPos)
452 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000453 if (StartOfFunctionCall != Other.StartOfFunctionCall)
454 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000455 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
456 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasperc238c872013-04-02 14:33:13 +0000457 if (CallContinuation != Other.CallContinuation)
458 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000459 if (VariablePos != Other.VariablePos)
460 return VariablePos < Other.VariablePos;
Daniel Jasperee7539a2013-07-08 14:25:23 +0000461 if (ContainsLineBreak != Other.ContainsLineBreak)
462 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000463 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000464 }
465 };
466
467 /// \brief The current state when indenting a unwrapped line.
468 ///
469 /// As the indenting tries different combinations this is copied by value.
470 struct LineState {
471 /// \brief The number of used columns in the current line.
472 unsigned Column;
473
474 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000475 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000476
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000477 /// \brief \c true if this line contains a continued for-loop section.
478 bool LineContainsContinuedForLoopSection;
479
Daniel Jasper400adc62013-02-08 15:28:42 +0000480 /// \brief The level of nesting inside (), [], <> and {}.
481 unsigned ParenLevel;
482
Daniel Jasper40c36c52013-02-18 11:05:07 +0000483 /// \brief The \c ParenLevel at the start of this line.
484 unsigned StartOfLineLevel;
485
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000486 /// \brief The lowest \c ParenLevel on the current line.
487 unsigned LowestLevelOnLine;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000488
Manuel Klimek02f640a2013-02-20 15:25:48 +0000489 /// \brief The start column of the string literal, if we're in a string
490 /// literal sequence, 0 otherwise.
491 unsigned StartOfStringLiteral;
492
Daniel Jasper337816e2013-01-11 10:22:12 +0000493 /// \brief A stack keeping track of properties applying to parenthesis
494 /// levels.
495 std::vector<ParenState> Stack;
496
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000497 /// \brief Ignore the stack of \c ParenStates for state comparison.
498 ///
499 /// In long and deeply nested unwrapped lines, the current algorithm can
500 /// be insufficient for finding the best formatting with a reasonable amount
501 /// of time and memory. Setting this flag will effectively lead to the
502 /// algorithm not analyzing some combinations. However, these combinations
503 /// rarely contain the optimal solution: In short, accepting a higher
504 /// penalty early would need to lead to different values in the \c
505 /// ParenState stack (in an otherwise identical state) and these different
506 /// values would need to lead to a significant amount of avoided penalty
507 /// later.
508 ///
509 /// FIXME: Come up with a better algorithm instead.
510 bool IgnoreStackForComparison;
511
Daniel Jasper337816e2013-01-11 10:22:12 +0000512 /// \brief Comparison operator to be able to used \c LineState in \c map.
513 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000514 if (NextToken != Other.NextToken)
515 return NextToken < Other.NextToken;
516 if (Column != Other.Column)
517 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000518 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000519 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000520 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000521 if (ParenLevel != Other.ParenLevel)
522 return ParenLevel < Other.ParenLevel;
523 if (StartOfLineLevel != Other.StartOfLineLevel)
524 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000525 if (LowestLevelOnLine != Other.LowestLevelOnLine)
526 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000527 if (StartOfStringLiteral != Other.StartOfStringLiteral)
528 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000529 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
530 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000531 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000532 }
533 };
534
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000535 /// \brief Formats the line starting at \p State, simply keeping all of the
536 /// input's line breaking decisions.
537 void formatWithoutColumnLimit(LineState &State) {
538 while (State.NextToken != NULL) {
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000539 bool Newline = mustBreak(State) ||
540 (canBreak(State) && State.NextToken->NewlinesBefore > 0);
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000541 addTokenToState(Newline, /*DryRun=*/false, State);
542 }
543 }
544
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000545 /// \brief Appends the next token to \p State and updates information
546 /// necessary for indentation.
547 ///
Nico Weberf579ab32013-06-26 02:42:46 +0000548 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000549 /// line break and necessary indentation otherwise.
550 ///
551 /// If \p DryRun is \c false, also creates and stores the required
552 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000553 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000554 const FormatToken &Current = *State.NextToken;
555 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000556
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000557 // Extra penalty that needs to be added because of the way certain line
558 // breaks are chosen.
559 unsigned ExtraPenalty = 0;
560
Daniel Jasper291f9362013-03-20 15:58:10 +0000561 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000562 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000563 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
564 State.NextToken->WhitespaceRange.getEnd()) -
565 SourceMgr.getSpellingColumnNumber(
566 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000567 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000568 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000569 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000570 }
571
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000572 // If we are continuing an expression, we want to indent an extra 4 spaces.
573 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000574 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000575 if (Newline) {
Daniel Jasperee7539a2013-07-08 14:25:23 +0000576 State.Stack.back().ContainsLineBreak = true;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000577 if (Current.is(tok::r_brace)) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000578 if (Current.BlockKind == BK_BracedInit)
579 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
580 else
Daniel Jasper51efbad2013-07-11 21:27:40 +0000581 State.Column = FirstIndent;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000582 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000583 State.StartOfStringLiteral != 0) {
584 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000585 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000586 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000587 State.Stack.back().FirstLessLess != 0) {
588 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000589 } else if (Current.isOneOf(tok::period, tok::arrow) &&
590 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000591 if (State.Stack.back().CallContinuation == 0) {
592 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000593 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000594 } else {
595 State.Column = State.Stack.back().CallContinuation;
596 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000597 } else if (Current.Type == TT_ConditionalExpr) {
598 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000599 } else if (Previous.is(tok::comma) &&
600 State.Stack.back().VariablePos != 0) {
601 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000602 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6331da02013-07-09 07:43:55 +0000603 ((Current.Type == TT_StartOfName ||
604 Current.is(tok::kw_operator)) &&
605 State.ParenLevel == 0 &&
Manuel Klimek836c2862013-06-21 17:25:42 +0000606 (!Style.IndentFunctionDeclarationAfterType ||
607 Line.StartsDefinition))) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000608 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000609 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000610 if (State.Stack.back().ColonPos > Current.CodePointCount) {
611 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000612 } else {
613 State.Column = State.Stack.back().Indent;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000614 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000615 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000616 } else if (Current.is(tok::l_square) &&
617 Current.Type != TT_ObjCMethodExpr) {
618 if (State.Stack.back().StartOfArraySubscripts != 0)
619 State.Column = State.Stack.back().StartOfArraySubscripts;
620 else
621 State.Column = ContinuationIndent;
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000622 } else if (Current.Type == TT_StartOfName ||
623 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000624 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000625 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000626 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000627 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000628 // Ensure that we fall back to indenting 4 spaces instead of just
629 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000630 if (State.Column == FirstIndent)
631 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000632 }
633
Daniel Jasper54a86022013-02-15 11:07:25 +0000634 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000635 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000636 if ((Previous.isOneOf(tok::comma, tok::semi) &&
637 !State.Stack.back().AvoidBinPacking) ||
638 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000639 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000640 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
641 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000642
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000643 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000644 unsigned NewLines = 1;
Alexander Kornienkof370ad92013-06-12 19:04:12 +0000645 if (Current.is(tok::comment))
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000646 NewLines = std::max(
647 NewLines,
648 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000649 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
650 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000651 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000652
Daniel Jasper185de242013-07-11 13:48:16 +0000653 if (!Current.isTrailingComment())
654 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000655 if (Current.isOneOf(tok::arrow, tok::period) &&
656 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000657 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000658 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000659 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000660
661 // Any break on this level means that the parent level has been broken
662 // and we need to avoid bin packing there.
663 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
664 State.Stack[i].BreakBeforeParameter = true;
665 }
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000666 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000667 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000668 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000669 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000670 State.Stack.back().BreakBeforeParameter = true;
671
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000672 // If we break after {, we should also break before the corresponding }.
673 if (Previous.is(tok::l_brace))
674 State.Stack.back().BreakBeforeClosingBrace = true;
675
676 if (State.Stack.back().AvoidBinPacking) {
677 // If we are breaking after '(', '{', '<', this is not bin packing
678 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000679 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
680 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000681 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
682 Line.MustBeDeclaration))
683 State.Stack.back().BreakBeforeParameter = true;
684 }
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000685
686 // Breaking before the first "<<" is generally not desirable.
687 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
688 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
689
Daniel Jasperf7935112012-12-03 18:12:45 +0000690 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000691 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000692 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000693 State.Stack.back().VariablePos == 0) {
694 State.Stack.back().VariablePos = State.Column;
695 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000696 const FormatToken *Tok = &Previous;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000697 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
698 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000699 if (Tok->SpacesRequiredBefore != 0)
700 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000701 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000702 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000703 if (Previous.PartOfMultiVariableDeclStmt)
704 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
705 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000706
Daniel Jaspereef30492013-02-11 12:36:37 +0000707 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000708
Daniel Jasperf7935112012-12-03 18:12:45 +0000709 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000710 Whitespaces.replaceWhitespace(Current, 0, Spaces,
711 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000712
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000713 if (Current.Type == TT_ObjCSelectorName &&
714 State.Stack.back().ColonPos == 0) {
715 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000716 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000717 State.Stack.back().ColonPos =
718 State.Stack.back().Indent + Current.LongestObjCSelectorName;
719 else
720 State.Stack.back().ColonPos =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000721 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000722 }
723
Daniel Jasperc04baae2013-04-10 09:49:49 +0000724 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000725 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000726 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000727 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
728 State.Stack.back().AvoidBinPacking)
729 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000730
Daniel Jaspere9de2602012-12-06 09:56:08 +0000731 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000732 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000733 // Treat the condition inside an if as if it was a second function
734 // parameter, i.e. let nested calls have an indent of 4.
735 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000736 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000737 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000738 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000739 Previous.Type == TT_ConditionalExpr ||
740 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000741 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000742 Current.FakeLParens.empty()))
743 // Always indent relative to the RHS of the expression unless this is a
744 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000745 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000746 else if (Previous.Type == TT_InheritanceColon)
747 State.Stack.back().Indent = State.Column;
Daniel Jasperbd058882013-07-09 11:57:27 +0000748 else if (Previous.opensScope()) {
749 // If a function has multiple parameters (including a single parameter
Daniel Jasper6cdec7c2013-07-09 14:36:48 +0000750 // that is a binary expression) or a trailing call, indent all
Daniel Jasperbd058882013-07-09 11:57:27 +0000751 // parameters from the opening parenthesis. This avoids confusing
752 // indents like:
753 // OuterFunction(InnerFunctionCall(
754 // ParameterToInnerFunction),
755 // SecondParameterToOuterFunction);
756 bool HasMultipleParameters = !Current.FakeLParens.empty();
757 bool HasTrailingCall = false;
758 if (Previous.MatchingParen) {
759 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
760 if (Next && Next->isOneOf(tok::period, tok::arrow))
761 HasTrailingCall = true;
762 }
763 if (HasMultipleParameters || HasTrailingCall)
764 State.Stack.back().LastSpace = State.Column;
765 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000766 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000767
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000768 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000769 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000770
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000771 /// \brief Mark the next token as consumed in \p State and modify its stacks
772 /// accordingly.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000773 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000774 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000775 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000776
Daniel Jaspereead02b2013-02-14 08:42:54 +0000777 if (Current.Type == TT_InheritanceColon)
778 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000779 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
780 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000781 if (Current.is(tok::l_square) &&
782 State.Stack.back().StartOfArraySubscripts == 0)
783 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000784 if (Current.is(tok::question))
785 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000786 if (!Current.opensScope() && !Current.closesScope())
787 State.LowestLevelOnLine =
788 std::min(State.LowestLevelOnLine, State.ParenLevel);
789 if (Current.isOneOf(tok::period, tok::arrow) &&
790 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
791 State.Stack.back().StartOfFunctionCall =
792 Current.LastInChainOfCalls ? 0
793 : State.Column + Current.CodePointCount;
Daniel Jasper37905f72013-02-21 15:00:29 +0000794 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000795 // Indent 2 from the column, so:
796 // SomeClass::SomeClass()
797 // : First(...), ...
798 // Next(...)
799 // ^ line up here.
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000800 if (!Style.BreakConstructorInitializersBeforeComma)
801 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000802 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
803 State.Stack.back().AvoidBinPacking = true;
804 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000805 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000806
Daniel Jasper6bee6822013-04-08 20:33:42 +0000807 // If return returns a binary expression, align after it.
808 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
809 State.Stack.back().LastSpace = State.Column + 7;
810
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000811 // In ObjC method declaration we align on the ":" of parameters, but we need
812 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000813 if (Current.Type == TT_ObjCMethodSpecifier)
814 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000815
Daniel Jasper400adc62013-02-08 15:28:42 +0000816 // Insert scopes created by fake parenthesis.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000817 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000818 // Don't add extra indentation for the first fake parenthesis after
819 // 'return', assignements or opening <({[. The indentation for these cases
820 // is special cased.
821 bool SkipFirstExtraIndent =
822 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000823 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000824 Previous->getPrecedence() == prec::Assignment));
Craig Topper61ac9062013-07-08 03:55:09 +0000825 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasper6bee6822013-04-08 20:33:42 +0000826 I = Current.FakeLParens.rbegin(),
827 E = Current.FakeLParens.rend();
828 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000829 ParenState NewParenState = State.Stack.back();
Daniel Jasperee7539a2013-07-08 14:25:23 +0000830 NewParenState.ContainsLineBreak = false;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000831 NewParenState.Indent =
832 std::max(std::max(State.Column, NewParenState.Indent),
833 State.Stack.back().LastSpace);
834
835 // Always indent conditional expressions. Never indent expression where
836 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
837 // prec::Assignment) as those have different indentation rules. Indent
838 // other expression, unless the indentation needs to be skipped.
839 if (*I == prec::Conditional ||
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000840 (!SkipFirstExtraIndent && *I > prec::Assignment &&
841 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6bee6822013-04-08 20:33:42 +0000842 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000843 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000844 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000845 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000846 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000847 }
848
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000849 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000850 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000851 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000852 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000853 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000854 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000855 if (Current.is(tok::l_brace)) {
Daniel Jasper6ab54682013-07-16 18:22:10 +0000856 NewIndent =
857 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000858 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000859 AvoidBinPacking = NextNoComment &&
860 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000861 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000862 NewIndent =
863 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000864 AvoidBinPacking = !Style.BinPackParameters ||
865 (Style.ExperimentalAutoDetectBinPacking &&
866 (Current.PackingKind == PPK_OnePerLine ||
867 (!BinPackInconclusiveFunctions &&
868 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000869 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000870
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000871 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
872 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000873 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000874 }
875
Daniel Jasperacc33662013-02-08 08:22:00 +0000876 // If this '[' opens an ObjC call, determine whether all parameters fit into
877 // one line and put one per line if they don't.
878 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
879 Current.MatchingParen != NULL) {
880 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
881 State.Stack.back().BreakBeforeParameter = true;
882 }
883
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000884 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000885 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000886 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000887 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000888 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000889 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000890 --State.ParenLevel;
891 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000892 if (Current.is(tok::r_square)) {
893 // If this ends the array subscript expr, reset the corresponding value.
894 const FormatToken *NextNonComment = Current.getNextNonComment();
895 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasperfa21c072013-07-15 14:33:14 +0000896 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000897 }
Daniel Jasper400adc62013-02-08 15:28:42 +0000898
899 // Remove scopes created by fake parenthesis.
900 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000901 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000902 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000903 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000904 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000905
Daniel Jasper47a04442013-05-13 20:50:15 +0000906 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000907 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000908 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
909 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000910 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000911 }
912
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000913 State.Column += Current.CodePointCount;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000914
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000915 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000916
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000917 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
918 Current.is(tok::string_literal))
919 return 0;
920
Manuel Klimek1998ea22013-02-20 10:15:13 +0000921 return breakProtrudingToken(Current, State, DryRun);
922 }
923
924 /// \brief If the current token sticks out over the end of the line, break
925 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000926 ///
927 /// \returns An extra penalty if a token was broken, otherwise 0.
928 ///
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000929 /// The returned penalty will cover the cost of the additional line breaks and
930 /// column limit violation in all lines except for the last one. The penalty
931 /// for the column limit violation in the last line (and in single line
932 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000933 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000934 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000935 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000936 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000937 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000938 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000939 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000940
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000941 if (Current.is(tok::string_literal) &&
942 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000943 // Only break up default narrow strings.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000944 if (!Current.TokenText.startswith("\""))
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000945 return 0;
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000946 // Don't break string literals with escaped newlines. As clang-format must
947 // not change the string's content, it is unlikely that we'll end up with
948 // a better format.
949 if (Current.TokenText.find("\\\n") != StringRef::npos)
950 return 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000951 // Exempts unterminated string literals from line breaking. The user will
952 // likely want to terminate the string before any line breaking is done.
953 if (Current.IsUnterminatedLiteral)
954 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000955
Alexander Kornienkobe633902013-06-14 11:46:10 +0000956 Token.reset(new BreakableStringLiteral(Current, StartColumn,
957 Line.InPPDirective, Encoding));
Alexander Kornienko94042342013-07-16 23:47:22 +0000958 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000959 Token.reset(new BreakableBlockComment(
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000960 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000961 Line.InPPDirective, Encoding));
Daniel Jasper4a4be012013-05-06 10:24:51 +0000962 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000963 (Current.Previous == NULL ||
964 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000965 // Don't break line comments with escaped newlines. These look like
966 // separate line comments, but in fact contain a single line comment with
967 // multiple lines including leading whitespace and the '//' markers.
968 //
969 // FIXME: If we want to handle them correctly, we'll need to adjust
970 // leading whitespace in consecutive lines when changing indentation of
971 // the first line similar to what we do with block comments.
972 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
973 if (EscapedNewlinePos != StringRef::npos) {
974 State.Column =
975 StartColumn +
976 encoding::getCodePointCount(
977 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
978 1;
979 return 0;
980 }
981
Alexander Kornienkobe633902013-06-14 11:46:10 +0000982 Token.reset(new BreakableLineComment(Current, StartColumn,
983 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000984 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000985 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000986 }
Alexander Kornienkobe633902013-06-14 11:46:10 +0000987 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000988 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000989
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000990 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000991 bool BreakInserted = false;
992 unsigned Penalty = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000993 unsigned RemainingTokenColumns = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +0000994 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
995 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000996 if (!DryRun)
997 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000998 unsigned TailOffset = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000999 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001000 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001001 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001002 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +00001003 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkoaa620e12013-07-01 13:42:42 +00001004 if (Split.first == StringRef::npos) {
1005 // The last line's penalty is handled in addNextStateToQueue().
1006 if (LineIndex < EndIndex - 1)
1007 Penalty += Style.PenaltyExcessCharacter *
1008 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001009 break;
Alexander Kornienkoaa620e12013-07-01 13:42:42 +00001010 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001011 assert(Split.first != 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001012 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001013 LineIndex, TailOffset + Split.first + Split.second,
1014 StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001015 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienkobe633902013-06-14 11:46:10 +00001016 if (!DryRun)
1017 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001018 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
1019 : Style.PenaltyBreakComment;
1020 unsigned ColumnsUsed =
1021 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1022 if (ColumnsUsed > getColumnLimit()) {
1023 Penalty +=
1024 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
1025 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001026 TailOffset += Split.first + Split.second;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001027 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001028 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001029 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001030 }
1031
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001032 State.Column = RemainingTokenColumns;
1033
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001034 if (BreakInserted) {
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +00001035 // If we break the token inside a parameter list, we need to break before
1036 // the next parameter on all levels, so that the next parameter is clearly
1037 // visible. Line comments already introduce a break.
1038 if (Current.Type != TT_LineComment) {
1039 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1040 State.Stack[i].BreakBeforeParameter = true;
1041 }
1042
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001043 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001044 }
Manuel Klimek1998ea22013-02-20 10:15:13 +00001045 return Penalty;
1046 }
1047
Daniel Jasper2df93312013-01-09 10:16:05 +00001048 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001049 // In preprocessor directives reserve two chars for trailing " \"
1050 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +00001051 }
1052
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001053 /// \brief An edge in the solution space from \c Previous->State to \c State,
1054 /// inserting a newline dependent on the \c NewLine.
1055 struct StateNode {
1056 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001057 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001058 LineState State;
1059 bool NewLine;
1060 StateNode *Previous;
1061 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001062
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001063 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1064 ///
1065 /// In case of equal penalties, we want to prefer states that were inserted
1066 /// first. During state generation we make sure that we insert states first
1067 /// that break the line as late as possible.
1068 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1069
1070 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1071 /// \c State has the given \c OrderedPenalty.
1072 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1073
1074 /// \brief The BFS queue type.
1075 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1076 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001077
1078 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001080 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1081 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1082 /// find the shortest path (the one with lowest penalty) from \p InitialState
1083 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +00001084 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001085 std::set<LineState> Seen;
1086
Daniel Jasper4b866272013-02-01 11:00:45 +00001087 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001088 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001089 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1090 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1091 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001092
1093 // While not empty, take first element and follow edges.
1094 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001095 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001096 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001097 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001098 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001099 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001100 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001101 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001102
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001103 // Cut off the analysis of certain solutions if the analysis gets too
1104 // complex. See description of IgnoreStackForComparison.
1105 if (Count > 10000)
1106 Node->State.IgnoreStackForComparison = true;
1107
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001108 if (!Seen.insert(Node->State).second)
1109 // State already examined with lower penalty.
1110 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001111
Nico Weber9096fc02013-06-26 00:30:14 +00001112 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1113 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001114 }
1115
1116 if (Queue.empty())
1117 // We were unable to find a solution, do nothing.
1118 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +00001119 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001120
Daniel Jasper4b866272013-02-01 11:00:45 +00001121 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001122 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +00001123 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1124 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001125 }
1126
1127 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001128 std::deque<StateNode *> Path;
1129 // We do not need a break before the initial token.
1130 while (Current->Previous) {
1131 Path.push_front(Current);
1132 Current = Current->Previous;
1133 }
1134 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1135 I != E; ++I) {
1136 DEBUG({
1137 if ((*I)->NewLine) {
1138 llvm::dbgs() << "Penalty for splitting before "
1139 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1140 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1141 }
1142 });
1143 addTokenToState((*I)->NewLine, false, State);
1144 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001145 }
1146
Manuel Klimekaf491072013-02-13 10:54:19 +00001147 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001148 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001149 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001150 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001151 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1152 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001153 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001155 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 return;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001157 if (NewLine) {
1158 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1159 Penalty += 15;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001160 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001161 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001162
1163 StateNode *Node = new (Allocator.Allocate())
1164 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001165 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001166 if (Node->State.Column > getColumnLimit()) {
1167 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001168 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001169 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001170
1171 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1172 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001173 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001174
Daniel Jasper4b866272013-02-01 11:00:45 +00001175 /// \brief Returns \c true, if a line break after \p State is allowed.
1176 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001177 const FormatToken &Current = *State.NextToken;
1178 const FormatToken &Previous = *Current.Previous;
1179 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001180 if (!Current.CanBreakBefore &&
1181 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001182 State.Stack.back().BreakBeforeClosingBrace))
1183 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001184 // The opening "{" of a braced list has to be on the same line as the first
1185 // element if it is nested in another braced init list or function call.
1186 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001187 Previous.Previous &&
1188 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001189 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001190 // This prevents breaks like:
1191 // ...
1192 // SomeParameter, OtherParameter).DoSomething(
1193 // ...
1194 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper0e90c3d2013-07-05 09:14:35 +00001195 if (Previous.opensScope() &&
1196 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper32a796b2013-05-27 11:50:16 +00001197 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001198 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001199 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001200
Daniel Jasper4b866272013-02-01 11:00:45 +00001201 /// \brief Returns \c true, if a line break after \p State is mandatory.
1202 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001203 const FormatToken &Current = *State.NextToken;
1204 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001205 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001206 return true;
Daniel Jasper6ab54682013-07-16 18:22:10 +00001207 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1208 State.Stack.back().BreakBeforeClosingBrace)
1209 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001210 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001211 return true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +00001212 if (Style.BreakConstructorInitializersBeforeComma) {
1213 if (Previous.Type == TT_CtorInitializerComma)
1214 return false;
1215 if (Current.Type == TT_CtorInitializerComma)
1216 return true;
1217 }
Daniel Jasperd69fc772013-05-08 14:12:04 +00001218 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1219 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001220 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001221 !Current.isTrailingComment() &&
1222 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001223 return true;
Daniel Jasperc834c702013-07-17 15:38:19 +00001224 if (Style.AlwaysBreakBeforeMultilineStrings &&
1225 State.Column > State.Stack.back().Indent &&
1226 Current.is(tok::string_literal) && Previous.isNot(tok::lessless) &&
1227 Previous.Type != TT_InlineASMColon &&
1228 ((Current.getNextNonComment() &&
1229 Current.getNextNonComment()->is(tok::string_literal)) ||
1230 (Current.TokenText.find("\\\n") != StringRef::npos)))
1231 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001232
Daniel Jaspere33d4af2013-07-26 16:56:36 +00001233 if (!Style.BreakBeforeBinaryOperators) {
1234 // If we need to break somewhere inside the LHS of a binary expression, we
1235 // should also break after the operator. Otherwise, the formatting would
1236 // hide the operator precedence, e.g. in:
1237 // if (aaaaaaaaaaaaaa ==
1238 // bbbbbbbbbbbbbb && c) {..
1239 // For comparisons, we only apply this rule, if the LHS is a binary
1240 // expression itself as otherwise, the line breaks seem superfluous.
1241 // We need special cases for ">>" which we have split into two ">" while
1242 // lexing in order to make template parsing easier.
1243 //
1244 // FIXME: We'll need something similar for styles that break before binary
1245 // operators.
1246 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1247 Previous.getPrecedence() == prec::Equality) &&
1248 Previous.Previous && Previous.Previous->Type !=
1249 TT_BinaryOperator; // For >>.
1250 bool LHSIsBinaryExpr =
1251 Previous.Previous && Previous.Previous->FakeRParens > 0;
1252 if (Previous.Type == TT_BinaryOperator &&
1253 (!IsComparison || LHSIsBinaryExpr) &&
1254 Current.Type != TT_BinaryOperator && // For >>.
1255 !Current.isTrailingComment() &&
1256 !Previous.isOneOf(tok::lessless, tok::question) &&
1257 Previous.getPrecedence() != prec::Assignment &&
1258 State.Stack.back().BreakBeforeParameter)
1259 return true;
1260 }
Daniel Jasperd69fc772013-05-08 14:12:04 +00001261
Daniel Jasper77d5d312013-07-12 15:14:05 +00001262 // Same as above, but for the first "<<" operator.
1263 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1264 State.Stack.back().FirstLessLess == 0)
1265 return true;
1266
Daniel Jasperd69fc772013-05-08 14:12:04 +00001267 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1268 // out whether it is the first parameter. Clean this up.
1269 if (Current.Type == TT_ObjCSelectorName &&
1270 Current.LongestObjCSelectorName == 0 &&
1271 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001272 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001273 if ((Current.Type == TT_CtorInitializerColon ||
1274 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001275 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001276
Daniel Jasper6331da02013-07-09 07:43:55 +00001277 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1278 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1279 State.ParenLevel == 0)
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001280 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001281 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001282 }
1283
Daniel Jasper9b334242013-03-15 14:57:30 +00001284 // Returns the total number of columns required for the remaining tokens.
1285 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001286 if (State.NextToken && State.NextToken->Previous)
1287 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001288 return 0;
1289 }
1290
Daniel Jasperf7935112012-12-03 18:12:45 +00001291 FormatStyle Style;
1292 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001293 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001294 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001295 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001296 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001297
1298 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1299 QueueType Queue;
1300 // Increasing count of \c StateNode items we have created. This is used
1301 // to create a deterministic order independent of the container.
1302 unsigned Count;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001303 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001304 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001305};
1306
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001307class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001308public:
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001309 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1310 encoding::Encoding Encoding)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001311 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001312 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1313 Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001314 Lex.SetKeepWhitespaceMode(true);
1315 }
1316
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001317 ArrayRef<FormatToken *> lex() {
1318 assert(Tokens.empty());
1319 do {
1320 Tokens.push_back(getNextToken());
1321 } while (Tokens.back()->Tok.isNot(tok::eof));
1322 return Tokens;
1323 }
1324
1325 IdentifierTable &getIdentTable() { return IdentTable; }
1326
1327private:
1328 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001329 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001330 // Create a synthesized second '>' token.
1331 Token Greater = FormatTok->Tok;
1332 FormatTok = new (Allocator.Allocate()) FormatToken;
1333 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001334 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001335 FormatTok->Tok.getLocation().getLocWithOffset(1);
1336 FormatTok->WhitespaceRange =
1337 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001338 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001339 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001340 GreaterStashed = false;
1341 return FormatTok;
1342 }
1343
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001344 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001345 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001346 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001347 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001348 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001349 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001350
1351 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001352 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001353 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001354 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001355 if (Newlines > 0)
Daniel Jasper8369aa52013-07-16 20:28:33 +00001356 FormatTok->LastNewlineOffset =
1357 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001358 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001359 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001360 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1361 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001362
Daniel Jasper8369aa52013-07-16 20:28:33 +00001363 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001364 }
Manuel Klimekef920692013-01-07 07:56:50 +00001365
Manuel Klimek1abf7892013-01-04 23:34:14 +00001366 // In case the token starts with escaped newlines, we want to
1367 // take them into account as whitespace - this pattern is quite frequent
1368 // in macro definitions.
1369 // FIXME: What do we want to do with other escaped spaces, and escaped
1370 // spaces or newlines in the middle of tokens?
1371 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001372 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1373 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001374 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001375 WhitespaceLength += 2;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001376 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001377 }
1378
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001379 TrailingWhitespace = 0;
1380 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001381 StringRef UntrimmedText = FormatTok->TokenText;
1382 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1383 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001384 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001385 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001386 FormatTok->Tok.setIdentifierInfo(&Info);
1387 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001388 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001389 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001390 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001391 GreaterStashed = true;
1392 }
1393
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001394 // Now FormatTok is the next non-whitespace token.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001395 FormatTok->CodePointCount =
1396 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001397
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001398 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001399 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001400 return FormatTok;
1401 }
1402
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001403 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001404 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001405 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001406 Lexer &Lex;
1407 SourceManager &SourceMgr;
1408 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001409 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001410 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1411 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001412
Daniel Jasper8369aa52013-07-16 20:28:33 +00001413 void readRawToken(FormatToken &Tok) {
1414 Lex.LexFromRawLexer(Tok.Tok);
1415 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1416 Tok.Tok.getLength());
1417
1418 // For formatting, treat unterminated string literals like normal string
1419 // literals.
1420 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1421 Tok.TokenText[0] == '"') {
1422 Tok.Tok.setKind(tok::string_literal);
1423 Tok.IsUnterminatedLiteral = true;
1424 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001425 }
1426};
1427
Daniel Jasperf7935112012-12-03 18:12:45 +00001428class Formatter : public UnwrappedLineConsumer {
1429public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001430 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001431 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001432 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001433 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1434 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001435 DEBUG(llvm::dbgs() << "File encoding: "
1436 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1437 : "unknown")
1438 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001439 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001440
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001441 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001442
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001443 tooling::Replacements format() {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001444 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001445
1446 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001447 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001448 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001449 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1450 Annotator.annotate(AnnotatedLines[i]);
1451 }
1452 deriveLocalStyle();
1453 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1454 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1455 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001456
1457 // Adapt level to the next line if this is a comment.
1458 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001459 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001460 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001461 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001462 !AnnotatedLines[i].First->Next)
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001463 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001464 else
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +00001465 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1466 ? &AnnotatedLines[i]
1467 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001468 }
1469
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001470 std::vector<int> IndentForLevel;
1471 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001472 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001473 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001474 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1475 E = AnnotatedLines.end();
1476 I != E; ++I) {
1477 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001478 const FormatToken *FirstTok = TheLine.First;
1479 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001480
1481 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001482 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001483 FormatPPDirective = false;
1484 if (!FormatPPDirective && TheLine.InPPDirective &&
1485 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1486 FormatPPDirective = true;
1487
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001488 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001489 while (IndentForLevel.size() <= TheLine.Level)
1490 IndentForLevel.push_back(-1);
1491 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001492 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1493 if (static_cast<int>(Indent) + Offset >= 0)
1494 Indent += Offset;
1495 tryFitMultipleLinesInOne(Indent, I, E);
1496
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001497 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001498 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001499 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001500 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001501 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001502 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001503 }
1504 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001505 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001506 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001507 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001508 // Insert a break even if there is a structural error in case where
1509 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001510 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001511 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001512 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001513 } else {
1514 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001515 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1516 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001517 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001518 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001519 TheLine.First, Whitespaces, Encoding,
1520 BinPackInconclusiveFunctions);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001521 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001522 IndentForLevel[TheLine.Level] = LevelIndent;
1523 PreviousLineWasTouched = true;
1524 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001525 // Format the first token if necessary, and notify the WhitespaceManager
1526 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001527 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1528 Tok = Tok->Next) {
1529 if (Tok == TheLine.First &&
1530 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1531 unsigned LevelIndent =
1532 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001533 // Remove trailing whitespace of the previous line if it was
1534 // touched.
1535 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1536 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1537 TheLine.InPPDirective);
1538 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001539 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001540 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001541
Manuel Klimek4fe43002013-05-22 12:51:29 +00001542 if (static_cast<int>(LevelIndent) - Offset >= 0)
1543 LevelIndent -= Offset;
1544 if (Tok->isNot(tok::comment))
1545 IndentForLevel[TheLine.Level] = LevelIndent;
1546 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001547 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001548 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001549 }
1550 // If we did not reformat this unwrapped line, the column at the end of
1551 // the last token is unchanged - thus, we can calculate the end of the
1552 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001553 PreviousLineWasTouched = false;
1554 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001555 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001556 }
1557 return Whitespaces.generateReplacements();
1558 }
1559
1560private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001561 void deriveLocalStyle() {
1562 unsigned CountBoundToVariable = 0;
1563 unsigned CountBoundToType = 0;
1564 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001565 bool HasBinPackedFunction = false;
1566 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001567 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001568 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001569 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001570 FormatToken *Tok = AnnotatedLines[i].First->Next;
1571 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001572 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001573 bool SpacesBefore =
1574 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1575 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1576 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001577 if (SpacesBefore && !SpacesAfter)
1578 ++CountBoundToVariable;
1579 else if (!SpacesBefore && SpacesAfter)
1580 ++CountBoundToType;
1581 }
1582
Daniel Jasper400adc62013-02-08 15:28:42 +00001583 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001584 Tok->Previous->Type == TT_TemplateCloser &&
1585 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001586 HasCpp03IncompatibleFormat = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001587
1588 if (Tok->PackingKind == PPK_BinPacked)
1589 HasBinPackedFunction = true;
1590 if (Tok->PackingKind == PPK_OnePerLine)
1591 HasOnePerLineFunction = true;
1592
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001593 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001594 }
1595 }
1596 if (Style.DerivePointerBinding) {
1597 if (CountBoundToType > CountBoundToVariable)
1598 Style.PointerBindsToType = true;
1599 else if (CountBoundToType < CountBoundToVariable)
1600 Style.PointerBindsToType = false;
1601 }
1602 if (Style.Standard == FormatStyle::LS_Auto) {
1603 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1604 : FormatStyle::LS_Cpp03;
1605 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001606 BinPackInconclusiveFunctions =
1607 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001608 }
1609
Manuel Klimekb95f5452013-02-08 17:38:27 +00001610 /// \brief Get the indent of \p Level from \p IndentForLevel.
1611 ///
1612 /// \p IndentForLevel must contain the indent for the level \c l
1613 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1614 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001615 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001616 if (IndentForLevel[Level] != -1)
1617 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001618 if (Level == 0)
1619 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001620 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001621 }
1622
1623 /// \brief Get the offset of the line relatively to the level.
1624 ///
1625 /// For example, 'public:' labels in classes are offset by 1 or 2
1626 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001627 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001628 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001629 return Style.AccessModifierOffset;
1630 return 0;
1631 }
1632
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001633 /// \brief Tries to merge lines into one.
1634 ///
1635 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1636 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001637 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001638 std::vector<AnnotatedLine>::iterator &I,
1639 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001640 // We can never merge stuff if there are trailing line comments.
1641 if (I->Last->Type == TT_LineComment)
1642 return;
1643
Daniel Jasperffefb3d2013-07-24 13:10:59 +00001644 if (Indent > Style.ColumnLimit)
1645 return;
1646
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001647 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001648 // If we already exceed the column limit, we set 'Limit' to 0. The different
1649 // tryMerge..() functions can then decide whether to still do merging.
1650 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001651
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001652 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001653 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001654
Daniel Jasperabca58c2013-05-15 14:09:55 +00001655 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001656 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001657 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001658 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001659 tryMergeSimpleControlStatement(I, E, Limit);
1660 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001661 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001662 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001663 } else if (I->InPPDirective &&
1664 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001665 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001666 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001667 }
1668
Daniel Jasper39825ea2013-01-14 15:40:57 +00001669 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1670 std::vector<AnnotatedLine>::iterator E,
1671 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001672 if (Limit == 0)
1673 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001674 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001675 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001676 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001677 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001678 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001679 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001680 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001681 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001682 join(Line, *(++I));
1683 }
1684
Daniel Jasper3a685df2013-05-16 12:12:21 +00001685 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1686 std::vector<AnnotatedLine>::iterator E,
1687 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001688 if (Limit == 0)
1689 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001690 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001691 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001692 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001693 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001694 if (Line.Last->isNot(tok::r_paren))
1695 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001696 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001697 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001698 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1699 tok::kw_while) ||
1700 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001701 return;
1702 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001703 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1704 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001705 return;
1706 join(Line, *(++I));
1707 }
1708
1709 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001710 std::vector<AnnotatedLine>::iterator E,
1711 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001712 // No merging if the brace already is on the next line.
1713 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1714 return;
1715
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001716 // First, check that the current line allows merging. This is the case if
1717 // we're not in a control flow statement and the last token is an opening
1718 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001719 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001720 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1721 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001722 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001723 // This gets rid of all ObjC @ keywords and methods.
1724 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001725 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001726
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001727 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001728 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001729 (Tok->getNextNonComment() == NULL ||
1730 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001731 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001732 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001733 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001734 join(Line, *(I + 1));
1735 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001736 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001737 // Check that we still have three lines and they fit into the limit.
1738 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1739 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001740 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001741
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001742 // Second, check that the next line does not contain any braces - if it
1743 // does, readability declines when putting it into a single line.
1744 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1745 return;
1746 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001747 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001748 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001749 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001750 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001751
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001752 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001753 Tok = (I + 2)->First;
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001754 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001755 Tok->MustBreakBefore)
1756 return;
1757
1758 join(Line, *(I + 1));
1759 join(Line, *(I + 2));
1760 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001761 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001762 }
1763
1764 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1765 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001766 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1767 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001768 }
1769
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001770 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001771 assert(!A.Last->Next);
1772 assert(!B.First->Previous);
1773 A.Last->Next = B.First;
1774 B.First->Previous = A.Last;
1775 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1776 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1777 Tok->TotalLength += LengthA;
1778 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001779 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001780 }
1781
Daniel Jasper97b89482013-03-13 07:49:51 +00001782 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001783 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1784 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1785 Ranges[i].getBegin()) &&
1786 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1787 Range.getBegin()))
1788 return true;
1789 }
1790 return false;
1791 }
1792
1793 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001794 const FormatToken *First = TheLine.First;
1795 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001796 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001797 First->WhitespaceRange.getBegin().getLocWithOffset(
1798 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001799 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001800 return touchesRanges(LineRange);
1801 }
1802
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001803 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1804 std::vector<AnnotatedLine>::iterator E) {
1805 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001806 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001807 return false;
1808 if (touchesLine(*I))
1809 return true;
1810 }
1811 return false;
1812 }
1813
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001814 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001815 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001816 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001817 First->WhitespaceRange.getBegin(),
1818 First->WhitespaceRange.getBegin().getLocWithOffset(
1819 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001820 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001821 }
1822
1823 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001824 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001825 }
1826
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001827 /// \brief Add a new line and the required indent before the first Token
1828 /// of the \c UnwrappedLine if there was no structural parsing error.
1829 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001830 void formatFirstToken(const FormatToken &RootToken,
1831 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001832 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001833 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001834 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001835 // Remove empty lines before "}" where applicable.
1836 if (RootToken.is(tok::r_brace) &&
1837 (!RootToken.Next ||
1838 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1839 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001840 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001841 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001842
Manuel Klimek4fe43002013-05-22 12:51:29 +00001843 // Insert extra new line before access specifiers.
1844 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001845 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001846 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001847
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001848 Whitespaces.replaceWhitespace(
1849 RootToken, Newlines, Indent, Indent,
1850 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001851 }
1852
Daniel Jasperf7935112012-12-03 18:12:45 +00001853 FormatStyle Style;
1854 Lexer &Lex;
1855 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001856 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001857 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001858 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001859
1860 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001861 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001862};
1863
Craig Topperaf35e852013-06-30 22:29:28 +00001864} // end anonymous namespace
1865
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001866tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1867 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001868 std::vector<CharSourceRange> Ranges) {
1869 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001870 return formatter.format();
1871}
1872
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001873tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1874 std::vector<tooling::Range> Ranges,
1875 StringRef FileName) {
1876 FileManager Files((FileSystemOptions()));
1877 DiagnosticsEngine Diagnostics(
1878 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1879 new DiagnosticOptions);
1880 SourceManager SourceMgr(Diagnostics, Files);
1881 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1882 const clang::FileEntry *Entry =
1883 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1884 SourceMgr.overrideFileContents(Entry, Buf);
1885 FileID ID =
1886 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001887 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1888 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001889 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1890 std::vector<CharSourceRange> CharRanges;
1891 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1892 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1893 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1894 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1895 }
1896 return reformat(Style, Lex, SourceMgr, CharRanges);
1897}
1898
Alexander Kornienko1e808872013-06-28 12:51:24 +00001899LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001900 LangOptions LangOpts;
1901 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001902 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001903 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001904 LangOpts.Bool = 1;
1905 LangOpts.ObjC1 = 1;
1906 LangOpts.ObjC2 = 1;
1907 return LangOpts;
1908}
1909
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001910} // namespace format
1911} // namespace clang