blob: 2dee5678b71dd47fd0bfac18a4311c550112ac49 [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);
Alexander Kornienkod6538332013-05-07 15:32:14 +000092 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
93 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
94 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
95 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
96 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +000097 IO.mapOptional("ExperimentalAutoDetectBinPacking",
98 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +000099 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
100 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
101 IO.mapOptional("ObjCSpaceBeforeProtocolList",
102 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000103 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
104 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000105 IO.mapOptional("PenaltyBreakFirstLessLess",
106 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000107 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
108 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
109 Style.PenaltyReturnTypeOnItsOwnLine);
110 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
111 IO.mapOptional("SpacesBeforeTrailingComments",
112 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000113 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000114 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000115 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000116 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000117 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000118 IO.mapOptional("IndentFunctionDeclarationAfterType",
119 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000120 }
121};
122}
123}
124
Daniel Jasperf7935112012-12-03 18:12:45 +0000125namespace clang {
126namespace format {
127
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000128void setDefaultPenalties(FormatStyle &Style) {
129 Style.PenaltyBreakComment = 45;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000130 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000131 Style.PenaltyBreakString = 1000;
132 Style.PenaltyExcessCharacter = 1000000;
133}
134
Daniel Jasperf7935112012-12-03 18:12:45 +0000135FormatStyle getLLVMStyle() {
136 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000137 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000138 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000139 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000140 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000141 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000142 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000143 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000144 LLVMStyle.BinPackParameters = true;
145 LLVMStyle.ColumnLimit = 80;
146 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
147 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000148 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000149 LLVMStyle.IndentCaseLabels = false;
150 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000151 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000152 LLVMStyle.PointerBindsToType = false;
153 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper6ab54682013-07-16 18:22:10 +0000154 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000155 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000156 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000157 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000158 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek836c2862013-06-21 17:25:42 +0000159 LLVMStyle.IndentFunctionDeclarationAfterType = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000160
161 setDefaultPenalties(LLVMStyle);
162 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
163
Daniel Jasperf7935112012-12-03 18:12:45 +0000164 return LLVMStyle;
165}
166
167FormatStyle getGoogleStyle() {
168 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000169 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000170 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000171 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000172 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000173 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000174 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000175 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000176 GoogleStyle.BinPackParameters = true;
177 GoogleStyle.ColumnLimit = 80;
178 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
179 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000180 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000181 GoogleStyle.IndentCaseLabels = true;
182 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000183 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000184 GoogleStyle.PointerBindsToType = true;
185 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper6ab54682013-07-16 18:22:10 +0000186 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000187 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000188 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000189 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000190 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek836c2862013-06-21 17:25:42 +0000191 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000192
193 setDefaultPenalties(GoogleStyle);
194 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
195
Daniel Jasperf7935112012-12-03 18:12:45 +0000196 return GoogleStyle;
197}
198
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000199FormatStyle getChromiumStyle() {
200 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000201 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000202 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000203 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000204 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000205 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
206 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000207 return ChromiumStyle;
208}
209
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000210FormatStyle getMozillaStyle() {
211 FormatStyle MozillaStyle = getLLVMStyle();
212 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
213 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
214 MozillaStyle.DerivePointerBinding = true;
215 MozillaStyle.IndentCaseLabels = true;
216 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
217 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
218 MozillaStyle.PointerBindsToType = true;
219 return MozillaStyle;
220}
221
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000222FormatStyle getWebKitStyle() {
223 FormatStyle Style = getLLVMStyle();
224 Style.ColumnLimit = 0;
225 Style.IndentWidth = 4;
226 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
227 Style.PointerBindsToType = true;
228 return Style;
229}
230
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000231bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000232 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000233 *Style = getLLVMStyle();
234 else if (Name.equals_lower("chromium"))
235 *Style = getChromiumStyle();
236 else if (Name.equals_lower("mozilla"))
237 *Style = getMozillaStyle();
238 else if (Name.equals_lower("google"))
239 *Style = getGoogleStyle();
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000240 else if (Name.equals_lower("webkit"))
241 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000242 else
243 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000244
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000245 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000246}
247
248llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000249 if (Text.trim().empty())
250 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000251 llvm::yaml::Input Input(Text);
252 Input >> *Style;
253 return Input.error();
254}
255
256std::string configurationAsText(const FormatStyle &Style) {
257 std::string Text;
258 llvm::raw_string_ostream Stream(Text);
259 llvm::yaml::Output Output(Stream);
260 // We use the same mapping method for input and output, so we need a non-const
261 // reference here.
262 FormatStyle NonConstStyle = Style;
263 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000264 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000265}
266
Daniel Jasperacc33662013-02-08 08:22:00 +0000267// Returns the length of everything up to the first possible line break after
268// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000269static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000270 if (Tok.MatchingParen == NULL)
271 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000272 FormatToken *End = Tok.MatchingParen;
273 while (End->Next && !End->Next->CanBreakBefore) {
274 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000275 }
276 return End->TotalLength - Tok.TotalLength + 1;
277}
278
Craig Topperaf35e852013-06-30 22:29:28 +0000279namespace {
280
Daniel Jasperf7935112012-12-03 18:12:45 +0000281class UnwrappedLineFormatter {
282public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000283 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000284 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000285 const FormatToken *RootToken,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000286 WhitespaceManager &Whitespaces,
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000287 encoding::Encoding Encoding,
288 bool BinPackInconclusiveFunctions)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000289 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000290 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000291 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
292 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000293
Manuel Klimek1abf7892013-01-04 23:34:14 +0000294 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000295 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000296 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000297 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000298 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000299 State.NextToken = RootToken;
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000300 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
301 /*AvoidBinPacking=*/false,
302 /*NoLineBreak=*/false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000303 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000304 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000305 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000306 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000307 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000308 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000309
310 // The first token has already been indented and thus consumed.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000311 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000312
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000313 if (Style.ColumnLimit == 0) {
314 formatWithoutColumnLimit(State);
315 return;
316 }
317
Daniel Jasper4b866272013-02-01 11:00:45 +0000318 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000319 unsigned ColumnLimit = Style.ColumnLimit;
320 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000321 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000322 ColumnLimit = getColumnLimit();
323 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000324 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000325 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000326 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000328
Daniel Jasperacc33662013-02-08 08:22:00 +0000329 // If the ObjC method declaration does not fit on a line, we should format
330 // it with one arg per line.
331 if (Line.Type == LT_ObjCMethodDecl)
332 State.Stack.back().BreakBeforeParameter = true;
333
Daniel Jasper4b866272013-02-01 11:00:45 +0000334 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000335 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000336 }
337
338private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000339 void DebugTokenState(const FormatToken &FormatTok) {
340 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000341 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000342 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000343 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000344 }
345
Daniel Jasper337816e2013-01-11 10:22:12 +0000346 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000347 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000348 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000349 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
350 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000351 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000352 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000353 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
354 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000355
Daniel Jasperf7935112012-12-03 18:12:45 +0000356 /// \brief The position to which a specific parenthesis level needs to be
357 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000358 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000359
Daniel Jaspere9de2602012-12-06 09:56:08 +0000360 /// \brief The position of the last space on each level.
361 ///
362 /// Used e.g. to break like:
363 /// functionCall(Parameter, otherCall(
364 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000365 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000366
Daniel Jaspere9de2602012-12-06 09:56:08 +0000367 /// \brief The position the first "<<" operator encountered on each level.
368 ///
369 /// Used to align "<<" operators. 0 if no such operator has been encountered
370 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000371 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000372
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000373 /// \brief Whether a newline needs to be inserted before the block's closing
374 /// brace.
375 ///
376 /// We only want to insert a newline before the closing brace if there also
377 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000378 bool BreakBeforeClosingBrace;
379
Daniel Jasperca6623b2013-01-28 12:45:14 +0000380 /// \brief The column of a \c ? in a conditional expression;
381 unsigned QuestionColumn;
382
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000383 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
384 /// lines, in this context.
385 bool AvoidBinPacking;
386
387 /// \brief Break after the next comma (or all the commas in this context if
388 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000389 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000390
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000391 /// \brief Line breaking in this context would break a formatting rule.
392 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000393
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000394 /// \brief The position of the colon in an ObjC method declaration/call.
395 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000396
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000397 /// \brief The start of the most recent function in a builder-type call.
398 unsigned StartOfFunctionCall;
399
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000400 /// \brief Contains the start of array subscript expressions, so that they
401 /// can be aligned.
402 unsigned StartOfArraySubscripts;
403
Daniel Jasperc238c872013-04-02 14:33:13 +0000404 /// \brief If a nested name specifier was broken over multiple lines, this
405 /// contains the start column of the second line. Otherwise 0.
406 unsigned NestedNameSpecifierContinuation;
407
408 /// \brief If a call expression was broken over multiple lines, this
409 /// contains the start column of the second line. Otherwise 0.
410 unsigned CallContinuation;
411
Daniel Jaspera628c982013-04-03 13:36:17 +0000412 /// \brief The column of the first variable name in a variable declaration.
413 ///
414 /// Used to align further variables if necessary.
415 unsigned VariablePos;
416
Daniel Jasperee7539a2013-07-08 14:25:23 +0000417 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000418 ///
Daniel Jasperee7539a2013-07-08 14:25:23 +0000419 /// The first line break in a certain \c ParenState causes extra penalty so
420 /// that clang-format prefers similar breaks, i.e. breaks in the same
421 /// parenthesis.
422 bool ContainsLineBreak;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000423
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 bool operator<(const ParenState &Other) const {
425 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000426 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 if (LastSpace != Other.LastSpace)
428 return LastSpace < Other.LastSpace;
429 if (FirstLessLess != Other.FirstLessLess)
430 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000431 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
432 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000433 if (QuestionColumn != Other.QuestionColumn)
434 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000435 if (AvoidBinPacking != Other.AvoidBinPacking)
436 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000437 if (BreakBeforeParameter != Other.BreakBeforeParameter)
438 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000439 if (NoLineBreak != Other.NoLineBreak)
440 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000441 if (ColonPos != Other.ColonPos)
442 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000443 if (StartOfFunctionCall != Other.StartOfFunctionCall)
444 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000445 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
446 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasperc238c872013-04-02 14:33:13 +0000447 if (CallContinuation != Other.CallContinuation)
448 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000449 if (VariablePos != Other.VariablePos)
450 return VariablePos < Other.VariablePos;
Daniel Jasperee7539a2013-07-08 14:25:23 +0000451 if (ContainsLineBreak != Other.ContainsLineBreak)
452 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000453 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000454 }
455 };
456
457 /// \brief The current state when indenting a unwrapped line.
458 ///
459 /// As the indenting tries different combinations this is copied by value.
460 struct LineState {
461 /// \brief The number of used columns in the current line.
462 unsigned Column;
463
464 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000465 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000466
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000467 /// \brief \c true if this line contains a continued for-loop section.
468 bool LineContainsContinuedForLoopSection;
469
Daniel Jasper400adc62013-02-08 15:28:42 +0000470 /// \brief The level of nesting inside (), [], <> and {}.
471 unsigned ParenLevel;
472
Daniel Jasper40c36c52013-02-18 11:05:07 +0000473 /// \brief The \c ParenLevel at the start of this line.
474 unsigned StartOfLineLevel;
475
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000476 /// \brief The lowest \c ParenLevel on the current line.
477 unsigned LowestLevelOnLine;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000478
Manuel Klimek02f640a2013-02-20 15:25:48 +0000479 /// \brief The start column of the string literal, if we're in a string
480 /// literal sequence, 0 otherwise.
481 unsigned StartOfStringLiteral;
482
Daniel Jasper337816e2013-01-11 10:22:12 +0000483 /// \brief A stack keeping track of properties applying to parenthesis
484 /// levels.
485 std::vector<ParenState> Stack;
486
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000487 /// \brief Ignore the stack of \c ParenStates for state comparison.
488 ///
489 /// In long and deeply nested unwrapped lines, the current algorithm can
490 /// be insufficient for finding the best formatting with a reasonable amount
491 /// of time and memory. Setting this flag will effectively lead to the
492 /// algorithm not analyzing some combinations. However, these combinations
493 /// rarely contain the optimal solution: In short, accepting a higher
494 /// penalty early would need to lead to different values in the \c
495 /// ParenState stack (in an otherwise identical state) and these different
496 /// values would need to lead to a significant amount of avoided penalty
497 /// later.
498 ///
499 /// FIXME: Come up with a better algorithm instead.
500 bool IgnoreStackForComparison;
501
Daniel Jasper337816e2013-01-11 10:22:12 +0000502 /// \brief Comparison operator to be able to used \c LineState in \c map.
503 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000504 if (NextToken != Other.NextToken)
505 return NextToken < Other.NextToken;
506 if (Column != Other.Column)
507 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000508 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000509 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000510 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000511 if (ParenLevel != Other.ParenLevel)
512 return ParenLevel < Other.ParenLevel;
513 if (StartOfLineLevel != Other.StartOfLineLevel)
514 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000515 if (LowestLevelOnLine != Other.LowestLevelOnLine)
516 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000517 if (StartOfStringLiteral != Other.StartOfStringLiteral)
518 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000519 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
520 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000521 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 }
523 };
524
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000525 /// \brief Formats the line starting at \p State, simply keeping all of the
526 /// input's line breaking decisions.
527 void formatWithoutColumnLimit(LineState &State) {
528 while (State.NextToken != NULL) {
529 bool Newline = State.NextToken->NewlinesBefore > 0;
530 addTokenToState(Newline, /*DryRun=*/false, State);
531 }
532 }
533
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000534 /// \brief Appends the next token to \p State and updates information
535 /// necessary for indentation.
536 ///
Nico Weberf579ab32013-06-26 02:42:46 +0000537 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000538 /// line break and necessary indentation otherwise.
539 ///
540 /// If \p DryRun is \c false, also creates and stores the required
541 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000542 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000543 const FormatToken &Current = *State.NextToken;
544 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000545
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000546 // Extra penalty that needs to be added because of the way certain line
547 // breaks are chosen.
548 unsigned ExtraPenalty = 0;
549
Daniel Jasper291f9362013-03-20 15:58:10 +0000550 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000551 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000552 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
553 State.NextToken->WhitespaceRange.getEnd()) -
554 SourceMgr.getSpellingColumnNumber(
555 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000556 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000557 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000558 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000559 }
560
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000561 // If we are continuing an expression, we want to indent an extra 4 spaces.
562 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000563 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000564 if (Newline) {
Daniel Jasperee7539a2013-07-08 14:25:23 +0000565 State.Stack.back().ContainsLineBreak = true;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000566 if (Current.is(tok::r_brace)) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000567 if (Current.BlockKind == BK_BracedInit)
568 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
569 else
Daniel Jasper51efbad2013-07-11 21:27:40 +0000570 State.Column = FirstIndent;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000571 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000572 State.StartOfStringLiteral != 0) {
573 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000574 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000575 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000576 State.Stack.back().FirstLessLess != 0) {
577 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000578 } else if (Current.isOneOf(tok::period, tok::arrow) &&
579 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000580 if (State.Stack.back().CallContinuation == 0) {
581 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000582 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000583 } else {
584 State.Column = State.Stack.back().CallContinuation;
585 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000586 } else if (Current.Type == TT_ConditionalExpr) {
587 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000588 } else if (Previous.is(tok::comma) &&
589 State.Stack.back().VariablePos != 0) {
590 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000591 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6331da02013-07-09 07:43:55 +0000592 ((Current.Type == TT_StartOfName ||
593 Current.is(tok::kw_operator)) &&
594 State.ParenLevel == 0 &&
Manuel Klimek836c2862013-06-21 17:25:42 +0000595 (!Style.IndentFunctionDeclarationAfterType ||
596 Line.StartsDefinition))) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000597 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000598 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000599 if (State.Stack.back().ColonPos > Current.CodePointCount) {
600 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000601 } else {
602 State.Column = State.Stack.back().Indent;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000603 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000604 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000605 } else if (Current.is(tok::l_square) &&
606 Current.Type != TT_ObjCMethodExpr) {
607 if (State.Stack.back().StartOfArraySubscripts != 0)
608 State.Column = State.Stack.back().StartOfArraySubscripts;
609 else
610 State.Column = ContinuationIndent;
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000611 } else if (Current.Type == TT_StartOfName ||
612 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000613 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000614 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000615 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000616 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000617 // Ensure that we fall back to indenting 4 spaces instead of just
618 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000619 if (State.Column == FirstIndent)
620 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000621 }
622
Daniel Jasper54a86022013-02-15 11:07:25 +0000623 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000624 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000625 if ((Previous.isOneOf(tok::comma, tok::semi) &&
626 !State.Stack.back().AvoidBinPacking) ||
627 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000628 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000629 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
630 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000631
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000632 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000633 unsigned NewLines = 1;
Alexander Kornienkof370ad92013-06-12 19:04:12 +0000634 if (Current.is(tok::comment))
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000635 NewLines = std::max(
636 NewLines,
637 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000638 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
639 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000640 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000641
Daniel Jasper185de242013-07-11 13:48:16 +0000642 if (!Current.isTrailingComment())
643 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000644 if (Current.isOneOf(tok::arrow, tok::period) &&
645 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000646 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000647 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000648 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000649
650 // Any break on this level means that the parent level has been broken
651 // and we need to avoid bin packing there.
652 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
653 State.Stack[i].BreakBeforeParameter = true;
654 }
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000655 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000656 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000657 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000658 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000659 State.Stack.back().BreakBeforeParameter = true;
660
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000661 // If we break after {, we should also break before the corresponding }.
662 if (Previous.is(tok::l_brace))
663 State.Stack.back().BreakBeforeClosingBrace = true;
664
665 if (State.Stack.back().AvoidBinPacking) {
666 // If we are breaking after '(', '{', '<', this is not bin packing
667 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000668 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
669 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000670 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
671 Line.MustBeDeclaration))
672 State.Stack.back().BreakBeforeParameter = true;
673 }
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000674
675 // Breaking before the first "<<" is generally not desirable.
676 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
677 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
678
Daniel Jasperf7935112012-12-03 18:12:45 +0000679 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000680 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000681 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000682 State.Stack.back().VariablePos == 0) {
683 State.Stack.back().VariablePos = State.Column;
684 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000685 const FormatToken *Tok = &Previous;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000686 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
687 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000688 if (Tok->SpacesRequiredBefore != 0)
689 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000690 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000691 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000692 if (Previous.PartOfMultiVariableDeclStmt)
693 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
694 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000695
Daniel Jaspereef30492013-02-11 12:36:37 +0000696 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000697
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000699 Whitespaces.replaceWhitespace(Current, 0, Spaces,
700 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000701
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000702 if (Current.Type == TT_ObjCSelectorName &&
703 State.Stack.back().ColonPos == 0) {
704 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000705 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000706 State.Stack.back().ColonPos =
707 State.Stack.back().Indent + Current.LongestObjCSelectorName;
708 else
709 State.Stack.back().ColonPos =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000710 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000711 }
712
Daniel Jasperc04baae2013-04-10 09:49:49 +0000713 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000714 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000715 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000716 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
717 State.Stack.back().AvoidBinPacking)
718 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000719
Daniel Jaspere9de2602012-12-06 09:56:08 +0000720 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000721 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000722 // Treat the condition inside an if as if it was a second function
723 // parameter, i.e. let nested calls have an indent of 4.
724 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000725 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000726 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000727 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000728 Previous.Type == TT_ConditionalExpr ||
729 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000730 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000731 Current.FakeLParens.empty()))
732 // Always indent relative to the RHS of the expression unless this is a
733 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000734 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000735 else if (Previous.Type == TT_InheritanceColon)
736 State.Stack.back().Indent = State.Column;
Daniel Jasperbd058882013-07-09 11:57:27 +0000737 else if (Previous.opensScope()) {
738 // If a function has multiple parameters (including a single parameter
Daniel Jasper6cdec7c2013-07-09 14:36:48 +0000739 // that is a binary expression) or a trailing call, indent all
Daniel Jasperbd058882013-07-09 11:57:27 +0000740 // parameters from the opening parenthesis. This avoids confusing
741 // indents like:
742 // OuterFunction(InnerFunctionCall(
743 // ParameterToInnerFunction),
744 // SecondParameterToOuterFunction);
745 bool HasMultipleParameters = !Current.FakeLParens.empty();
746 bool HasTrailingCall = false;
747 if (Previous.MatchingParen) {
748 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
749 if (Next && Next->isOneOf(tok::period, tok::arrow))
750 HasTrailingCall = true;
751 }
752 if (HasMultipleParameters || HasTrailingCall)
753 State.Stack.back().LastSpace = State.Column;
754 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000755 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000756
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000757 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000758 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000759
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000760 /// \brief Mark the next token as consumed in \p State and modify its stacks
761 /// accordingly.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000762 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000763 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000764 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000765
Daniel Jaspereead02b2013-02-14 08:42:54 +0000766 if (Current.Type == TT_InheritanceColon)
767 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000768 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
769 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000770 if (Current.is(tok::l_square) &&
771 State.Stack.back().StartOfArraySubscripts == 0)
772 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000773 if (Current.is(tok::question))
774 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000775 if (!Current.opensScope() && !Current.closesScope())
776 State.LowestLevelOnLine =
777 std::min(State.LowestLevelOnLine, State.ParenLevel);
778 if (Current.isOneOf(tok::period, tok::arrow) &&
779 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
780 State.Stack.back().StartOfFunctionCall =
781 Current.LastInChainOfCalls ? 0
782 : State.Column + Current.CodePointCount;
Daniel Jasper37905f72013-02-21 15:00:29 +0000783 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000784 // Indent 2 from the column, so:
785 // SomeClass::SomeClass()
786 // : First(...), ...
787 // Next(...)
788 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000789 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000790 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
791 State.Stack.back().AvoidBinPacking = true;
792 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000793 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000794
Daniel Jasper6bee6822013-04-08 20:33:42 +0000795 // If return returns a binary expression, align after it.
796 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
797 State.Stack.back().LastSpace = State.Column + 7;
798
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000799 // In ObjC method declaration we align on the ":" of parameters, but we need
800 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000801 if (Current.Type == TT_ObjCMethodSpecifier)
802 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000803
Daniel Jasper400adc62013-02-08 15:28:42 +0000804 // Insert scopes created by fake parenthesis.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000805 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000806 // Don't add extra indentation for the first fake parenthesis after
807 // 'return', assignements or opening <({[. The indentation for these cases
808 // is special cased.
809 bool SkipFirstExtraIndent =
810 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000811 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000812 Previous->getPrecedence() == prec::Assignment));
Craig Topper61ac9062013-07-08 03:55:09 +0000813 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasper6bee6822013-04-08 20:33:42 +0000814 I = Current.FakeLParens.rbegin(),
815 E = Current.FakeLParens.rend();
816 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000817 ParenState NewParenState = State.Stack.back();
Daniel Jasperee7539a2013-07-08 14:25:23 +0000818 NewParenState.ContainsLineBreak = false;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000819 NewParenState.Indent =
820 std::max(std::max(State.Column, NewParenState.Indent),
821 State.Stack.back().LastSpace);
822
823 // Always indent conditional expressions. Never indent expression where
824 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
825 // prec::Assignment) as those have different indentation rules. Indent
826 // other expression, unless the indentation needs to be skipped.
827 if (*I == prec::Conditional ||
828 (!SkipFirstExtraIndent && *I > prec::Assignment))
829 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000830 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000831 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000832 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000833 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000834 }
835
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000836 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000837 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000838 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000839 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000840 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000841 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000842 if (Current.is(tok::l_brace)) {
Daniel Jasper6ab54682013-07-16 18:22:10 +0000843 NewIndent =
844 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000845 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000846 AvoidBinPacking = NextNoComment &&
847 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000848 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000849 NewIndent =
850 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000851 AvoidBinPacking = !Style.BinPackParameters ||
852 (Style.ExperimentalAutoDetectBinPacking &&
853 (Current.PackingKind == PPK_OnePerLine ||
854 (!BinPackInconclusiveFunctions &&
855 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000856 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000857
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000858 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
859 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000860 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000861 }
862
Daniel Jasperacc33662013-02-08 08:22:00 +0000863 // If this '[' opens an ObjC call, determine whether all parameters fit into
864 // one line and put one per line if they don't.
865 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
866 Current.MatchingParen != NULL) {
867 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
868 State.Stack.back().BreakBeforeParameter = true;
869 }
870
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000871 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000872 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000873 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000874 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000875 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000876 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000877 --State.ParenLevel;
878 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000879 if (Current.is(tok::r_square)) {
880 // If this ends the array subscript expr, reset the corresponding value.
881 const FormatToken *NextNonComment = Current.getNextNonComment();
882 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasperfa21c072013-07-15 14:33:14 +0000883 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000884 }
Daniel Jasper400adc62013-02-08 15:28:42 +0000885
886 // Remove scopes created by fake parenthesis.
887 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000888 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000889 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000890 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000891 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000892
Daniel Jasper47a04442013-05-13 20:50:15 +0000893 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000894 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000895 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
896 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000897 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000898 }
899
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000900 State.Column += Current.CodePointCount;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000901
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000902 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000903
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000904 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
905 Current.is(tok::string_literal))
906 return 0;
907
Manuel Klimek1998ea22013-02-20 10:15:13 +0000908 return breakProtrudingToken(Current, State, DryRun);
909 }
910
911 /// \brief If the current token sticks out over the end of the line, break
912 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000913 ///
914 /// \returns An extra penalty if a token was broken, otherwise 0.
915 ///
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000916 /// The returned penalty will cover the cost of the additional line breaks and
917 /// column limit violation in all lines except for the last one. The penalty
918 /// for the column limit violation in the last line (and in single line
919 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000920 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000921 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000922 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000923 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000924 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000925 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000926 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000927
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000928 if (Current.is(tok::string_literal) &&
929 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000930 // Only break up default narrow strings.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000931 if (!Current.TokenText.startswith("\""))
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000932 return 0;
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000933 // Don't break string literals with escaped newlines. As clang-format must
934 // not change the string's content, it is unlikely that we'll end up with
935 // a better format.
936 if (Current.TokenText.find("\\\n") != StringRef::npos)
937 return 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000938 // Exempts unterminated string literals from line breaking. The user will
939 // likely want to terminate the string before any line breaking is done.
940 if (Current.IsUnterminatedLiteral)
941 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000942
Alexander Kornienkobe633902013-06-14 11:46:10 +0000943 Token.reset(new BreakableStringLiteral(Current, StartColumn,
944 Line.InPPDirective, Encoding));
Alexander Kornienko94042342013-07-16 23:47:22 +0000945 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000946 Token.reset(new BreakableBlockComment(
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000947 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000948 Line.InPPDirective, Encoding));
Daniel Jasper4a4be012013-05-06 10:24:51 +0000949 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000950 (Current.Previous == NULL ||
951 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000952 // Don't break line comments with escaped newlines. These look like
953 // separate line comments, but in fact contain a single line comment with
954 // multiple lines including leading whitespace and the '//' markers.
955 //
956 // FIXME: If we want to handle them correctly, we'll need to adjust
957 // leading whitespace in consecutive lines when changing indentation of
958 // the first line similar to what we do with block comments.
959 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
960 if (EscapedNewlinePos != StringRef::npos) {
961 State.Column =
962 StartColumn +
963 encoding::getCodePointCount(
964 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
965 1;
966 return 0;
967 }
968
Alexander Kornienkobe633902013-06-14 11:46:10 +0000969 Token.reset(new BreakableLineComment(Current, StartColumn,
970 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000971 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000972 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000973 }
Alexander Kornienkobe633902013-06-14 11:46:10 +0000974 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000975 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000976
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000977 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000978 bool BreakInserted = false;
979 unsigned Penalty = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000980 unsigned RemainingTokenColumns = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +0000981 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
982 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000983 if (!DryRun)
984 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000985 unsigned TailOffset = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000986 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000987 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000988 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000989 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000990 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000991 if (Split.first == StringRef::npos) {
992 // The last line's penalty is handled in addNextStateToQueue().
993 if (LineIndex < EndIndex - 1)
994 Penalty += Style.PenaltyExcessCharacter *
995 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000996 break;
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000997 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000998 assert(Split.first != 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000999 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001000 LineIndex, TailOffset + Split.first + Split.second,
1001 StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001002 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienkobe633902013-06-14 11:46:10 +00001003 if (!DryRun)
1004 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001005 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
1006 : Style.PenaltyBreakComment;
1007 unsigned ColumnsUsed =
1008 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1009 if (ColumnsUsed > getColumnLimit()) {
1010 Penalty +=
1011 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
1012 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001013 TailOffset += Split.first + Split.second;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001014 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001015 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001016 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001017 }
1018
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001019 State.Column = RemainingTokenColumns;
1020
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001021 if (BreakInserted) {
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +00001022 // If we break the token inside a parameter list, we need to break before
1023 // the next parameter on all levels, so that the next parameter is clearly
1024 // visible. Line comments already introduce a break.
1025 if (Current.Type != TT_LineComment) {
1026 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1027 State.Stack[i].BreakBeforeParameter = true;
1028 }
1029
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001030 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001031 }
Manuel Klimek1998ea22013-02-20 10:15:13 +00001032 return Penalty;
1033 }
1034
Daniel Jasper2df93312013-01-09 10:16:05 +00001035 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001036 // In preprocessor directives reserve two chars for trailing " \"
1037 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +00001038 }
1039
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001040 /// \brief An edge in the solution space from \c Previous->State to \c State,
1041 /// inserting a newline dependent on the \c NewLine.
1042 struct StateNode {
1043 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001044 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001045 LineState State;
1046 bool NewLine;
1047 StateNode *Previous;
1048 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001049
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001050 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1051 ///
1052 /// In case of equal penalties, we want to prefer states that were inserted
1053 /// first. During state generation we make sure that we insert states first
1054 /// that break the line as late as possible.
1055 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1056
1057 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1058 /// \c State has the given \c OrderedPenalty.
1059 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1060
1061 /// \brief The BFS queue type.
1062 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1063 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001064
1065 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001067 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1068 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1069 /// find the shortest path (the one with lowest penalty) from \p InitialState
1070 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +00001071 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001072 std::set<LineState> Seen;
1073
Daniel Jasper4b866272013-02-01 11:00:45 +00001074 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001075 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001076 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1077 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1078 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001079
1080 // While not empty, take first element and follow edges.
1081 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001082 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001083 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001084 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001085 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001086 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001087 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001088 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001089
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001090 // Cut off the analysis of certain solutions if the analysis gets too
1091 // complex. See description of IgnoreStackForComparison.
1092 if (Count > 10000)
1093 Node->State.IgnoreStackForComparison = true;
1094
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001095 if (!Seen.insert(Node->State).second)
1096 // State already examined with lower penalty.
1097 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001098
Nico Weber9096fc02013-06-26 00:30:14 +00001099 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1100 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001101 }
1102
1103 if (Queue.empty())
1104 // We were unable to find a solution, do nothing.
1105 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +00001106 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001107
Daniel Jasper4b866272013-02-01 11:00:45 +00001108 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001109 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +00001110 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1111 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001112 }
1113
1114 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001115 std::deque<StateNode *> Path;
1116 // We do not need a break before the initial token.
1117 while (Current->Previous) {
1118 Path.push_front(Current);
1119 Current = Current->Previous;
1120 }
1121 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1122 I != E; ++I) {
1123 DEBUG({
1124 if ((*I)->NewLine) {
1125 llvm::dbgs() << "Penalty for splitting before "
1126 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1127 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1128 }
1129 });
1130 addTokenToState((*I)->NewLine, false, State);
1131 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001132 }
1133
Manuel Klimekaf491072013-02-13 10:54:19 +00001134 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001135 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001136 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001137 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001138 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1139 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001140 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001141 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001142 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001143 return;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001144 if (NewLine) {
1145 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1146 Penalty += 15;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001147 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001148 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001149
1150 StateNode *Node = new (Allocator.Allocate())
1151 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001152 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001153 if (Node->State.Column > getColumnLimit()) {
1154 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001155 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001156 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001157
1158 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1159 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001160 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001161
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 /// \brief Returns \c true, if a line break after \p State is allowed.
1163 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001164 const FormatToken &Current = *State.NextToken;
1165 const FormatToken &Previous = *Current.Previous;
1166 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001167 if (!Current.CanBreakBefore &&
1168 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001169 State.Stack.back().BreakBeforeClosingBrace))
1170 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001171 // The opening "{" of a braced list has to be on the same line as the first
1172 // element if it is nested in another braced init list or function call.
1173 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001174 Previous.Previous &&
1175 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001176 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001177 // This prevents breaks like:
1178 // ...
1179 // SomeParameter, OtherParameter).DoSomething(
1180 // ...
1181 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper0e90c3d2013-07-05 09:14:35 +00001182 if (Previous.opensScope() &&
1183 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper32a796b2013-05-27 11:50:16 +00001184 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001185 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001186 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001187
Daniel Jasper4b866272013-02-01 11:00:45 +00001188 /// \brief Returns \c true, if a line break after \p State is mandatory.
1189 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001190 const FormatToken &Current = *State.NextToken;
1191 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001192 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001193 return true;
Daniel Jasper6ab54682013-07-16 18:22:10 +00001194 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1195 State.Stack.back().BreakBeforeClosingBrace)
1196 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001197 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001198 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001199 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1200 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001201 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001202 !Current.isTrailingComment() &&
1203 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001204 return true;
Daniel Jasperc834c702013-07-17 15:38:19 +00001205 if (Style.AlwaysBreakBeforeMultilineStrings &&
1206 State.Column > State.Stack.back().Indent &&
1207 Current.is(tok::string_literal) && Previous.isNot(tok::lessless) &&
1208 Previous.Type != TT_InlineASMColon &&
1209 ((Current.getNextNonComment() &&
1210 Current.getNextNonComment()->is(tok::string_literal)) ||
1211 (Current.TokenText.find("\\\n") != StringRef::npos)))
1212 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001213
1214 // If we need to break somewhere inside the LHS of a binary expression, we
Daniel Jasper7ae41cd2013-07-03 10:34:47 +00001215 // should also break after the operator. Otherwise, the formatting would
1216 // hide the operator precedence, e.g. in:
1217 // if (aaaaaaaaaaaaaa ==
1218 // bbbbbbbbbbbbbb && c) {..
1219 // For comparisons, we only apply this rule, if the LHS is a binary
1220 // expression itself as otherwise, the line breaks seem superfluous.
1221 // We need special cases for ">>" which we have split into two ">" while
1222 // lexing in order to make template parsing easier.
1223 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1224 Previous.getPrecedence() == prec::Equality) &&
1225 Previous.Previous &&
1226 Previous.Previous->Type != TT_BinaryOperator; // For >>.
1227 bool LHSIsBinaryExpr =
1228 Previous.Previous && Previous.Previous->FakeRParens > 0;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001229 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper7ae41cd2013-07-03 10:34:47 +00001230 (!IsComparison || LHSIsBinaryExpr) &&
1231 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasper68d888c2013-06-03 08:42:05 +00001232 !Current.isTrailingComment() &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001233 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001234 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001235 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001236 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001237
Daniel Jasper77d5d312013-07-12 15:14:05 +00001238 // Same as above, but for the first "<<" operator.
1239 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1240 State.Stack.back().FirstLessLess == 0)
1241 return true;
1242
Daniel Jasperd69fc772013-05-08 14:12:04 +00001243 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1244 // out whether it is the first parameter. Clean this up.
1245 if (Current.Type == TT_ObjCSelectorName &&
1246 Current.LongestObjCSelectorName == 0 &&
1247 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001248 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001249 if ((Current.Type == TT_CtorInitializerColon ||
1250 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001251 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001252
Daniel Jasper6331da02013-07-09 07:43:55 +00001253 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1254 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1255 State.ParenLevel == 0)
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001256 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001257 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001258 }
1259
Daniel Jasper9b334242013-03-15 14:57:30 +00001260 // Returns the total number of columns required for the remaining tokens.
1261 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001262 if (State.NextToken && State.NextToken->Previous)
1263 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001264 return 0;
1265 }
1266
Daniel Jasperf7935112012-12-03 18:12:45 +00001267 FormatStyle Style;
1268 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001269 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001270 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001271 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001272 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001273
1274 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1275 QueueType Queue;
1276 // Increasing count of \c StateNode items we have created. This is used
1277 // to create a deterministic order independent of the container.
1278 unsigned Count;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001279 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001280 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001281};
1282
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001283class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001284public:
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001285 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1286 encoding::Encoding Encoding)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001287 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001288 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1289 Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001290 Lex.SetKeepWhitespaceMode(true);
1291 }
1292
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001293 ArrayRef<FormatToken *> lex() {
1294 assert(Tokens.empty());
1295 do {
1296 Tokens.push_back(getNextToken());
1297 } while (Tokens.back()->Tok.isNot(tok::eof));
1298 return Tokens;
1299 }
1300
1301 IdentifierTable &getIdentTable() { return IdentTable; }
1302
1303private:
1304 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001305 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001306 // Create a synthesized second '>' token.
1307 Token Greater = FormatTok->Tok;
1308 FormatTok = new (Allocator.Allocate()) FormatToken;
1309 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001310 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001311 FormatTok->Tok.getLocation().getLocWithOffset(1);
1312 FormatTok->WhitespaceRange =
1313 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001314 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001315 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001316 GreaterStashed = false;
1317 return FormatTok;
1318 }
1319
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001320 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001321 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001322 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001323 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001324 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001325 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001326
1327 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001328 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001329 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001330 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001331 if (Newlines > 0)
Daniel Jasper8369aa52013-07-16 20:28:33 +00001332 FormatTok->LastNewlineOffset =
1333 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001334 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001335 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001336 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1337 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001338
Daniel Jasper8369aa52013-07-16 20:28:33 +00001339 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001340 }
Manuel Klimekef920692013-01-07 07:56:50 +00001341
Manuel Klimek1abf7892013-01-04 23:34:14 +00001342 // In case the token starts with escaped newlines, we want to
1343 // take them into account as whitespace - this pattern is quite frequent
1344 // in macro definitions.
1345 // FIXME: What do we want to do with other escaped spaces, and escaped
1346 // spaces or newlines in the middle of tokens?
1347 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001348 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1349 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001350 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001351 WhitespaceLength += 2;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001352 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001353 }
1354
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001355 TrailingWhitespace = 0;
1356 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001357 StringRef UntrimmedText = FormatTok->TokenText;
1358 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1359 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001360 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001361 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001362 FormatTok->Tok.setIdentifierInfo(&Info);
1363 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001364 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001365 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001366 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001367 GreaterStashed = true;
1368 }
1369
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001370 // Now FormatTok is the next non-whitespace token.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001371 FormatTok->CodePointCount =
1372 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001373
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001374 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001375 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001376 return FormatTok;
1377 }
1378
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001379 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001380 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001381 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001382 Lexer &Lex;
1383 SourceManager &SourceMgr;
1384 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001385 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001386 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1387 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001388
Daniel Jasper8369aa52013-07-16 20:28:33 +00001389 void readRawToken(FormatToken &Tok) {
1390 Lex.LexFromRawLexer(Tok.Tok);
1391 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1392 Tok.Tok.getLength());
1393
1394 // For formatting, treat unterminated string literals like normal string
1395 // literals.
1396 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1397 Tok.TokenText[0] == '"') {
1398 Tok.Tok.setKind(tok::string_literal);
1399 Tok.IsUnterminatedLiteral = true;
1400 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001401 }
1402};
1403
Daniel Jasperf7935112012-12-03 18:12:45 +00001404class Formatter : public UnwrappedLineConsumer {
1405public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001406 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001407 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001408 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001409 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1410 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001411 DEBUG(llvm::dbgs() << "File encoding: "
1412 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1413 : "unknown")
1414 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001415 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001416
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001417 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001418
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001419 tooling::Replacements format() {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001420 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001421
1422 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001423 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001424 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001425 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1426 Annotator.annotate(AnnotatedLines[i]);
1427 }
1428 deriveLocalStyle();
1429 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1430 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1431 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001432
1433 // Adapt level to the next line if this is a comment.
1434 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001435 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001436 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001437 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001438 !AnnotatedLines[i].First->Next)
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001439 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001440 else
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +00001441 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1442 ? &AnnotatedLines[i]
1443 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001444 }
1445
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001446 std::vector<int> IndentForLevel;
1447 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001448 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001449 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001450 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1451 E = AnnotatedLines.end();
1452 I != E; ++I) {
1453 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001454 const FormatToken *FirstTok = TheLine.First;
1455 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001456
1457 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001458 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001459 FormatPPDirective = false;
1460 if (!FormatPPDirective && TheLine.InPPDirective &&
1461 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1462 FormatPPDirective = true;
1463
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001464 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001465 while (IndentForLevel.size() <= TheLine.Level)
1466 IndentForLevel.push_back(-1);
1467 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001468 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1469 if (static_cast<int>(Indent) + Offset >= 0)
1470 Indent += Offset;
1471 tryFitMultipleLinesInOne(Indent, I, E);
1472
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001473 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001474 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001475 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001476 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001477 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001478 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001479 }
1480 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001481 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001482 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001483 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001484 // Insert a break even if there is a structural error in case where
1485 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001486 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001487 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001488 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001489 } else {
1490 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001491 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1492 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001493 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001494 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001495 TheLine.First, Whitespaces, Encoding,
1496 BinPackInconclusiveFunctions);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001497 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001498 IndentForLevel[TheLine.Level] = LevelIndent;
1499 PreviousLineWasTouched = true;
1500 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001501 // Format the first token if necessary, and notify the WhitespaceManager
1502 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001503 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1504 Tok = Tok->Next) {
1505 if (Tok == TheLine.First &&
1506 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1507 unsigned LevelIndent =
1508 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001509 // Remove trailing whitespace of the previous line if it was
1510 // touched.
1511 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1512 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1513 TheLine.InPPDirective);
1514 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001515 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001516 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001517
Manuel Klimek4fe43002013-05-22 12:51:29 +00001518 if (static_cast<int>(LevelIndent) - Offset >= 0)
1519 LevelIndent -= Offset;
1520 if (Tok->isNot(tok::comment))
1521 IndentForLevel[TheLine.Level] = LevelIndent;
1522 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001523 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001524 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001525 }
1526 // If we did not reformat this unwrapped line, the column at the end of
1527 // the last token is unchanged - thus, we can calculate the end of the
1528 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001529 PreviousLineWasTouched = false;
1530 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001531 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001532 }
1533 return Whitespaces.generateReplacements();
1534 }
1535
1536private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001537 void deriveLocalStyle() {
1538 unsigned CountBoundToVariable = 0;
1539 unsigned CountBoundToType = 0;
1540 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001541 bool HasBinPackedFunction = false;
1542 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001543 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001544 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001545 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001546 FormatToken *Tok = AnnotatedLines[i].First->Next;
1547 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001548 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001549 bool SpacesBefore =
1550 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1551 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1552 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001553 if (SpacesBefore && !SpacesAfter)
1554 ++CountBoundToVariable;
1555 else if (!SpacesBefore && SpacesAfter)
1556 ++CountBoundToType;
1557 }
1558
Daniel Jasper400adc62013-02-08 15:28:42 +00001559 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001560 Tok->Previous->Type == TT_TemplateCloser &&
1561 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001562 HasCpp03IncompatibleFormat = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001563
1564 if (Tok->PackingKind == PPK_BinPacked)
1565 HasBinPackedFunction = true;
1566 if (Tok->PackingKind == PPK_OnePerLine)
1567 HasOnePerLineFunction = true;
1568
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001569 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001570 }
1571 }
1572 if (Style.DerivePointerBinding) {
1573 if (CountBoundToType > CountBoundToVariable)
1574 Style.PointerBindsToType = true;
1575 else if (CountBoundToType < CountBoundToVariable)
1576 Style.PointerBindsToType = false;
1577 }
1578 if (Style.Standard == FormatStyle::LS_Auto) {
1579 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1580 : FormatStyle::LS_Cpp03;
1581 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001582 BinPackInconclusiveFunctions =
1583 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001584 }
1585
Manuel Klimekb95f5452013-02-08 17:38:27 +00001586 /// \brief Get the indent of \p Level from \p IndentForLevel.
1587 ///
1588 /// \p IndentForLevel must contain the indent for the level \c l
1589 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1590 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001591 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001592 if (IndentForLevel[Level] != -1)
1593 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001594 if (Level == 0)
1595 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001596 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001597 }
1598
1599 /// \brief Get the offset of the line relatively to the level.
1600 ///
1601 /// For example, 'public:' labels in classes are offset by 1 or 2
1602 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001603 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001604 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001605 return Style.AccessModifierOffset;
1606 return 0;
1607 }
1608
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001609 /// \brief Tries to merge lines into one.
1610 ///
1611 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1612 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001613 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001614 std::vector<AnnotatedLine>::iterator &I,
1615 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001616 // We can never merge stuff if there are trailing line comments.
1617 if (I->Last->Type == TT_LineComment)
1618 return;
1619
Daniel Jasperffefb3d2013-07-24 13:10:59 +00001620 if (Indent > Style.ColumnLimit)
1621 return;
1622
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001623 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001624 // If we already exceed the column limit, we set 'Limit' to 0. The different
1625 // tryMerge..() functions can then decide whether to still do merging.
1626 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001627
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001628 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001629 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001630
Daniel Jasperabca58c2013-05-15 14:09:55 +00001631 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001632 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001633 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001634 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001635 tryMergeSimpleControlStatement(I, E, Limit);
1636 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001637 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001638 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001639 } else if (I->InPPDirective &&
1640 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001641 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001642 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001643 }
1644
Daniel Jasper39825ea2013-01-14 15:40:57 +00001645 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1646 std::vector<AnnotatedLine>::iterator E,
1647 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001648 if (Limit == 0)
1649 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001650 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001651 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001652 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001653 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001654 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001655 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001656 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001657 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001658 join(Line, *(++I));
1659 }
1660
Daniel Jasper3a685df2013-05-16 12:12:21 +00001661 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1662 std::vector<AnnotatedLine>::iterator E,
1663 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001664 if (Limit == 0)
1665 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001666 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001667 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001668 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001669 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001670 if (Line.Last->isNot(tok::r_paren))
1671 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001672 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001673 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001674 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1675 tok::kw_while) ||
1676 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001677 return;
1678 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001679 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1680 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001681 return;
1682 join(Line, *(++I));
1683 }
1684
1685 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001686 std::vector<AnnotatedLine>::iterator E,
1687 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001688 // No merging if the brace already is on the next line.
1689 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1690 return;
1691
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001692 // First, check that the current line allows merging. This is the case if
1693 // we're not in a control flow statement and the last token is an opening
1694 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001695 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001696 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1697 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001698 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001699 // This gets rid of all ObjC @ keywords and methods.
1700 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001701 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001702
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001703 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001704 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001705 (Tok->getNextNonComment() == NULL ||
1706 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001707 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001708 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001709 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001710 join(Line, *(I + 1));
1711 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001712 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001713 // Check that we still have three lines and they fit into the limit.
1714 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1715 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001716 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001717
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001718 // Second, check that the next line does not contain any braces - if it
1719 // does, readability declines when putting it into a single line.
1720 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1721 return;
1722 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001723 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001724 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001725 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001726 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001727
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001728 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001729 Tok = (I + 2)->First;
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001730 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001731 Tok->MustBreakBefore)
1732 return;
1733
1734 join(Line, *(I + 1));
1735 join(Line, *(I + 2));
1736 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001737 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001738 }
1739
1740 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1741 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001742 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1743 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001744 }
1745
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001746 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001747 assert(!A.Last->Next);
1748 assert(!B.First->Previous);
1749 A.Last->Next = B.First;
1750 B.First->Previous = A.Last;
1751 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1752 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1753 Tok->TotalLength += LengthA;
1754 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001755 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001756 }
1757
Daniel Jasper97b89482013-03-13 07:49:51 +00001758 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001759 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1760 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1761 Ranges[i].getBegin()) &&
1762 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1763 Range.getBegin()))
1764 return true;
1765 }
1766 return false;
1767 }
1768
1769 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001770 const FormatToken *First = TheLine.First;
1771 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001772 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001773 First->WhitespaceRange.getBegin().getLocWithOffset(
1774 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001775 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001776 return touchesRanges(LineRange);
1777 }
1778
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001779 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1780 std::vector<AnnotatedLine>::iterator E) {
1781 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001782 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001783 return false;
1784 if (touchesLine(*I))
1785 return true;
1786 }
1787 return false;
1788 }
1789
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001790 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001791 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001792 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001793 First->WhitespaceRange.getBegin(),
1794 First->WhitespaceRange.getBegin().getLocWithOffset(
1795 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001796 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001797 }
1798
1799 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001800 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001801 }
1802
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001803 /// \brief Add a new line and the required indent before the first Token
1804 /// of the \c UnwrappedLine if there was no structural parsing error.
1805 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001806 void formatFirstToken(const FormatToken &RootToken,
1807 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001808 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001809 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001810 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001811 // Remove empty lines before "}" where applicable.
1812 if (RootToken.is(tok::r_brace) &&
1813 (!RootToken.Next ||
1814 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1815 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001816 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001817 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001818
Manuel Klimek4fe43002013-05-22 12:51:29 +00001819 // Insert extra new line before access specifiers.
1820 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001821 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001822 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001823
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001824 Whitespaces.replaceWhitespace(
1825 RootToken, Newlines, Indent, Indent,
1826 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001827 }
1828
Daniel Jasperf7935112012-12-03 18:12:45 +00001829 FormatStyle Style;
1830 Lexer &Lex;
1831 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001832 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001833 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001834 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001835
1836 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001837 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001838};
1839
Craig Topperaf35e852013-06-30 22:29:28 +00001840} // end anonymous namespace
1841
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001842tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1843 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001844 std::vector<CharSourceRange> Ranges) {
1845 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001846 return formatter.format();
1847}
1848
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001849tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1850 std::vector<tooling::Range> Ranges,
1851 StringRef FileName) {
1852 FileManager Files((FileSystemOptions()));
1853 DiagnosticsEngine Diagnostics(
1854 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1855 new DiagnosticOptions);
1856 SourceManager SourceMgr(Diagnostics, Files);
1857 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1858 const clang::FileEntry *Entry =
1859 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1860 SourceMgr.overrideFileContents(Entry, Buf);
1861 FileID ID =
1862 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001863 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1864 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001865 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1866 std::vector<CharSourceRange> CharRanges;
1867 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1868 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1869 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1870 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1871 }
1872 return reformat(Style, Lex, SourceMgr, CharRanges);
1873}
1874
Alexander Kornienko1e808872013-06-28 12:51:24 +00001875LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001876 LangOptions LangOpts;
1877 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001878 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001879 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001880 LangOpts.Bool = 1;
1881 LangOpts.ObjC1 = 1;
1882 LangOpts.ObjC2 = 1;
1883 return LangOpts;
1884}
1885
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001886} // namespace format
1887} // namespace clang