blob: ee9fe7625db609ee0dc625c4bd2def6eb9545cb5 [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.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000442 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000443 LineState State =
444 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000445 while (State.NextToken != NULL) {
446 bool Newline =
447 Indenter->mustBreak(State) ||
448 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
449 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
450 }
451 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000452
Daniel Jasperde0328a2013-08-16 11:20:30 +0000453private:
454 ContinuationIndenter *Indenter;
455};
456
Daniel Jasper56f8b432013-11-06 23:12:09 +0000457class LineJoiner {
458public:
459 LineJoiner(const FormatStyle &Style) : Style(Style) {}
460
461 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
462 unsigned
463 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000464 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000465 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
466 // We can never merge stuff if there are trailing line comments.
467 AnnotatedLine *TheLine = *I;
468 if (TheLine->Last->Type == TT_LineComment)
469 return 0;
470
471 if (Indent > Style.ColumnLimit)
472 return 0;
473
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000474 unsigned Limit =
475 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000476 // If we already exceed the column limit, we set 'Limit' to 0. The different
477 // tryMerge..() functions can then decide whether to still do merging.
478 Limit = TheLine->Last->TotalLength > Limit
479 ? 0
480 : Limit - TheLine->Last->TotalLength;
481
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000482 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000483 return 0;
484
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000485 if (TheLine->Last->Type == TT_FunctionLBrace) {
486 return Style.AllowShortFunctionsOnASingleLine
487 ? tryMergeSimpleBlock(I, E, Limit)
488 : 0;
489 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000490 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000491 return Style.BreakBeforeBraces == clang::format::FormatStyle::BS_Attach
492 ? tryMergeSimpleBlock(I, E, Limit)
493 : 0;
494 }
495 if (I[1]->First->Type == TT_FunctionLBrace &&
496 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
497 // Reduce the column limit by the number of spaces we need to insert
498 // around braces.
499 Limit = Limit > 3 ? Limit - 3 : 0;
500 unsigned MergedLines = 0;
501 if (Style.AllowShortFunctionsOnASingleLine) {
502 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
503 // If we managed to merge the block, count the function header, which is
504 // on a separate line.
505 if (MergedLines > 0)
506 ++MergedLines;
507 }
508 return MergedLines;
509 }
510 if (TheLine->First->is(tok::kw_if)) {
511 return Style.AllowShortIfStatementsOnASingleLine
512 ? tryMergeSimpleControlStatement(I, E, Limit)
513 : 0;
514 }
515 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
516 return Style.AllowShortLoopsOnASingleLine
517 ? tryMergeSimpleControlStatement(I, E, Limit)
518 : 0;
519 }
520 if (TheLine->InPPDirective &&
521 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000522 return tryMergeSimplePPDirective(I, E, Limit);
523 }
524 return 0;
525 }
526
527private:
528 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000529 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000530 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
531 unsigned Limit) {
532 if (Limit == 0)
533 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000534 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000535 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000536 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000537 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000538 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000539 return 0;
540 return 1;
541 }
542
543 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000544 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000545 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
546 if (Limit == 0)
547 return 0;
548 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000549 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000550 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000551 if (I[1]->InPPDirective != (*I)->InPPDirective ||
552 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000553 return 0;
554 AnnotatedLine &Line = **I;
555 if (Line.Last->isNot(tok::r_paren))
556 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000557 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000558 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000559 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000560 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000561 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000562 return 0;
563 // Only inline simple if's (no nested if or else).
564 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000565 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000566 return 0;
567 return 1;
568 }
569
570 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000571 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000572 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
573 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000574 // First, check that the current line allows merging. This is the case if
575 // we're not in a control flow statement and the last token is an opening
576 // brace.
577 AnnotatedLine &Line = **I;
578 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
579 tok::kw_else, tok::kw_try, tok::kw_catch,
580 tok::kw_for,
581 // This gets rid of all ObjC @ keywords and methods.
582 tok::at, tok::minus, tok::plus))
583 return 0;
584
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000585 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000586 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
587 (Tok->getNextNonComment() == NULL ||
588 Tok->getNextNonComment()->is(tok::semi))) {
589 // We merge empty blocks even if the line exceeds the column limit.
590 Tok->SpacesRequiredBefore = 0;
591 Tok->CanBreakBefore = true;
592 return 1;
593 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
594 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000595 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000596 return 0;
597
598 if (!nextTwoLinesFitInto(I, Limit))
599 return 0;
600
601 // Second, check that the next line does not contain any braces - if it
602 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000603 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000604 return 0;
605 do {
606 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
607 return 0;
608 Tok = Tok->Next;
609 } while (Tok != NULL);
610
611 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000612 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000613 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
614 Tok->MustBreakBefore)
615 return 0;
616
617 return 2;
618 }
619 return 0;
620 }
621
622 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
623 unsigned Limit) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000624 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000625 }
626
627 const FormatStyle &Style;
628};
629
Daniel Jasperf7935112012-12-03 18:12:45 +0000630class UnwrappedLineFormatter {
631public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000632 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000633 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000634 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000635 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
636 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000637
Daniel Jasper56f8b432013-11-06 23:12:09 +0000638 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000639 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000640 assert(!Lines.empty());
641 unsigned Penalty = 0;
642 std::vector<int> IndentForLevel;
643 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
644 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000645 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000646 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
647 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000648 I != E; ++I) {
649 const AnnotatedLine &TheLine = **I;
650 const FormatToken *FirstTok = TheLine.First;
651 int Offset = getIndentOffset(*FirstTok);
652
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000653 // Determine indent and try to merge multiple unwrapped lines.
654 while (IndentForLevel.size() <= TheLine.Level)
655 IndentForLevel.push_back(-1);
656 IndentForLevel.resize(TheLine.Level + 1);
657 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
658 if (static_cast<int>(Indent) + Offset >= 0)
659 Indent += Offset;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000660 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
661 if (!DryRun) {
662 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000663 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000664 }
665 }
666 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000667
Daniel Jasper9c199562013-11-28 15:58:55 +0000668 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
669 bool FixIndentation =
670 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000671 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000672 if (PreviousLine && PreviousLine->Affected && !DryRun) {
673 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000674 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
675 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
676 /*IndentLevel=*/0, /*Spaces=*/0,
677 /*TargetColumn=*/0);
678 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000679 } else if (TheLine.Type != LT_Invalid &&
680 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000681 if (FirstTok->WhitespaceRange.isValid()) {
682 if (!DryRun)
683 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
684 Indent, TheLine.InPPDirective);
685 } else {
686 Indent = LevelIndent = FirstTok->OriginalColumn;
687 }
688
689 // If everything fits on a single line, just put it there.
690 unsigned ColumnLimit = Style.ColumnLimit;
691 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000692 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000693 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
694 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
695 }
696
697 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
698 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
699 while (State.NextToken != NULL)
700 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
701 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000702 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000703 NoColumnLimitFormatter Formatter(Indenter);
704 if (!DryRun)
705 Formatter.format(Indent, &TheLine);
706 } else {
707 Penalty += format(TheLine, Indent, DryRun);
708 }
709
710 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000711 } else if (TheLine.ChildrenAffected) {
712 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000713 } else {
714 // Format the first token if necessary, and notify the WhitespaceManager
715 // about the unchanged whitespace.
716 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
717 if (Tok == TheLine.First &&
718 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
719 unsigned LevelIndent = Tok->OriginalColumn;
720 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000721 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000722 if ((PreviousLine && PreviousLine->Affected) ||
723 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000724 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
725 TheLine.InPPDirective);
726 } else {
727 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
728 }
729 }
730
731 if (static_cast<int>(LevelIndent) - Offset >= 0)
732 LevelIndent -= Offset;
733 if (Tok->isNot(tok::comment))
734 IndentForLevel[TheLine.Level] = LevelIndent;
735 } else if (!DryRun) {
736 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
737 }
738 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000739 }
740 if (!DryRun) {
741 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
742 Tok->Finalized = true;
743 }
744 }
745 PreviousLine = *I;
746 }
747 return Penalty;
748 }
749
750private:
751 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000752 ///
753 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000754 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
755 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000756 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000757
Daniel Jasperacc33662013-02-08 08:22:00 +0000758 // If the ObjC method declaration does not fit on a line, we should format
759 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000760 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000761 State.Stack.back().BreakBeforeParameter = true;
762
Daniel Jasper4b866272013-02-01 11:00:45 +0000763 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000764 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 }
766
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000767 /// \brief An edge in the solution space from \c Previous->State to \c State,
768 /// inserting a newline dependent on the \c NewLine.
769 struct StateNode {
770 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000771 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000772 LineState State;
773 bool NewLine;
774 StateNode *Previous;
775 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000776
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000777 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
778 ///
779 /// In case of equal penalties, we want to prefer states that were inserted
780 /// first. During state generation we make sure that we insert states first
781 /// that break the line as late as possible.
782 typedef std::pair<unsigned, unsigned> OrderedPenalty;
783
784 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
785 /// \c State has the given \c OrderedPenalty.
786 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
787
788 /// \brief The BFS queue type.
789 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
790 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000791
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000792 /// \brief Get the offset of the line relatively to the level.
793 ///
794 /// For example, 'public:' labels in classes are offset by 1 or 2
795 /// characters to the left from their level.
796 int getIndentOffset(const FormatToken &RootToken) {
797 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
798 return Style.AccessModifierOffset;
799 return 0;
800 }
801
802 /// \brief Add a new line and the required indent before the first Token
803 /// of the \c UnwrappedLine if there was no structural parsing error.
804 void formatFirstToken(FormatToken &RootToken,
805 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
806 unsigned Indent, bool InPPDirective) {
807 unsigned Newlines =
808 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
809 // Remove empty lines before "}" where applicable.
810 if (RootToken.is(tok::r_brace) &&
811 (!RootToken.Next ||
812 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
813 Newlines = std::min(Newlines, 1u);
814 if (Newlines == 0 && !RootToken.IsFirst)
815 Newlines = 1;
816
817 // Insert extra new line before access specifiers.
818 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
819 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
820 ++Newlines;
821
822 // Remove empty lines after access specifiers.
823 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
824 Newlines = std::min(1u, Newlines);
825
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000826 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
827 Indent, InPPDirective &&
828 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000829 }
830
831 /// \brief Get the indent of \p Level from \p IndentForLevel.
832 ///
833 /// \p IndentForLevel must contain the indent for the level \c l
834 /// at \p IndentForLevel[l], or a value < 0 if the indent for
835 /// that level is unknown.
836 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
837 if (IndentForLevel[Level] != -1)
838 return IndentForLevel[Level];
839 if (Level == 0)
840 return 0;
841 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
842 }
843
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000844 void join(AnnotatedLine &A, const AnnotatedLine &B) {
845 assert(!A.Last->Next);
846 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000847 if (B.Affected)
848 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000849 A.Last->Next = B.First;
850 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000851 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000852 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
853 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
854 Tok->TotalLength += LengthA;
855 A.Last = Tok;
856 }
857 }
858
859 unsigned getColumnLimit(bool InPPDirective) const {
860 // In preprocessor directives reserve two chars for trailing " \"
861 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
862 }
863
Daniel Jasper4b866272013-02-01 11:00:45 +0000864 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000865 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000866 /// This implements a variant of Dijkstra's algorithm on the graph that spans
867 /// the solution space (\c LineStates are the nodes). The algorithm tries to
868 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000869 /// to a state where all tokens are placed. Returns the penalty.
870 ///
871 /// If \p DryRun is \c false, directly applies the changes.
872 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000873 std::set<LineState> Seen;
874
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000875 // Increasing count of \c StateNode items we have created. This is used to
876 // create a deterministic order independent of the container.
877 unsigned Count = 0;
878 QueueType Queue;
879
Daniel Jasper4b866272013-02-01 11:00:45 +0000880 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000881 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
883 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
884 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000885
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000886 unsigned Penalty = 0;
887
Daniel Jasper4b866272013-02-01 11:00:45 +0000888 // While not empty, take first element and follow edges.
889 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000890 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000891 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000892 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000893 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000894 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000895 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000896 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000897
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000898 // Cut off the analysis of certain solutions if the analysis gets too
899 // complex. See description of IgnoreStackForComparison.
900 if (Count > 10000)
901 Node->State.IgnoreStackForComparison = true;
902
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000903 if (!Seen.insert(Node->State).second)
904 // State already examined with lower penalty.
905 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000906
Manuel Klimek71814b42013-10-11 21:25:45 +0000907 FormatDecision LastFormat = Node->State.NextToken->Decision;
908 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000909 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +0000910 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000911 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +0000912 }
913
Manuel Klimek71814b42013-10-11 21:25:45 +0000914 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000915 // We were unable to find a solution, do nothing.
916 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +0000917 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000918 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +0000919 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000920
Daniel Jasper4b866272013-02-01 11:00:45 +0000921 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000922 if (!DryRun)
923 reconstructPath(InitialState, Queue.top().second);
924
Alexander Kornienko49149672013-05-10 11:56:10 +0000925 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
926 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000927
928 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000929 }
930
931 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000932 std::deque<StateNode *> Path;
933 // We do not need a break before the initial token.
934 while (Current->Previous) {
935 Path.push_front(Current);
936 Current = Current->Previous;
937 }
938 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
939 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000940 unsigned Penalty = 0;
941 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
942 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
943
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000944 DEBUG({
945 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000946 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000947 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000948 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000949 }
950 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000951 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000952 }
953
Manuel Klimekaf491072013-02-13 10:54:19 +0000954 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000955 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000956 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000957 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000958 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000959 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000960 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000961 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000962 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000963 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000964
965 StateNode *Node = new (Allocator.Allocate())
966 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000967 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
968 return;
969
Daniel Jasperde0328a2013-08-16 11:20:30 +0000970 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000971
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000972 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
973 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +0000974 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000975
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000976 /// \brief If the \p State's next token is an r_brace closing a nested block,
977 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000978 ///
979 /// Returns \c true if all children could be placed successfully and adapts
980 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
981 /// creates changes using \c Whitespaces.
982 ///
983 /// The crucial idea here is that children always get formatted upon
984 /// encountering the closing brace right after the nested block. Now, if we
985 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
986 /// \c false), the entire block has to be kept on the same line (which is only
987 /// possible if it fits on the line, only contains a single statement, etc.
988 ///
989 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
990 /// break after the "{", format all lines with correct indentation and the put
991 /// the closing "}" on yet another new line.
992 ///
993 /// This enables us to keep the simple structure of the
994 /// \c UnwrappedLineFormatter, where we only have two options for each token:
995 /// break or don't break.
996 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
997 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000998 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000999 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1000 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1001 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001002 // The previous token does not open a block. Nothing to do. We don't
1003 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001004 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001005
1006 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001007 int AdditionalIndent = State.Stack.back().Indent -
1008 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001009 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1010 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001011 return true;
1012 }
1013
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001014 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001015 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001016 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001017
1018 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001019 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001020 return false;
1021
1022 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001023 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001024 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001025 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001026 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001027 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001028 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001029
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001030 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001031 return true;
1032 }
1033
Daniel Jasperde0328a2013-08-16 11:20:30 +00001034 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001035 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001037 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001038
1039 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040};
1041
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001042class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001043public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001044 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001045 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001046 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001047 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1048 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001049 Lex.SetKeepWhitespaceMode(true);
1050 }
1051
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001052 ArrayRef<FormatToken *> lex() {
1053 assert(Tokens.empty());
1054 do {
1055 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001056 tryMergePreviousTokens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001057 } while (Tokens.back()->Tok.isNot(tok::eof));
1058 return Tokens;
1059 }
1060
1061 IdentifierTable &getIdentTable() { return IdentTable; }
1062
1063private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001064 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001065 if (tryMerge_TMacro())
1066 return;
1067
1068 if (Style.Language == FormatStyle::LK_JavaScript) {
1069 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1070 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1071 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1072 tok::greaterequal };
1073 // FIXME: We probably need to change token type to mimic operator with the
1074 // correct priority.
1075 if (tryMergeTokens(JSIdentity))
1076 return;
1077 if (tryMergeTokens(JSNotIdentity))
1078 return;
1079 if (tryMergeTokens(JSShiftEqual))
1080 return;
1081 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001082 }
1083
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001084 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1085 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001086 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001087
1088 SmallVectorImpl<FormatToken *>::const_iterator First =
1089 Tokens.end() - Kinds.size();
1090 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001091 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001092 unsigned AddLength = 0;
1093 for (unsigned i = 1; i < Kinds.size(); ++i) {
1094 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1095 First[i]->WhitespaceRange.getEnd())
1096 return false;
1097 AddLength += First[i]->TokenText.size();
1098 }
1099 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1100 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1101 First[0]->TokenText.size() + AddLength);
1102 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001103 return true;
1104 }
1105
1106 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001107 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001108 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001109 FormatToken *Last = Tokens.back();
1110 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001111 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001112
1113 FormatToken *String = Tokens[Tokens.size() - 2];
1114 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001115 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001116
1117 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001118 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001119
1120 FormatToken *Macro = Tokens[Tokens.size() - 4];
1121 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001122 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001123
1124 const char *Start = Macro->TokenText.data();
1125 const char *End = Last->TokenText.data() + Last->TokenText.size();
1126 String->TokenText = StringRef(Start, End - Start);
1127 String->IsFirst = Macro->IsFirst;
1128 String->LastNewlineOffset = Macro->LastNewlineOffset;
1129 String->WhitespaceRange = Macro->WhitespaceRange;
1130 String->OriginalColumn = Macro->OriginalColumn;
1131 String->ColumnWidth = encoding::columnWidthWithTabs(
1132 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1133
1134 Tokens.pop_back();
1135 Tokens.pop_back();
1136 Tokens.pop_back();
1137 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001138 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001139 }
1140
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001141 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001142 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001143 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001144 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001145 Token Greater = FormatTok->Tok;
1146 FormatTok = new (Allocator.Allocate()) FormatToken;
1147 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001148 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001149 FormatTok->Tok.getLocation().getLocWithOffset(1);
1150 FormatTok->WhitespaceRange =
1151 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001152 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001153 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001154 GreaterStashed = false;
1155 return FormatTok;
1156 }
1157
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001158 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001159 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001160 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001161 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001162 FormatTok->IsFirst = IsFirstToken;
1163 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001164
1165 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001166 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001167 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001168 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1169 switch (FormatTok->TokenText[i]) {
1170 case '\n':
1171 ++FormatTok->NewlinesBefore;
1172 // FIXME: This is technically incorrect, as it could also
1173 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001174 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1175 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1176 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001177 FormatTok->HasUnescapedNewline = true;
1178 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1179 Column = 0;
1180 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001181 case '\r':
1182 case '\f':
1183 case '\v':
1184 Column = 0;
1185 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001186 case ' ':
1187 ++Column;
1188 break;
1189 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001190 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001191 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001192 case '\\':
1193 ++Column;
1194 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1195 FormatTok->TokenText[i + 1] != '\n'))
1196 FormatTok->Type = TT_ImplicitStringLiteral;
1197 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001198 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001199 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001200 ++Column;
1201 break;
1202 }
1203 }
1204
Daniel Jasper877615c2013-10-11 19:45:02 +00001205 if (FormatTok->Type == TT_ImplicitStringLiteral)
1206 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001207 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001208
Daniel Jasper8369aa52013-07-16 20:28:33 +00001209 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001210 }
Manuel Klimekef920692013-01-07 07:56:50 +00001211
Manuel Klimek1abf7892013-01-04 23:34:14 +00001212 // In case the token starts with escaped newlines, we want to
1213 // take them into account as whitespace - this pattern is quite frequent
1214 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001215 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001216 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1217 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001218 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001219 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001220 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001221 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001222 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001223
1224 FormatTok->WhitespaceRange = SourceRange(
1225 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1226
Manuel Klimek31c85922013-08-29 15:21:40 +00001227 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001229 TrailingWhitespace = 0;
1230 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001231 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001232 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001233 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001234 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001235 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001236 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001237 FormatTok->Tok.setIdentifierInfo(&Info);
1238 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001239 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001240 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001241 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001242 GreaterStashed = true;
1243 }
1244
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001245 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001246
Alexander Kornienko39856b72013-09-10 09:38:25 +00001247 StringRef Text = FormatTok->TokenText;
1248 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001249 if (FirstNewlinePos == StringRef::npos) {
1250 // FIXME: ColumnWidth actually depends on the start column, we need to
1251 // take this into account when the token is moved.
1252 FormatTok->ColumnWidth =
1253 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1254 Column += FormatTok->ColumnWidth;
1255 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001256 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001257 // FIXME: ColumnWidth actually depends on the start column, we need to
1258 // take this into account when the token is moved.
1259 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1260 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1261
Alexander Kornienko39856b72013-09-10 09:38:25 +00001262 // The last line of the token always starts in column 0.
1263 // Thus, the length can be precomputed even in the presence of tabs.
1264 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1265 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1266 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001267 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001268 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001269
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001270 return FormatTok;
1271 }
1272
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001273 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001274 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001276 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001277 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001278 Lexer &Lex;
1279 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001280 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001282 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001283 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1284 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001285
Daniel Jasper8369aa52013-07-16 20:28:33 +00001286 void readRawToken(FormatToken &Tok) {
1287 Lex.LexFromRawLexer(Tok.Tok);
1288 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1289 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001290 // For formatting, treat unterminated string literals like normal string
1291 // literals.
1292 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1293 Tok.TokenText[0] == '"') {
1294 Tok.Tok.setKind(tok::string_literal);
1295 Tok.IsUnterminatedLiteral = true;
1296 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001297 }
1298};
1299
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001300static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1301 switch (Language) {
1302 case FormatStyle::LK_Cpp:
1303 return "C++";
1304 case FormatStyle::LK_JavaScript:
1305 return "JavaScript";
1306 default:
1307 return "Unknown";
1308 }
1309}
1310
Daniel Jasperf7935112012-12-03 18:12:45 +00001311class Formatter : public UnwrappedLineConsumer {
1312public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001313 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001314 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001315 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001316 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001317 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001318 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001319 DEBUG(llvm::dbgs() << "File encoding: "
1320 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1321 : "unknown")
1322 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001323 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1324 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001325 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001326
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001327 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001328 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001329 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001330
1331 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001332 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001333 assert(UnwrappedLines.rbegin()->empty());
1334 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1335 ++Run) {
1336 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1337 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1338 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1339 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1340 }
1341 tooling::Replacements RunResult =
1342 format(AnnotatedLines, StructuralError, Tokens);
1343 DEBUG({
1344 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1345 for (tooling::Replacements::iterator I = RunResult.begin(),
1346 E = RunResult.end();
1347 I != E; ++I) {
1348 llvm::dbgs() << I->toString() << "\n";
1349 }
1350 });
1351 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1352 delete AnnotatedLines[i];
1353 }
1354 Result.insert(RunResult.begin(), RunResult.end());
1355 Whitespaces.reset();
1356 }
1357 return Result;
1358 }
1359
1360 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1361 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001362 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001363 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001364 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001365 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001366 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001367 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001368 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001369 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001370 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001371
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001372 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001373 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1374 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001375 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001376 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001377 return Whitespaces.generateReplacements();
1378 }
1379
1380private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001381 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001382 // Returns \c true if at least one line between I and E or one of their
1383 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001384 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1385 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1386 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001387 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001388 while (I != E) {
1389 AnnotatedLine *Line = *I;
1390 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1391
1392 // If a line is part of a preprocessor directive, it needs to be formatted
1393 // if any token within the directive is affected.
1394 if (Line->InPPDirective) {
1395 FormatToken *Last = Line->Last;
1396 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1397 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1398 Last = (*PPEnd)->Last;
1399 ++PPEnd;
1400 }
1401
1402 if (affectsTokenRange(*Line->First, *Last,
1403 /*IncludeLeadingNewlines=*/false)) {
1404 SomeLineAffected = true;
1405 markAllAsAffected(I, PPEnd);
1406 }
1407 I = PPEnd;
1408 continue;
1409 }
1410
Daniel Jasper38c82402013-11-29 09:27:43 +00001411 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001412 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001413
Daniel Jasper38c82402013-11-29 09:27:43 +00001414 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001415 ++I;
1416 }
1417 return SomeLineAffected;
1418 }
1419
Daniel Jasper9c199562013-11-28 15:58:55 +00001420 // Determines whether 'Line' is affected by the SourceRanges given as input.
1421 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001422 bool nonPPLineAffected(AnnotatedLine *Line,
1423 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001424 bool SomeLineAffected = false;
1425 Line->ChildrenAffected =
1426 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1427 if (Line->ChildrenAffected)
1428 SomeLineAffected = true;
1429
1430 // Stores whether one of the line's tokens is directly affected.
1431 bool SomeTokenAffected = false;
1432 // Stores whether we need to look at the leading newlines of the next token
1433 // in order to determine whether it was affected.
1434 bool IncludeLeadingNewlines = false;
1435
1436 // Stores whether the first child line of any of this line's tokens is
1437 // affected.
1438 bool SomeFirstChildAffected = false;
1439
1440 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1441 // Determine whether 'Tok' was affected.
1442 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1443 SomeTokenAffected = true;
1444
1445 // Determine whether the first child of 'Tok' was affected.
1446 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1447 SomeFirstChildAffected = true;
1448
1449 IncludeLeadingNewlines = Tok->Children.empty();
1450 }
1451
1452 // Was this line moved, i.e. has it previously been on the same line as an
1453 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001454 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1455 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001456
Daniel Jasper38c82402013-11-29 09:27:43 +00001457 bool IsContinuedComment = Line->First->is(tok::comment) &&
1458 Line->First->Next == NULL &&
1459 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001460 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001461 PreviousLine->Last->is(tok::comment);
1462
1463 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1464 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001465 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001466 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001467 }
1468 return SomeLineAffected;
1469 }
1470
Daniel Jasper5500f612013-11-25 11:08:59 +00001471 // Marks all lines between I and E as well as all their children as affected.
1472 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1473 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1474 while (I != E) {
1475 (*I)->Affected = true;
1476 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1477 ++I;
1478 }
1479 }
1480
1481 // Returns true if the range from 'First' to 'Last' intersects with one of the
1482 // input ranges.
1483 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1484 bool IncludeLeadingNewlines) {
1485 SourceLocation Start = First.WhitespaceRange.getBegin();
1486 if (!IncludeLeadingNewlines)
1487 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001488 SourceLocation End = Last.getStartOfNonWhitespace();
1489 if (Last.TokenText.size() > 0)
1490 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001491 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1492 return affectsCharSourceRange(Range);
1493 }
1494
1495 // Returns true if one of the input ranges intersect the leading empty lines
1496 // before 'Tok'.
1497 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1498 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1499 Tok.WhitespaceRange.getBegin(),
1500 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1501 return affectsCharSourceRange(EmptyLineRange);
1502 }
1503
1504 // Returns true if 'Range' intersects with one of the input ranges.
1505 bool affectsCharSourceRange(const CharSourceRange &Range) {
1506 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1507 E = Ranges.end();
1508 I != E; ++I) {
1509 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1510 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1511 return true;
1512 }
1513 return false;
1514 }
1515
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001516 static bool inputUsesCRLF(StringRef Text) {
1517 return Text.count('\r') * 2 > Text.count('\n');
1518 }
1519
Manuel Klimek71814b42013-10-11 21:25:45 +00001520 void
1521 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001522 unsigned CountBoundToVariable = 0;
1523 unsigned CountBoundToType = 0;
1524 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001525 bool HasBinPackedFunction = false;
1526 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001527 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001528 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001529 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001530 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001531 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001532 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001533 bool SpacesBefore =
1534 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1535 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1536 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001537 if (SpacesBefore && !SpacesAfter)
1538 ++CountBoundToVariable;
1539 else if (!SpacesBefore && SpacesAfter)
1540 ++CountBoundToType;
1541 }
1542
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001543 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1544 if (Tok->is(tok::coloncolon) &&
1545 Tok->Previous->Type == TT_TemplateOpener)
1546 HasCpp03IncompatibleFormat = true;
1547 if (Tok->Type == TT_TemplateCloser &&
1548 Tok->Previous->Type == TT_TemplateCloser)
1549 HasCpp03IncompatibleFormat = true;
1550 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001551
1552 if (Tok->PackingKind == PPK_BinPacked)
1553 HasBinPackedFunction = true;
1554 if (Tok->PackingKind == PPK_OnePerLine)
1555 HasOnePerLineFunction = true;
1556
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001557 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001558 }
1559 }
1560 if (Style.DerivePointerBinding) {
1561 if (CountBoundToType > CountBoundToVariable)
1562 Style.PointerBindsToType = true;
1563 else if (CountBoundToType < CountBoundToVariable)
1564 Style.PointerBindsToType = false;
1565 }
1566 if (Style.Standard == FormatStyle::LS_Auto) {
1567 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1568 : FormatStyle::LS_Cpp03;
1569 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001570 BinPackInconclusiveFunctions =
1571 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001572 }
1573
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001574 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001575 assert(!UnwrappedLines.empty());
1576 UnwrappedLines.back().push_back(TheLine);
1577 }
1578
1579 virtual void finishRun() {
1580 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001581 }
1582
1583 FormatStyle Style;
1584 Lexer &Lex;
1585 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001586 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001587 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001588 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001589
1590 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001591 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001592};
1593
Craig Topperaf35e852013-06-30 22:29:28 +00001594} // end anonymous namespace
1595
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001596tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1597 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001598 std::vector<CharSourceRange> Ranges) {
1599 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001600 return formatter.format();
1601}
1602
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001603tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1604 std::vector<tooling::Range> Ranges,
1605 StringRef FileName) {
1606 FileManager Files((FileSystemOptions()));
1607 DiagnosticsEngine Diagnostics(
1608 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1609 new DiagnosticOptions);
1610 SourceManager SourceMgr(Diagnostics, Files);
1611 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1612 const clang::FileEntry *Entry =
1613 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1614 SourceMgr.overrideFileContents(Entry, Buf);
1615 FileID ID =
1616 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001617 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1618 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001619 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1620 std::vector<CharSourceRange> CharRanges;
1621 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1622 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1623 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1624 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1625 }
1626 return reformat(Style, Lex, SourceMgr, CharRanges);
1627}
1628
Alexander Kornienko1e808872013-06-28 12:51:24 +00001629LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001630 LangOptions LangOpts;
1631 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001632 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001633 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001634 LangOpts.Bool = 1;
1635 LangOpts.ObjC1 = 1;
1636 LangOpts.ObjC2 = 1;
1637 return LangOpts;
1638}
1639
Edwin Vaned544aa72013-09-30 13:31:48 +00001640const char *StyleOptionHelpDescription =
1641 "Coding style, currently supports:\n"
1642 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1643 "Use -style=file to load style configuration from\n"
1644 ".clang-format file located in one of the parent\n"
1645 "directories of the source file (or current\n"
1646 "directory for stdin).\n"
1647 "Use -style=\"{key: value, ...}\" to set specific\n"
1648 "parameters, e.g.:\n"
1649 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1650
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001651static void fillLanguageByFileName(StringRef FileName, FormatStyle *Style) {
1652 if (FileName.endswith_lower(".c") || FileName.endswith_lower(".h") ||
1653 FileName.endswith_lower(".cpp") || FileName.endswith_lower(".hpp") ||
1654 FileName.endswith_lower(".cc") || FileName.endswith_lower(".hh") ||
1655 FileName.endswith_lower(".cxx") || FileName.endswith_lower(".hxx") ||
1656 FileName.endswith_lower(".m") || FileName.endswith_lower(".mm")) {
1657 Style->Language = FormatStyle::LK_Cpp;
1658 }
1659 if (FileName.endswith_lower(".js")) {
1660 Style->Language = FormatStyle::LK_JavaScript;
1661 }
1662}
1663
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001664FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1665 StringRef FallbackStyle) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001666 FormatStyle Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001667 if (!getPredefinedStyle(FallbackStyle, &Style)) {
1668 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1669 << "\" using LLVM style\n";
1670 return getLLVMStyle();
1671 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001672 fillLanguageByFileName(FileName, &Style);
Edwin Vaned544aa72013-09-30 13:31:48 +00001673
1674 if (StyleName.startswith("{")) {
1675 // Parse YAML/JSON style from the command line.
1676 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001677 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1678 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001679 }
1680 return Style;
1681 }
1682
1683 if (!StyleName.equals_lower("file")) {
1684 if (!getPredefinedStyle(StyleName, &Style))
1685 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1686 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001687 fillLanguageByFileName(FileName, &Style);
Edwin Vaned544aa72013-09-30 13:31:48 +00001688 return Style;
1689 }
1690
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001691 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001692 SmallString<128> Path(FileName);
1693 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001694 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001695 Directory = llvm::sys::path::parent_path(Directory)) {
1696 if (!llvm::sys::fs::is_directory(Directory))
1697 continue;
1698 SmallString<128> ConfigFile(Directory);
1699
1700 llvm::sys::path::append(ConfigFile, ".clang-format");
1701 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1702 bool IsFile = false;
1703 // Ignore errors from is_regular_file: we only need to know if we can read
1704 // the file or not.
1705 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1706
1707 if (!IsFile) {
1708 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1709 ConfigFile = Directory;
1710 llvm::sys::path::append(ConfigFile, "_clang-format");
1711 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1712 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1713 }
1714
1715 if (IsFile) {
1716 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001717 if (llvm::error_code ec =
1718 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001719 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001720 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001721 }
1722 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001723 if (ec == llvm::errc::not_supported) {
1724 if (!UnsuitableConfigFiles.empty())
1725 UnsuitableConfigFiles.append(", ");
1726 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001727 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001728 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001729 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1730 << "\n";
1731 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001732 }
1733 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1734 return Style;
1735 }
1736 }
1737 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1738 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001739 if (!UnsuitableConfigFiles.empty()) {
1740 llvm::errs() << "Configuration file(s) do(es) not support "
1741 << getLanguageName(Style.Language) << ": "
1742 << UnsuitableConfigFiles << "\n";
1743 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001744 return Style;
1745}
1746
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001747} // namespace format
1748} // namespace clang