blob: 156ff6429c003c28f32165f1a4a4bf2c14e212c3 [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
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.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"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000030#include "llvm/Support/Path.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 <>
Alexander Kornienkocabdd732013-11-29 15:19:43 +000037struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageKind> {
38 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageKind &Value) {
40 IO.enumCase(Value, "Cpp", clang::format::FormatStyle::LK_Cpp);
41 IO.enumCase(Value, "JavaScript", clang::format::FormatStyle::LK_JavaScript);
42 }
43};
44
45template <>
Alexander Kornienkod6538332013-05-07 15:32:14 +000046struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000047 static void enumeration(IO &IO,
48 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000049 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000050 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000051 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000052 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
53 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
54 }
55};
56
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000057template <>
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000058struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000059 static void enumeration(IO &IO,
60 clang::format::FormatStyle::UseTabStyle &Value) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000061 IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation",
66 clang::format::FormatStyle::UT_ForIndentation);
67 }
68};
69
70template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000071struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
72 static void
73 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
74 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
75 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
76 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +000077 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod6538332013-05-07 15:32:14 +000078 }
79};
80
Daniel Jasper65ee3472013-07-31 23:16:02 +000081template <>
82struct ScalarEnumerationTraits<
83 clang::format::FormatStyle::NamespaceIndentationKind> {
84 static void
85 enumeration(IO &IO,
86 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
87 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
88 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
89 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
90 }
91};
92
Alexander Kornienkod6538332013-05-07 15:32:14 +000093template <> struct MappingTraits<clang::format::FormatStyle> {
94 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000095 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +000096 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
97 "Mozilla", "WebKit" };
Alexander Kornienko49149672013-05-10 11:56:10 +000098 ArrayRef<StringRef> Styles(StylesArray);
99 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
100 StringRef StyleName(Styles[i]);
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000101 clang::format::FormatStyle PredefinedStyle;
102 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
103 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000104 IO.mapOptional("# BasedOnStyle", StyleName);
105 break;
106 }
107 }
108 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000109 StringRef BasedOnStyle;
110 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000111 if (!BasedOnStyle.empty()) {
112 clang::format::FormatStyle::LanguageKind Language = Style.Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000113 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
114 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
115 return;
116 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000117 Style.Language = Language;
118 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000119 }
120
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000121 IO.mapOptional("Language", Style.Language);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000122 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000123 IO.mapOptional("ConstructorInitializerIndentWidth",
124 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000125 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000126 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000127 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
128 Style.AllowAllParametersOfDeclarationOnNextLine);
129 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
130 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000131 IO.mapOptional("AllowShortLoopsOnASingleLine",
132 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000133 IO.mapOptional("AllowShortFunctionsOnASingleLine",
134 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000135 IO.mapOptional("AlwaysBreakTemplateDeclarations",
136 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000137 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
138 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000139 IO.mapOptional("BreakBeforeBinaryOperators",
140 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000141 IO.mapOptional("BreakBeforeTernaryOperators",
142 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000143 IO.mapOptional("BreakConstructorInitializersBeforeComma",
144 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000145 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
146 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
147 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
148 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
149 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000150 IO.mapOptional("ExperimentalAutoDetectBinPacking",
151 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000152 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
153 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000154 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000155 IO.mapOptional("ObjCSpaceBeforeProtocolList",
156 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000157 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
158 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000159 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
160 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000161 IO.mapOptional("PenaltyBreakFirstLessLess",
162 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000163 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
164 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
165 Style.PenaltyReturnTypeOnItsOwnLine);
166 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
167 IO.mapOptional("SpacesBeforeTrailingComments",
168 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000169 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000171 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000172 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000173 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000174 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000175 IO.mapOptional("IndentFunctionDeclarationAfterType",
176 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000177 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000178 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000179 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000180 IO.mapOptional("SpacesInCStyleCastParentheses",
181 Style.SpacesInCStyleCastParentheses);
182 IO.mapOptional("SpaceAfterControlStatementKeyword",
183 Style.SpaceAfterControlStatementKeyword);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000184 IO.mapOptional("SpaceBeforeAssignmentOperators",
185 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000186 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000187 }
188};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000189
190// Allows to read vector<FormatStyle> while keeping default values.
191// Elements will be written or read starting from the 1st element.
192// When writing, the 0th element is ignored.
193// When reading, keys that are not present in the serialized form will be
194// copied from the 0th element of the vector. If the first element had no
195// Language specified, it will be treated as the default one for the following
196// elements.
197template <>
198struct DocumentListTraits<std::vector<clang::format::FormatStyle> > {
199 static size_t size(IO &io, std::vector<clang::format::FormatStyle> &Seq) {
200 return Seq.size() - 1;
201 }
202 static clang::format::FormatStyle &
203 element(IO &io, std::vector<clang::format::FormatStyle> &Seq, size_t Index) {
204 if (Index + 2 > Seq.size()) {
205 assert(Index + 2 == Seq.size() + 1);
206 clang::format::FormatStyle Template;
207 if (Seq.size() > 1 &&
208 Seq[1].Language == clang::format::FormatStyle::LK_None) {
209 Template = Seq[1];
210 } else {
211 Template = Seq[0];
212 Template.Language = clang::format::FormatStyle::LK_None;
213 }
214 Seq.resize(Index + 2, Template);
215 }
216 return Seq[Index + 1];
217 }
218};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000219}
220}
221
Daniel Jasperf7935112012-12-03 18:12:45 +0000222namespace clang {
223namespace format {
224
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000225void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasper2739af32013-08-28 10:03:58 +0000226 Style.PenaltyBreakComment = 60;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000227 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000228 Style.PenaltyBreakString = 1000;
229 Style.PenaltyExcessCharacter = 1000000;
230}
231
Daniel Jasperf7935112012-12-03 18:12:45 +0000232FormatStyle getLLVMStyle() {
233 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000234 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000235 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000236 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000237 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000238 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000239 LLVMStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000240 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000241 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000242 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000243 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000244 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000245 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000246 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000247 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
248 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000249 LLVMStyle.ColumnLimit = 80;
250 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000251 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000252 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000253 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000254 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000255 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000256 LLVMStyle.IndentFunctionDeclarationAfterType = false;
257 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000258 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000259 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000260 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000261 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000262 LLVMStyle.PointerBindsToType = false;
263 LLVMStyle.SpacesBeforeTrailingComments = 1;
264 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000265 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000266 LLVMStyle.SpacesInParentheses = false;
267 LLVMStyle.SpaceInEmptyParentheses = false;
268 LLVMStyle.SpacesInCStyleCastParentheses = false;
269 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000270 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000271 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000272 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000273
274 setDefaultPenalties(LLVMStyle);
275 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000276 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000277
Daniel Jasperf7935112012-12-03 18:12:45 +0000278 return LLVMStyle;
279}
280
281FormatStyle getGoogleStyle() {
282 FormatStyle GoogleStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000283 GoogleStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000284 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000285 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000286 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000287 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000288 GoogleStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000289 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000290 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000291 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000292 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000293 GoogleStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000294 GoogleStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000295 GoogleStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000296 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
297 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000298 GoogleStyle.ColumnLimit = 80;
299 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000300 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000301 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000302 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000303 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000304 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000305 GoogleStyle.IndentFunctionDeclarationAfterType = true;
306 GoogleStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000307 GoogleStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000308 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000309 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000310 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000311 GoogleStyle.PointerBindsToType = true;
312 GoogleStyle.SpacesBeforeTrailingComments = 2;
313 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000314 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000315 GoogleStyle.SpacesInParentheses = false;
316 GoogleStyle.SpaceInEmptyParentheses = false;
317 GoogleStyle.SpacesInCStyleCastParentheses = false;
318 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000319 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000320 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000321 GoogleStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000322
323 setDefaultPenalties(GoogleStyle);
324 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000325 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000326
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 return GoogleStyle;
328}
329
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000330FormatStyle getChromiumStyle() {
331 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000332 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000333 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000334 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000335 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000336 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000337 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000338 return ChromiumStyle;
339}
340
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000341FormatStyle getMozillaStyle() {
342 FormatStyle MozillaStyle = getLLVMStyle();
343 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
344 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
345 MozillaStyle.DerivePointerBinding = true;
346 MozillaStyle.IndentCaseLabels = true;
347 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
348 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
349 MozillaStyle.PointerBindsToType = true;
350 return MozillaStyle;
351}
352
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000353FormatStyle getWebKitStyle() {
354 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000355 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000356 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000357 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000358 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000359 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000360 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000361 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000362 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000363 Style.PointerBindsToType = true;
364 return Style;
365}
366
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000367bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000368 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000369 *Style = getLLVMStyle();
370 else if (Name.equals_lower("chromium"))
371 *Style = getChromiumStyle();
372 else if (Name.equals_lower("mozilla"))
373 *Style = getMozillaStyle();
374 else if (Name.equals_lower("google"))
375 *Style = getGoogleStyle();
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000376 else if (Name.equals_lower("webkit"))
377 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000378 else
379 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000380
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000381 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000382}
383
384llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000385 assert(Style);
386 assert(Style->Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000387 if (Text.trim().empty())
388 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000389
390 std::vector<FormatStyle> Styles;
391 // DocumentListTraits<vector<FormatStyle>> uses 0th element as the default one
392 // for the fields, keys for which are missing from the configuration.
393 Styles.push_back(*Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000394 llvm::yaml::Input Input(Text);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000395 Input >> Styles;
396 if (Input.error())
397 return Input.error();
398
399 for (unsigned i = 1; i < Styles.size(); ++i) {
400 // Ensures that only the first configuration can skip the Language option.
401 if (Styles[i].Language == FormatStyle::LK_None && i != 1)
402 return llvm::make_error_code(llvm::errc::invalid_argument);
403 // Ensure that each language is configured at most once.
404 for (unsigned j = 1; j < i; ++j) {
405 if (Styles[i].Language == Styles[j].Language)
406 return llvm::make_error_code(llvm::errc::invalid_argument);
407 }
408 }
409 // Look for a suitable configuration starting from the end, so we can
410 // find the configuration for the specific language first, and the default
411 // configuration (which can only be at slot 1) after it.
412 for (unsigned i = Styles.size() - 1; i > 0; --i) {
413 if (Styles[i].Language == Styles[0].Language ||
414 Styles[i].Language == FormatStyle::LK_None) {
415 *Style = Styles[i];
416 Style->Language = Styles[0].Language;
417 return llvm::make_error_code(llvm::errc::success);
418 }
419 }
420 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000421}
422
423std::string configurationAsText(const FormatStyle &Style) {
424 std::string Text;
425 llvm::raw_string_ostream Stream(Text);
426 llvm::yaml::Output Output(Stream);
427 // We use the same mapping method for input and output, so we need a non-const
428 // reference here.
429 FormatStyle NonConstStyle = Style;
430 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000431 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000432}
433
Craig Topperaf35e852013-06-30 22:29:28 +0000434namespace {
435
Daniel Jasperde0328a2013-08-16 11:20:30 +0000436class NoColumnLimitFormatter {
437public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000438 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000439
440 /// \brief Formats the line starting at \p State, simply keeping all of the
441 /// input's line breaking decisions.
Alexander Kornienko31e95542013-12-04 12:21:08 +0000442 void format(unsigned FirstIndent, const AnnotatedLine *Line,
443 bool LineIsMerged) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000444 LineState State =
445 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000446 while (State.NextToken != NULL) {
447 bool Newline =
Alexander Kornienko31e95542013-12-04 12:21:08 +0000448 (!LineIsMerged && Indenter->mustBreak(State)) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000449 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
450 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
451 }
452 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000453
Daniel Jasperde0328a2013-08-16 11:20:30 +0000454private:
455 ContinuationIndenter *Indenter;
456};
457
Daniel Jasper56f8b432013-11-06 23:12:09 +0000458class LineJoiner {
459public:
460 LineJoiner(const FormatStyle &Style) : Style(Style) {}
461
462 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
463 unsigned
464 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000465 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000466 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
467 // We can never merge stuff if there are trailing line comments.
468 AnnotatedLine *TheLine = *I;
469 if (TheLine->Last->Type == TT_LineComment)
470 return 0;
471
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000472 unsigned Limit =
473 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000474 // If we already exceed the column limit, we set 'Limit' to 0. The different
475 // tryMerge..() functions can then decide whether to still do merging.
476 Limit = TheLine->Last->TotalLength > Limit
477 ? 0
478 : Limit - TheLine->Last->TotalLength;
479
Alexander Kornienko31e95542013-12-04 12:21:08 +0000480 if (Indent > Limit)
481 return 0;
482
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000483 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000484 return 0;
485
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000486 if (TheLine->Last->Type == TT_FunctionLBrace) {
487 return Style.AllowShortFunctionsOnASingleLine
488 ? tryMergeSimpleBlock(I, E, Limit)
489 : 0;
490 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000491 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000492 return Style.BreakBeforeBraces == clang::format::FormatStyle::BS_Attach
493 ? tryMergeSimpleBlock(I, E, Limit)
494 : 0;
495 }
496 if (I[1]->First->Type == TT_FunctionLBrace &&
497 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
498 // Reduce the column limit by the number of spaces we need to insert
499 // around braces.
500 Limit = Limit > 3 ? Limit - 3 : 0;
501 unsigned MergedLines = 0;
502 if (Style.AllowShortFunctionsOnASingleLine) {
503 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
504 // If we managed to merge the block, count the function header, which is
505 // on a separate line.
506 if (MergedLines > 0)
507 ++MergedLines;
508 }
509 return MergedLines;
510 }
511 if (TheLine->First->is(tok::kw_if)) {
512 return Style.AllowShortIfStatementsOnASingleLine
513 ? tryMergeSimpleControlStatement(I, E, Limit)
514 : 0;
515 }
516 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
517 return Style.AllowShortLoopsOnASingleLine
518 ? tryMergeSimpleControlStatement(I, E, Limit)
519 : 0;
520 }
521 if (TheLine->InPPDirective &&
522 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000523 return tryMergeSimplePPDirective(I, E, Limit);
524 }
525 return 0;
526 }
527
528private:
529 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000530 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000531 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
532 unsigned Limit) {
533 if (Limit == 0)
534 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000535 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000536 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000537 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000538 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000539 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000540 return 0;
541 return 1;
542 }
543
544 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000545 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000546 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
547 if (Limit == 0)
548 return 0;
549 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000550 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000551 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000552 if (I[1]->InPPDirective != (*I)->InPPDirective ||
553 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000554 return 0;
555 AnnotatedLine &Line = **I;
556 if (Line.Last->isNot(tok::r_paren))
557 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000558 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000559 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000560 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000561 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000562 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000563 return 0;
564 // Only inline simple if's (no nested if or else).
565 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000566 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000567 return 0;
568 return 1;
569 }
570
571 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000572 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000573 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
574 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000575 // First, check that the current line allows merging. This is the case if
576 // we're not in a control flow statement and the last token is an opening
577 // brace.
578 AnnotatedLine &Line = **I;
579 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
580 tok::kw_else, tok::kw_try, tok::kw_catch,
581 tok::kw_for,
582 // This gets rid of all ObjC @ keywords and methods.
583 tok::at, tok::minus, tok::plus))
584 return 0;
585
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000586 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000587 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
588 (Tok->getNextNonComment() == NULL ||
589 Tok->getNextNonComment()->is(tok::semi))) {
590 // We merge empty blocks even if the line exceeds the column limit.
591 Tok->SpacesRequiredBefore = 0;
592 Tok->CanBreakBefore = true;
593 return 1;
594 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
595 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000596 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000597 return 0;
598
599 if (!nextTwoLinesFitInto(I, Limit))
600 return 0;
601
602 // Second, check that the next line does not contain any braces - if it
603 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000604 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000605 return 0;
606 do {
607 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
608 return 0;
609 Tok = Tok->Next;
610 } while (Tok != NULL);
611
612 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000613 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000614 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
615 Tok->MustBreakBefore)
616 return 0;
617
618 return 2;
619 }
620 return 0;
621 }
622
623 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
624 unsigned Limit) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000625 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000626 }
627
628 const FormatStyle &Style;
629};
630
Daniel Jasperf7935112012-12-03 18:12:45 +0000631class UnwrappedLineFormatter {
632public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000633 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000634 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000635 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000636 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
637 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000638
Daniel Jasper56f8b432013-11-06 23:12:09 +0000639 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000640 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000641 assert(!Lines.empty());
642 unsigned Penalty = 0;
643 std::vector<int> IndentForLevel;
644 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
645 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000646 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000647 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
648 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000649 I != E; ++I) {
650 const AnnotatedLine &TheLine = **I;
651 const FormatToken *FirstTok = TheLine.First;
652 int Offset = getIndentOffset(*FirstTok);
653
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000654 // Determine indent and try to merge multiple unwrapped lines.
655 while (IndentForLevel.size() <= TheLine.Level)
656 IndentForLevel.push_back(-1);
657 IndentForLevel.resize(TheLine.Level + 1);
658 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
659 if (static_cast<int>(Indent) + Offset >= 0)
660 Indent += Offset;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000661 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000662 if (MergedLines > 0 && Style.ColumnLimit == 0) {
663 // Disallow line merging if there is a break at the start of one of the
664 // input lines.
665 for (unsigned i = 0; i < MergedLines; ++i) {
666 if (I[i + 1]->First->NewlinesBefore > 0)
667 MergedLines = 0;
668 }
669 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 if (!DryRun) {
671 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000672 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000673 }
674 }
675 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000676
Daniel Jasper9c199562013-11-28 15:58:55 +0000677 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
678 bool FixIndentation =
679 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000680 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000681 if (PreviousLine && PreviousLine->Affected && !DryRun) {
682 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000683 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
684 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
685 /*IndentLevel=*/0, /*Spaces=*/0,
686 /*TargetColumn=*/0);
687 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000688 } else if (TheLine.Type != LT_Invalid &&
689 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000690 if (FirstTok->WhitespaceRange.isValid()) {
691 if (!DryRun)
692 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
693 Indent, TheLine.InPPDirective);
694 } else {
695 Indent = LevelIndent = FirstTok->OriginalColumn;
696 }
697
698 // If everything fits on a single line, just put it there.
699 unsigned ColumnLimit = Style.ColumnLimit;
700 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000701 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000702 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
703 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
704 }
705
706 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
707 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
708 while (State.NextToken != NULL)
709 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
710 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000711 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000712 NoColumnLimitFormatter Formatter(Indenter);
713 if (!DryRun)
Alexander Kornienko31e95542013-12-04 12:21:08 +0000714 Formatter.format(Indent, &TheLine,
715 /*LineIsMerged=*/MergedLines > 0);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000716 } else {
717 Penalty += format(TheLine, Indent, DryRun);
718 }
719
720 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000721 } else if (TheLine.ChildrenAffected) {
722 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000723 } else {
724 // Format the first token if necessary, and notify the WhitespaceManager
725 // about the unchanged whitespace.
726 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
727 if (Tok == TheLine.First &&
728 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
729 unsigned LevelIndent = Tok->OriginalColumn;
730 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000731 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000732 if ((PreviousLine && PreviousLine->Affected) ||
733 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000734 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
735 TheLine.InPPDirective);
736 } else {
737 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
738 }
739 }
740
741 if (static_cast<int>(LevelIndent) - Offset >= 0)
742 LevelIndent -= Offset;
743 if (Tok->isNot(tok::comment))
744 IndentForLevel[TheLine.Level] = LevelIndent;
745 } else if (!DryRun) {
746 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
747 }
748 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000749 }
750 if (!DryRun) {
751 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
752 Tok->Finalized = true;
753 }
754 }
755 PreviousLine = *I;
756 }
757 return Penalty;
758 }
759
760private:
761 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000762 ///
763 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000764 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
765 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000766 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000767
Daniel Jasperacc33662013-02-08 08:22:00 +0000768 // If the ObjC method declaration does not fit on a line, we should format
769 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000770 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000771 State.Stack.back().BreakBeforeParameter = true;
772
Daniel Jasper4b866272013-02-01 11:00:45 +0000773 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000774 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 }
776
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000777 /// \brief An edge in the solution space from \c Previous->State to \c State,
778 /// inserting a newline dependent on the \c NewLine.
779 struct StateNode {
780 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000781 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000782 LineState State;
783 bool NewLine;
784 StateNode *Previous;
785 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000786
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000787 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
788 ///
789 /// In case of equal penalties, we want to prefer states that were inserted
790 /// first. During state generation we make sure that we insert states first
791 /// that break the line as late as possible.
792 typedef std::pair<unsigned, unsigned> OrderedPenalty;
793
794 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
795 /// \c State has the given \c OrderedPenalty.
796 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
797
798 /// \brief The BFS queue type.
799 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
800 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000801
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000802 /// \brief Get the offset of the line relatively to the level.
803 ///
804 /// For example, 'public:' labels in classes are offset by 1 or 2
805 /// characters to the left from their level.
806 int getIndentOffset(const FormatToken &RootToken) {
807 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
808 return Style.AccessModifierOffset;
809 return 0;
810 }
811
812 /// \brief Add a new line and the required indent before the first Token
813 /// of the \c UnwrappedLine if there was no structural parsing error.
814 void formatFirstToken(FormatToken &RootToken,
815 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
816 unsigned Indent, bool InPPDirective) {
817 unsigned Newlines =
818 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
819 // Remove empty lines before "}" where applicable.
820 if (RootToken.is(tok::r_brace) &&
821 (!RootToken.Next ||
822 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
823 Newlines = std::min(Newlines, 1u);
824 if (Newlines == 0 && !RootToken.IsFirst)
825 Newlines = 1;
826
827 // Insert extra new line before access specifiers.
828 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
829 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
830 ++Newlines;
831
832 // Remove empty lines after access specifiers.
833 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
834 Newlines = std::min(1u, Newlines);
835
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000836 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
837 Indent, InPPDirective &&
838 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000839 }
840
841 /// \brief Get the indent of \p Level from \p IndentForLevel.
842 ///
843 /// \p IndentForLevel must contain the indent for the level \c l
844 /// at \p IndentForLevel[l], or a value < 0 if the indent for
845 /// that level is unknown.
846 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
847 if (IndentForLevel[Level] != -1)
848 return IndentForLevel[Level];
849 if (Level == 0)
850 return 0;
851 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
852 }
853
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000854 void join(AnnotatedLine &A, const AnnotatedLine &B) {
855 assert(!A.Last->Next);
856 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000857 if (B.Affected)
858 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000859 A.Last->Next = B.First;
860 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000861 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000862 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
863 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
864 Tok->TotalLength += LengthA;
865 A.Last = Tok;
866 }
867 }
868
869 unsigned getColumnLimit(bool InPPDirective) const {
870 // In preprocessor directives reserve two chars for trailing " \"
871 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
872 }
873
Daniel Jasper4b866272013-02-01 11:00:45 +0000874 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000876 /// This implements a variant of Dijkstra's algorithm on the graph that spans
877 /// the solution space (\c LineStates are the nodes). The algorithm tries to
878 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000879 /// to a state where all tokens are placed. Returns the penalty.
880 ///
881 /// If \p DryRun is \c false, directly applies the changes.
882 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000883 std::set<LineState> Seen;
884
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000885 // Increasing count of \c StateNode items we have created. This is used to
886 // create a deterministic order independent of the container.
887 unsigned Count = 0;
888 QueueType Queue;
889
Daniel Jasper4b866272013-02-01 11:00:45 +0000890 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000891 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000892 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
893 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
894 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000895
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000896 unsigned Penalty = 0;
897
Daniel Jasper4b866272013-02-01 11:00:45 +0000898 // While not empty, take first element and follow edges.
899 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000900 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000901 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000902 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000903 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000904 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000905 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000907
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000908 // Cut off the analysis of certain solutions if the analysis gets too
909 // complex. See description of IgnoreStackForComparison.
910 if (Count > 10000)
911 Node->State.IgnoreStackForComparison = true;
912
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000913 if (!Seen.insert(Node->State).second)
914 // State already examined with lower penalty.
915 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000916
Manuel Klimek71814b42013-10-11 21:25:45 +0000917 FormatDecision LastFormat = Node->State.NextToken->Decision;
918 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000919 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +0000920 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000921 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +0000922 }
923
Manuel Klimek71814b42013-10-11 21:25:45 +0000924 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000925 // We were unable to find a solution, do nothing.
926 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +0000927 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000928 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +0000929 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000930
Daniel Jasper4b866272013-02-01 11:00:45 +0000931 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000932 if (!DryRun)
933 reconstructPath(InitialState, Queue.top().second);
934
Alexander Kornienko49149672013-05-10 11:56:10 +0000935 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
936 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000937
938 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000939 }
940
941 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000942 std::deque<StateNode *> Path;
943 // We do not need a break before the initial token.
944 while (Current->Previous) {
945 Path.push_front(Current);
946 Current = Current->Previous;
947 }
948 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
949 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000950 unsigned Penalty = 0;
951 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
952 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
953
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000954 DEBUG({
955 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000956 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000957 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000958 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000959 }
960 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000961 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000962 }
963
Manuel Klimekaf491072013-02-13 10:54:19 +0000964 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000965 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000966 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000967 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000968 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000969 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000970 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000971 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000972 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000973 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000974
975 StateNode *Node = new (Allocator.Allocate())
976 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000977 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
978 return;
979
Daniel Jasperde0328a2013-08-16 11:20:30 +0000980 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000981
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000982 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
983 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +0000984 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000985
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000986 /// \brief If the \p State's next token is an r_brace closing a nested block,
987 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000988 ///
989 /// Returns \c true if all children could be placed successfully and adapts
990 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
991 /// creates changes using \c Whitespaces.
992 ///
993 /// The crucial idea here is that children always get formatted upon
994 /// encountering the closing brace right after the nested block. Now, if we
995 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
996 /// \c false), the entire block has to be kept on the same line (which is only
997 /// possible if it fits on the line, only contains a single statement, etc.
998 ///
999 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1000 /// break after the "{", format all lines with correct indentation and the put
1001 /// the closing "}" on yet another new line.
1002 ///
1003 /// This enables us to keep the simple structure of the
1004 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1005 /// break or don't break.
1006 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1007 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001008 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001009 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1010 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1011 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001012 // The previous token does not open a block. Nothing to do. We don't
1013 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001014 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001015
1016 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001017 int AdditionalIndent = State.Stack.back().Indent -
1018 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001019 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1020 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001021 return true;
1022 }
1023
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001024 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001025 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001026 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001027
1028 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001029 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001030 return false;
1031
1032 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001033 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001034 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001035 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001036 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001037 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001038 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001039
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001040 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001041 return true;
1042 }
1043
Daniel Jasperde0328a2013-08-16 11:20:30 +00001044 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001045 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001046 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001047 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001048
1049 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001050};
1051
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001052class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001053public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001054 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001055 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001056 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001057 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1058 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001059 Lex.SetKeepWhitespaceMode(true);
1060 }
1061
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001062 ArrayRef<FormatToken *> lex() {
1063 assert(Tokens.empty());
1064 do {
1065 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001066 tryMergePreviousTokens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001067 } while (Tokens.back()->Tok.isNot(tok::eof));
1068 return Tokens;
1069 }
1070
1071 IdentifierTable &getIdentTable() { return IdentTable; }
1072
1073private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001074 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001075 if (tryMerge_TMacro())
1076 return;
1077
1078 if (Style.Language == FormatStyle::LK_JavaScript) {
1079 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1080 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1081 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1082 tok::greaterequal };
1083 // FIXME: We probably need to change token type to mimic operator with the
1084 // correct priority.
1085 if (tryMergeTokens(JSIdentity))
1086 return;
1087 if (tryMergeTokens(JSNotIdentity))
1088 return;
1089 if (tryMergeTokens(JSShiftEqual))
1090 return;
1091 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001092 }
1093
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001094 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1095 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001096 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001097
1098 SmallVectorImpl<FormatToken *>::const_iterator First =
1099 Tokens.end() - Kinds.size();
1100 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001101 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001102 unsigned AddLength = 0;
1103 for (unsigned i = 1; i < Kinds.size(); ++i) {
1104 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1105 First[i]->WhitespaceRange.getEnd())
1106 return false;
1107 AddLength += First[i]->TokenText.size();
1108 }
1109 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1110 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1111 First[0]->TokenText.size() + AddLength);
1112 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001113 return true;
1114 }
1115
1116 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001117 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001118 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001119 FormatToken *Last = Tokens.back();
1120 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001121 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001122
1123 FormatToken *String = Tokens[Tokens.size() - 2];
1124 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001125 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001126
1127 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001128 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001129
1130 FormatToken *Macro = Tokens[Tokens.size() - 4];
1131 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001132 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001133
1134 const char *Start = Macro->TokenText.data();
1135 const char *End = Last->TokenText.data() + Last->TokenText.size();
1136 String->TokenText = StringRef(Start, End - Start);
1137 String->IsFirst = Macro->IsFirst;
1138 String->LastNewlineOffset = Macro->LastNewlineOffset;
1139 String->WhitespaceRange = Macro->WhitespaceRange;
1140 String->OriginalColumn = Macro->OriginalColumn;
1141 String->ColumnWidth = encoding::columnWidthWithTabs(
1142 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1143
1144 Tokens.pop_back();
1145 Tokens.pop_back();
1146 Tokens.pop_back();
1147 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001148 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001149 }
1150
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001151 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001152 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001153 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001154 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001155 Token Greater = FormatTok->Tok;
1156 FormatTok = new (Allocator.Allocate()) FormatToken;
1157 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001158 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001159 FormatTok->Tok.getLocation().getLocWithOffset(1);
1160 FormatTok->WhitespaceRange =
1161 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001162 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001163 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001164 GreaterStashed = false;
1165 return FormatTok;
1166 }
1167
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001168 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001169 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001170 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001171 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001172 FormatTok->IsFirst = IsFirstToken;
1173 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001174
1175 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001176 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001177 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001178 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1179 switch (FormatTok->TokenText[i]) {
1180 case '\n':
1181 ++FormatTok->NewlinesBefore;
1182 // FIXME: This is technically incorrect, as it could also
1183 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001184 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1185 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1186 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001187 FormatTok->HasUnescapedNewline = true;
1188 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1189 Column = 0;
1190 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001191 case '\r':
1192 case '\f':
1193 case '\v':
1194 Column = 0;
1195 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001196 case ' ':
1197 ++Column;
1198 break;
1199 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001200 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001201 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001202 case '\\':
1203 ++Column;
1204 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1205 FormatTok->TokenText[i + 1] != '\n'))
1206 FormatTok->Type = TT_ImplicitStringLiteral;
1207 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001208 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001209 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001210 ++Column;
1211 break;
1212 }
1213 }
1214
Daniel Jasper877615c2013-10-11 19:45:02 +00001215 if (FormatTok->Type == TT_ImplicitStringLiteral)
1216 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001217 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001218
Daniel Jasper8369aa52013-07-16 20:28:33 +00001219 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001220 }
Manuel Klimekef920692013-01-07 07:56:50 +00001221
Manuel Klimek1abf7892013-01-04 23:34:14 +00001222 // In case the token starts with escaped newlines, we want to
1223 // take them into account as whitespace - this pattern is quite frequent
1224 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001225 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001226 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1227 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001228 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001229 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001230 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001231 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001232 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001233
1234 FormatTok->WhitespaceRange = SourceRange(
1235 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1236
Manuel Klimek31c85922013-08-29 15:21:40 +00001237 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001238
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001239 TrailingWhitespace = 0;
1240 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001241 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001242 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001243 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001244 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001245 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001246 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001247 FormatTok->Tok.setIdentifierInfo(&Info);
1248 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001249 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001250 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001251 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001252 GreaterStashed = true;
1253 }
1254
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001255 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001256
Alexander Kornienko39856b72013-09-10 09:38:25 +00001257 StringRef Text = FormatTok->TokenText;
1258 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001259 if (FirstNewlinePos == StringRef::npos) {
1260 // FIXME: ColumnWidth actually depends on the start column, we need to
1261 // take this into account when the token is moved.
1262 FormatTok->ColumnWidth =
1263 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1264 Column += FormatTok->ColumnWidth;
1265 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001266 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001267 // FIXME: ColumnWidth actually depends on the start column, we need to
1268 // take this into account when the token is moved.
1269 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1270 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1271
Alexander Kornienko39856b72013-09-10 09:38:25 +00001272 // The last line of the token always starts in column 0.
1273 // Thus, the length can be precomputed even in the presence of tabs.
1274 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1275 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1276 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001277 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001278 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001279
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001280 return FormatTok;
1281 }
1282
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001283 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001284 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001285 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001286 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001287 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001288 Lexer &Lex;
1289 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001290 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001291 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001292 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001293 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1294 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001295
Daniel Jasper8369aa52013-07-16 20:28:33 +00001296 void readRawToken(FormatToken &Tok) {
1297 Lex.LexFromRawLexer(Tok.Tok);
1298 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1299 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001300 // For formatting, treat unterminated string literals like normal string
1301 // literals.
1302 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1303 Tok.TokenText[0] == '"') {
1304 Tok.Tok.setKind(tok::string_literal);
1305 Tok.IsUnterminatedLiteral = true;
1306 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001307 }
1308};
1309
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001310static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1311 switch (Language) {
1312 case FormatStyle::LK_Cpp:
1313 return "C++";
1314 case FormatStyle::LK_JavaScript:
1315 return "JavaScript";
1316 default:
1317 return "Unknown";
1318 }
1319}
1320
Daniel Jasperf7935112012-12-03 18:12:45 +00001321class Formatter : public UnwrappedLineConsumer {
1322public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001323 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001324 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001325 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001326 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001327 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001328 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001329 DEBUG(llvm::dbgs() << "File encoding: "
1330 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1331 : "unknown")
1332 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001333 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1334 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001335 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001336
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001337 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001338 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001339 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001340
1341 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001342 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001343 assert(UnwrappedLines.rbegin()->empty());
1344 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1345 ++Run) {
1346 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1347 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1348 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1349 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1350 }
1351 tooling::Replacements RunResult =
1352 format(AnnotatedLines, StructuralError, Tokens);
1353 DEBUG({
1354 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1355 for (tooling::Replacements::iterator I = RunResult.begin(),
1356 E = RunResult.end();
1357 I != E; ++I) {
1358 llvm::dbgs() << I->toString() << "\n";
1359 }
1360 });
1361 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1362 delete AnnotatedLines[i];
1363 }
1364 Result.insert(RunResult.begin(), RunResult.end());
1365 Whitespaces.reset();
1366 }
1367 return Result;
1368 }
1369
1370 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1371 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001372 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001373 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001374 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001375 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001376 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001377 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001378 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001379 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001380 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001381
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001382 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001383 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1384 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001385 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001386 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001387 return Whitespaces.generateReplacements();
1388 }
1389
1390private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001391 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001392 // Returns \c true if at least one line between I and E or one of their
1393 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001394 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1395 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1396 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001397 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001398 while (I != E) {
1399 AnnotatedLine *Line = *I;
1400 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1401
1402 // If a line is part of a preprocessor directive, it needs to be formatted
1403 // if any token within the directive is affected.
1404 if (Line->InPPDirective) {
1405 FormatToken *Last = Line->Last;
1406 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1407 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1408 Last = (*PPEnd)->Last;
1409 ++PPEnd;
1410 }
1411
1412 if (affectsTokenRange(*Line->First, *Last,
1413 /*IncludeLeadingNewlines=*/false)) {
1414 SomeLineAffected = true;
1415 markAllAsAffected(I, PPEnd);
1416 }
1417 I = PPEnd;
1418 continue;
1419 }
1420
Daniel Jasper38c82402013-11-29 09:27:43 +00001421 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001422 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001423
Daniel Jasper38c82402013-11-29 09:27:43 +00001424 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001425 ++I;
1426 }
1427 return SomeLineAffected;
1428 }
1429
Daniel Jasper9c199562013-11-28 15:58:55 +00001430 // Determines whether 'Line' is affected by the SourceRanges given as input.
1431 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001432 bool nonPPLineAffected(AnnotatedLine *Line,
1433 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001434 bool SomeLineAffected = false;
1435 Line->ChildrenAffected =
1436 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1437 if (Line->ChildrenAffected)
1438 SomeLineAffected = true;
1439
1440 // Stores whether one of the line's tokens is directly affected.
1441 bool SomeTokenAffected = false;
1442 // Stores whether we need to look at the leading newlines of the next token
1443 // in order to determine whether it was affected.
1444 bool IncludeLeadingNewlines = false;
1445
1446 // Stores whether the first child line of any of this line's tokens is
1447 // affected.
1448 bool SomeFirstChildAffected = false;
1449
1450 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1451 // Determine whether 'Tok' was affected.
1452 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1453 SomeTokenAffected = true;
1454
1455 // Determine whether the first child of 'Tok' was affected.
1456 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1457 SomeFirstChildAffected = true;
1458
1459 IncludeLeadingNewlines = Tok->Children.empty();
1460 }
1461
1462 // Was this line moved, i.e. has it previously been on the same line as an
1463 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001464 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1465 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001466
Daniel Jasper38c82402013-11-29 09:27:43 +00001467 bool IsContinuedComment = Line->First->is(tok::comment) &&
1468 Line->First->Next == NULL &&
1469 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001470 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001471 PreviousLine->Last->is(tok::comment);
1472
1473 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1474 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001475 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001476 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001477 }
1478 return SomeLineAffected;
1479 }
1480
Daniel Jasper5500f612013-11-25 11:08:59 +00001481 // Marks all lines between I and E as well as all their children as affected.
1482 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1483 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1484 while (I != E) {
1485 (*I)->Affected = true;
1486 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1487 ++I;
1488 }
1489 }
1490
1491 // Returns true if the range from 'First' to 'Last' intersects with one of the
1492 // input ranges.
1493 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1494 bool IncludeLeadingNewlines) {
1495 SourceLocation Start = First.WhitespaceRange.getBegin();
1496 if (!IncludeLeadingNewlines)
1497 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001498 SourceLocation End = Last.getStartOfNonWhitespace();
1499 if (Last.TokenText.size() > 0)
1500 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001501 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1502 return affectsCharSourceRange(Range);
1503 }
1504
1505 // Returns true if one of the input ranges intersect the leading empty lines
1506 // before 'Tok'.
1507 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1508 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1509 Tok.WhitespaceRange.getBegin(),
1510 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1511 return affectsCharSourceRange(EmptyLineRange);
1512 }
1513
1514 // Returns true if 'Range' intersects with one of the input ranges.
1515 bool affectsCharSourceRange(const CharSourceRange &Range) {
1516 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1517 E = Ranges.end();
1518 I != E; ++I) {
1519 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1520 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1521 return true;
1522 }
1523 return false;
1524 }
1525
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001526 static bool inputUsesCRLF(StringRef Text) {
1527 return Text.count('\r') * 2 > Text.count('\n');
1528 }
1529
Manuel Klimek71814b42013-10-11 21:25:45 +00001530 void
1531 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001532 unsigned CountBoundToVariable = 0;
1533 unsigned CountBoundToType = 0;
1534 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001535 bool HasBinPackedFunction = false;
1536 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001537 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001538 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001539 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001540 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001541 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001542 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001543 bool SpacesBefore =
1544 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1545 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1546 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001547 if (SpacesBefore && !SpacesAfter)
1548 ++CountBoundToVariable;
1549 else if (!SpacesBefore && SpacesAfter)
1550 ++CountBoundToType;
1551 }
1552
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001553 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1554 if (Tok->is(tok::coloncolon) &&
1555 Tok->Previous->Type == TT_TemplateOpener)
1556 HasCpp03IncompatibleFormat = true;
1557 if (Tok->Type == TT_TemplateCloser &&
1558 Tok->Previous->Type == TT_TemplateCloser)
1559 HasCpp03IncompatibleFormat = true;
1560 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001561
1562 if (Tok->PackingKind == PPK_BinPacked)
1563 HasBinPackedFunction = true;
1564 if (Tok->PackingKind == PPK_OnePerLine)
1565 HasOnePerLineFunction = true;
1566
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001567 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001568 }
1569 }
1570 if (Style.DerivePointerBinding) {
1571 if (CountBoundToType > CountBoundToVariable)
1572 Style.PointerBindsToType = true;
1573 else if (CountBoundToType < CountBoundToVariable)
1574 Style.PointerBindsToType = false;
1575 }
1576 if (Style.Standard == FormatStyle::LS_Auto) {
1577 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1578 : FormatStyle::LS_Cpp03;
1579 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001580 BinPackInconclusiveFunctions =
1581 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001582 }
1583
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001584 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001585 assert(!UnwrappedLines.empty());
1586 UnwrappedLines.back().push_back(TheLine);
1587 }
1588
1589 virtual void finishRun() {
1590 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001591 }
1592
1593 FormatStyle Style;
1594 Lexer &Lex;
1595 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001596 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001597 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001598 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001599
1600 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001601 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001602};
1603
Craig Topperaf35e852013-06-30 22:29:28 +00001604} // end anonymous namespace
1605
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001606tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1607 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001608 std::vector<CharSourceRange> Ranges) {
1609 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001610 return formatter.format();
1611}
1612
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001613tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1614 std::vector<tooling::Range> Ranges,
1615 StringRef FileName) {
1616 FileManager Files((FileSystemOptions()));
1617 DiagnosticsEngine Diagnostics(
1618 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1619 new DiagnosticOptions);
1620 SourceManager SourceMgr(Diagnostics, Files);
1621 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1622 const clang::FileEntry *Entry =
1623 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1624 SourceMgr.overrideFileContents(Entry, Buf);
1625 FileID ID =
1626 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001627 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1628 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001629 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1630 std::vector<CharSourceRange> CharRanges;
1631 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1632 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1633 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1634 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1635 }
1636 return reformat(Style, Lex, SourceMgr, CharRanges);
1637}
1638
Alexander Kornienko1e808872013-06-28 12:51:24 +00001639LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001640 LangOptions LangOpts;
1641 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001642 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001643 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001644 LangOpts.Bool = 1;
1645 LangOpts.ObjC1 = 1;
1646 LangOpts.ObjC2 = 1;
1647 return LangOpts;
1648}
1649
Edwin Vaned544aa72013-09-30 13:31:48 +00001650const char *StyleOptionHelpDescription =
1651 "Coding style, currently supports:\n"
1652 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1653 "Use -style=file to load style configuration from\n"
1654 ".clang-format file located in one of the parent\n"
1655 "directories of the source file (or current\n"
1656 "directory for stdin).\n"
1657 "Use -style=\"{key: value, ...}\" to set specific\n"
1658 "parameters, e.g.:\n"
1659 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1660
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001661static void fillLanguageByFileName(StringRef FileName, FormatStyle *Style) {
1662 if (FileName.endswith_lower(".c") || FileName.endswith_lower(".h") ||
1663 FileName.endswith_lower(".cpp") || FileName.endswith_lower(".hpp") ||
1664 FileName.endswith_lower(".cc") || FileName.endswith_lower(".hh") ||
1665 FileName.endswith_lower(".cxx") || FileName.endswith_lower(".hxx") ||
1666 FileName.endswith_lower(".m") || FileName.endswith_lower(".mm")) {
1667 Style->Language = FormatStyle::LK_Cpp;
1668 }
1669 if (FileName.endswith_lower(".js")) {
1670 Style->Language = FormatStyle::LK_JavaScript;
1671 }
1672}
1673
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001674FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1675 StringRef FallbackStyle) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001676 FormatStyle Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001677 if (!getPredefinedStyle(FallbackStyle, &Style)) {
1678 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1679 << "\" using LLVM style\n";
1680 return getLLVMStyle();
1681 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001682 fillLanguageByFileName(FileName, &Style);
Edwin Vaned544aa72013-09-30 13:31:48 +00001683
1684 if (StyleName.startswith("{")) {
1685 // Parse YAML/JSON style from the command line.
1686 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001687 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1688 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001689 }
1690 return Style;
1691 }
1692
1693 if (!StyleName.equals_lower("file")) {
1694 if (!getPredefinedStyle(StyleName, &Style))
1695 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1696 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001697 fillLanguageByFileName(FileName, &Style);
Edwin Vaned544aa72013-09-30 13:31:48 +00001698 return Style;
1699 }
1700
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001701 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001702 SmallString<128> Path(FileName);
1703 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001704 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001705 Directory = llvm::sys::path::parent_path(Directory)) {
1706 if (!llvm::sys::fs::is_directory(Directory))
1707 continue;
1708 SmallString<128> ConfigFile(Directory);
1709
1710 llvm::sys::path::append(ConfigFile, ".clang-format");
1711 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1712 bool IsFile = false;
1713 // Ignore errors from is_regular_file: we only need to know if we can read
1714 // the file or not.
1715 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1716
1717 if (!IsFile) {
1718 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1719 ConfigFile = Directory;
1720 llvm::sys::path::append(ConfigFile, "_clang-format");
1721 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1722 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1723 }
1724
1725 if (IsFile) {
1726 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001727 if (llvm::error_code ec =
1728 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001729 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001730 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001731 }
1732 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001733 if (ec == llvm::errc::not_supported) {
1734 if (!UnsuitableConfigFiles.empty())
1735 UnsuitableConfigFiles.append(", ");
1736 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001737 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001738 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001739 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1740 << "\n";
1741 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001742 }
1743 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1744 return Style;
1745 }
1746 }
1747 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1748 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001749 if (!UnsuitableConfigFiles.empty()) {
1750 llvm::errs() << "Configuration file(s) do(es) not support "
1751 << getLanguageName(Style.Language) << ": "
1752 << UnsuitableConfigFiles << "\n";
1753 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001754 return Style;
1755}
1756
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001757} // namespace format
1758} // namespace clang