blob: ebd12909e1c1ce8757d541c320e8e6f823cfbf92 [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
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000044 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000046 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 }
48};
49
50template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57 }
58};
59
60template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63 IO.enumCase(Value, "false", FormatStyle::UT_Never);
64 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65 IO.enumCase(Value, "true", FormatStyle::UT_Always);
66 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67 }
68};
69
Daniel Jasperd74cf402014-04-08 12:46:38 +000070template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72 IO.enumCase(Value, "None", FormatStyle::SFS_None);
73 IO.enumCase(Value, "false", FormatStyle::SFS_None);
74 IO.enumCase(Value, "All", FormatStyle::SFS_All);
75 IO.enumCase(Value, "true", FormatStyle::SFS_All);
76 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000077 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000078 }
79};
80
Daniel Jasperac043c92014-09-15 11:11:00 +000081template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
82 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
83 IO.enumCase(Value, "All", FormatStyle::BOS_All);
84 IO.enumCase(Value, "true", FormatStyle::BOS_All);
85 IO.enumCase(Value, "None", FormatStyle::BOS_None);
86 IO.enumCase(Value, "false", FormatStyle::BOS_None);
87 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
88 }
89};
90
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000091template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
92 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
93 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
94 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
95 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
96 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000097 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000098 }
99};
100
Alexander Kornienkod6538332013-05-07 15:32:14 +0000101template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000103 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 FormatStyle::NamespaceIndentationKind &Value) {
105 IO.enumCase(Value, "None", FormatStyle::NI_None);
106 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
107 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000108 }
109};
110
111template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000112struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113 static void enumeration(IO &IO,
114 FormatStyle::PointerAlignmentStyle &Value) {
115 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
116 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
117 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
118
Alp Toker958027b2014-07-14 19:42:55 +0000119 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000120 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
121 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
122 }
123};
124
125template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000126struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000127 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128 FormatStyle::SpaceBeforeParensOptions &Value) {
129 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000130 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000131 FormatStyle::SBPO_ControlStatements);
132 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000133
134 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000135 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
136 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000137 }
138};
139
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000140template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000141 static void mapping(IO &IO, FormatStyle &Style) {
142 // When reading, read the language first, we need it for getPredefinedStyle.
143 IO.mapOptional("Language", Style.Language);
144
Alexander Kornienko49149672013-05-10 11:56:10 +0000145 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000146 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000147 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000148 ArrayRef<StringRef> Styles(StylesArray);
149 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
150 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000151 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000152 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000153 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000154 IO.mapOptional("# BasedOnStyle", StyleName);
155 break;
156 }
157 }
158 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000159 StringRef BasedOnStyle;
160 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000161 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000162 FormatStyle::LanguageKind OldLanguage = Style.Language;
163 FormatStyle::LanguageKind Language =
164 ((FormatStyle *)IO.getContext())->Language;
165 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000166 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
167 return;
168 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000169 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000170 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000171 }
172
173 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000174 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000175 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000176 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000177 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000178 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
179 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000180 IO.mapOptional("AllowShortBlocksOnASingleLine",
181 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000182 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
183 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000184 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
185 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000186 IO.mapOptional("AllowShortLoopsOnASingleLine",
187 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000188 IO.mapOptional("AllowShortFunctionsOnASingleLine",
189 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000190 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
191 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000192 IO.mapOptional("AlwaysBreakTemplateDeclarations",
193 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000194 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
195 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000196 IO.mapOptional("BreakBeforeBinaryOperators",
197 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000198 IO.mapOptional("BreakBeforeTernaryOperators",
199 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000200 IO.mapOptional("BreakConstructorInitializersBeforeComma",
201 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000203 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000204 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
205 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
206 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000207 IO.mapOptional("ConstructorInitializerIndentWidth",
208 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000209 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000210 IO.mapOptional("ExperimentalAutoDetectBinPacking",
211 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000212 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000213 IO.mapOptional("IndentWrappedFunctionNames",
214 Style.IndentWrappedFunctionNames);
215 IO.mapOptional("IndentFunctionDeclarationAfterType",
216 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000217 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000218 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
219 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000220 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000221 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000222 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000223 IO.mapOptional("ObjCSpaceBeforeProtocolList",
224 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000225 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
226 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000227 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
228 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000229 IO.mapOptional("PenaltyBreakFirstLessLess",
230 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
232 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
233 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000234 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("SpacesBeforeTrailingComments",
236 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000237 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000238 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000239 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000240 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000241 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000242 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000243 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000244 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000245 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000246 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000247 IO.mapOptional("SpacesInCStyleCastParentheses",
248 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000249 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000250 IO.mapOptional("SpacesInContainerLiterals",
251 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000252 IO.mapOptional("SpaceBeforeAssignmentOperators",
253 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000254 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000255 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000256 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000257
258 // For backward compatibility.
259 if (!IO.outputting()) {
260 IO.mapOptional("SpaceAfterControlStatementKeyword",
261 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000262 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
263 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000264 }
265 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000266 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000267 }
268};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269
270// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000271// IO.getContext() should contain a pointer to the FormatStyle structure, that
272// will be used to get default values for missing keys.
273// If the first element has no Language specified, it will be treated as the
274// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000275template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000276 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
277 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000278 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000279 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000280 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000281 if (Index >= Seq.size()) {
282 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000283 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000284 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000285 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000286 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000287 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000288 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000289 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000290 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000291 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000292 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000293 }
294};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000295}
296}
297
Daniel Jasperf7935112012-12-03 18:12:45 +0000298namespace clang {
299namespace format {
300
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000301const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000302 static ParseErrorCategory C;
303 return C;
304}
305std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000306 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000307}
308
309const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
310 return "clang-format.parse_error";
311}
312
313std::string ParseErrorCategory::message(int EV) const {
314 switch (static_cast<ParseError>(EV)) {
315 case ParseError::Success:
316 return "Success";
317 case ParseError::Error:
318 return "Invalid argument";
319 case ParseError::Unsuitable:
320 return "Unsuitable";
321 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000322 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000323}
324
Daniel Jasperf7935112012-12-03 18:12:45 +0000325FormatStyle getLLVMStyle() {
326 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000327 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000329 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000330 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000331 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000332 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000333 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000334 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000335 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000336 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000337 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000338 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000339 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000340 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000341 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000342 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000343 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000344 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000345 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000346 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
347 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000348 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000349 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000350 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000351 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000352 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000353 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000354 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000355 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000356 LLVMStyle.ForEachMacros.push_back("foreach");
357 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
358 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000359 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000360 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000361 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000362 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000363 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000364 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000365 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000366 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000367 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000368 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000369 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000370 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000371 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000372 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000373 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000374 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000375 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000376 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000377 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000378 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000379 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000380 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000381 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000382
Daniel Jasper19a541e2013-12-19 16:45:34 +0000383 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000384 LLVMStyle.PenaltyBreakFirstLessLess = 120;
385 LLVMStyle.PenaltyBreakString = 1000;
386 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000387 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000388 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000389
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000390 LLVMStyle.DisableFormat = false;
391
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 return LLVMStyle;
393}
394
Nico Weber514ecc82014-02-02 20:50:45 +0000395FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000396 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000397 GoogleStyle.Language = Language;
398
Daniel Jasperf7935112012-12-03 18:12:45 +0000399 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000400 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000401 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000402 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000403 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000404 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000405 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000406 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000407 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000408 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000409 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000410 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000411 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000412 GoogleStyle.SpacesBeforeTrailingComments = 2;
413 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000414
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000415 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000416 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000417
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000418 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000419 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000420 GoogleStyle.AlignOperands = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000421 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000422 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
423 GoogleStyle.ColumnLimit = 100;
424 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000425 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000426 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000427 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000428 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000429 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000430 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Nico Weber514ecc82014-02-02 20:50:45 +0000431 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000432 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000433 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000434 }
435
Daniel Jasperf7935112012-12-03 18:12:45 +0000436 return GoogleStyle;
437}
438
Nico Weber514ecc82014-02-02 20:50:45 +0000439FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
440 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000441 if (Language == FormatStyle::LK_Java) {
442 ChromiumStyle.IndentWidth = 4;
443 ChromiumStyle.ContinuationIndentWidth = 8;
444 } else {
445 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
446 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
447 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
448 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
449 ChromiumStyle.BinPackParameters = false;
450 ChromiumStyle.DerivePointerAlignment = false;
451 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000452 return ChromiumStyle;
453}
454
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000455FormatStyle getMozillaStyle() {
456 FormatStyle MozillaStyle = getLLVMStyle();
457 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000458 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000459 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000460 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000461 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000462 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000463 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
464 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000465 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000466 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000467 return MozillaStyle;
468}
469
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000470FormatStyle getWebKitStyle() {
471 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000472 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000473 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000474 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000475 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000476 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000477 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000478 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000479 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000480 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000481 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000482 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000483 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000484 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000485 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000486 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000487 return Style;
488}
489
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000490FormatStyle getGNUStyle() {
491 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000492 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000493 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000494 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000495 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000496 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000497 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000498 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000499 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000500 return Style;
501}
502
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000503FormatStyle getNoStyle() {
504 FormatStyle NoStyle = getLLVMStyle();
505 NoStyle.DisableFormat = true;
506 return NoStyle;
507}
508
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000509bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
510 FormatStyle *Style) {
511 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000512 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000513 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000514 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000516 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000517 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000518 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000519 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000520 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000521 } else if (Name.equals_lower("gnu")) {
522 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000523 } else if (Name.equals_lower("none")) {
524 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000525 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000526 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000527 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000528
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000529 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000530 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000531}
532
Rafael Espindolac0809172014-06-12 14:02:15 +0000533std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000534 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000535 FormatStyle::LanguageKind Language = Style->Language;
536 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000537 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000538 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000539
540 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000541 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
543 // values for the fields, keys for which are missing from the configuration.
544 // Mapping also uses the context to get the language to find the correct
545 // base style.
546 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000547 Input >> Styles;
548 if (Input.error())
549 return Input.error();
550
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000551 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000552 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000553 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000554 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000555 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000556 for (unsigned j = 0; j < i; ++j) {
557 if (Styles[i].Language == Styles[j].Language) {
558 DEBUG(llvm::dbgs()
559 << "Duplicate languages in the config file on positions " << j
560 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000561 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000562 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000563 }
564 }
565 // Look for a suitable configuration starting from the end, so we can
566 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000567 // configuration (which can only be at slot 0) after it.
568 for (int i = Styles.size() - 1; i >= 0; --i) {
569 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000570 Styles[i].Language == FormatStyle::LK_None) {
571 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000572 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000573 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000574 }
575 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000576 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000577}
578
579std::string configurationAsText(const FormatStyle &Style) {
580 std::string Text;
581 llvm::raw_string_ostream Stream(Text);
582 llvm::yaml::Output Output(Stream);
583 // We use the same mapping method for input and output, so we need a non-const
584 // reference here.
585 FormatStyle NonConstStyle = Style;
586 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000587 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000588}
589
Craig Topperaf35e852013-06-30 22:29:28 +0000590namespace {
591
Nico Weber34272652014-11-13 16:25:37 +0000592bool startsExternCBlock(const AnnotatedLine &Line) {
593 const FormatToken *Next = Line.First->getNextNonComment();
594 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
595 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
596 NextNext && NextNext->is(tok::l_brace);
597}
598
Daniel Jasperde0328a2013-08-16 11:20:30 +0000599class NoColumnLimitFormatter {
600public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000601 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000602
603 /// \brief Formats the line starting at \p State, simply keeping all of the
604 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000605 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000606 LineState State =
607 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000608 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000609 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000610 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000611 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
612 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
613 }
614 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000615
Daniel Jasperde0328a2013-08-16 11:20:30 +0000616private:
617 ContinuationIndenter *Indenter;
618};
619
Daniel Jasper56f8b432013-11-06 23:12:09 +0000620class LineJoiner {
621public:
622 LineJoiner(const FormatStyle &Style) : Style(Style) {}
623
624 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
625 unsigned
626 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000627 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000628 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
629 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000630 const AnnotatedLine *TheLine = *I;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000631 if (TheLine->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000632 return 0;
633
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000634 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
635 return 0;
636
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000637 unsigned Limit =
638 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000639 // If we already exceed the column limit, we set 'Limit' to 0. The different
640 // tryMerge..() functions can then decide whether to still do merging.
641 Limit = TheLine->Last->TotalLength > Limit
642 ? 0
643 : Limit - TheLine->Last->TotalLength;
644
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000645 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000646 return 0;
647
Daniel Jasperd74cf402014-04-08 12:46:38 +0000648 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
649 // If necessary, change to something smarter.
650 bool MergeShortFunctions =
651 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper9e709352014-11-26 10:43:58 +0000652 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
653 I[1]->First->is(tok::r_brace)) ||
Daniel Jasperd74cf402014-04-08 12:46:38 +0000654 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
655 TheLine->Level != 0);
656
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000657 if (TheLine->Last->is(TT_FunctionLBrace) &&
Daniel Jasper234379f2013-12-24 13:31:25 +0000658 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000659 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000660 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000661 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000662 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000663 ? tryMergeSimpleBlock(I, E, Limit)
664 : 0;
665 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000666 if (I[1]->First->is(TT_FunctionLBrace) &&
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000667 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Daniel Jasper55aed672014-12-07 16:44:49 +0000668 if (I[1]->Last->is(TT_LineComment))
669 return 0;
670
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000671 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000672 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
673 return 0;
674 Limit -= 2;
675
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000676 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000677 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000678 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
679 // If we managed to merge the block, count the function header, which is
680 // on a separate line.
681 if (MergedLines > 0)
682 ++MergedLines;
683 }
684 return MergedLines;
685 }
686 if (TheLine->First->is(tok::kw_if)) {
687 return Style.AllowShortIfStatementsOnASingleLine
688 ? tryMergeSimpleControlStatement(I, E, Limit)
689 : 0;
690 }
691 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
692 return Style.AllowShortLoopsOnASingleLine
693 ? tryMergeSimpleControlStatement(I, E, Limit)
694 : 0;
695 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000696 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
697 return Style.AllowShortCaseLabelsOnASingleLine
698 ? tryMergeShortCaseLabels(I, E, Limit)
699 : 0;
700 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000701 if (TheLine->InPPDirective &&
702 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000703 return tryMergeSimplePPDirective(I, E, Limit);
704 }
705 return 0;
706 }
707
708private:
709 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000710 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000711 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
712 unsigned Limit) {
713 if (Limit == 0)
714 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000715 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000716 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000717 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000718 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000719 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000720 return 0;
721 return 1;
722 }
723
724 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000725 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000726 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
727 if (Limit == 0)
728 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000729 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
730 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000731 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000732 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000733 if (I[1]->InPPDirective != (*I)->InPPDirective ||
734 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000735 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000736 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 AnnotatedLine &Line = **I;
738 if (Line.Last->isNot(tok::r_paren))
739 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000740 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000741 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000742 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000743 tok::kw_while, TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000744 return 0;
745 // Only inline simple if's (no nested if or else).
746 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000747 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000748 return 0;
749 return 1;
750 }
751
Daniel Jasperb87899b2014-09-10 13:11:45 +0000752 unsigned tryMergeShortCaseLabels(
753 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
754 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
755 if (Limit == 0 || I + 1 == E ||
756 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
757 return 0;
758 unsigned NumStmts = 0;
759 unsigned Length = 0;
Daniel Jasper79f226e2014-11-23 21:45:03 +0000760 bool InPPDirective = I[0]->InPPDirective;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000761 for (; NumStmts < 3; ++NumStmts) {
762 if (I + 1 + NumStmts == E)
763 break;
764 const AnnotatedLine *Line = I[1 + NumStmts];
Daniel Jasper79f226e2014-11-23 21:45:03 +0000765 if (Line->InPPDirective != InPPDirective)
766 break;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000767 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
768 break;
769 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasperd081e882014-11-21 12:36:25 +0000770 tok::kw_while, tok::comment))
Daniel Jasperb87899b2014-09-10 13:11:45 +0000771 return 0;
772 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
773 }
774 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
775 return 0;
776 return NumStmts;
777 }
778
Daniel Jasper56f8b432013-11-06 23:12:09 +0000779 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000780 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000781 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
782 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000783 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000784
785 // Don't merge ObjC @ keywords and methods.
Daniel Jasper9e709352014-11-26 10:43:58 +0000786 if (Style.Language != FormatStyle::LK_Java &&
787 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000788 return 0;
789
Daniel Jasper17605d32014-05-14 09:33:35 +0000790 // Check that the current line allows merging. This depends on whether we
791 // are in a control flow statements as well as several style flags.
792 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
793 return 0;
794 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
795 tok::kw_catch, tok::kw_for, tok::r_brace)) {
796 if (!Style.AllowShortBlocksOnASingleLine)
797 return 0;
798 if (!Style.AllowShortIfStatementsOnASingleLine &&
799 Line.First->is(tok::kw_if))
800 return 0;
801 if (!Style.AllowShortLoopsOnASingleLine &&
802 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
803 return 0;
804 // FIXME: Consider an option to allow short exception handling clauses on
805 // a single line.
806 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
807 return 0;
808 }
809
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000810 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000811 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000812 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000813 Tok->getNextNonComment()->is(tok::semi))) {
814 // We merge empty blocks even if the line exceeds the column limit.
815 Tok->SpacesRequiredBefore = 0;
816 Tok->CanBreakBefore = true;
817 return 1;
Nico Weber34272652014-11-13 16:25:37 +0000818 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
819 !startsExternCBlock(Line)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000820 // We don't merge short records.
821 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
822 return 0;
823
Daniel Jasper56f8b432013-11-06 23:12:09 +0000824 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000825 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000826 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000827 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000828
829 if (!nextTwoLinesFitInto(I, Limit))
830 return 0;
831
832 // Second, check that the next line does not contain any braces - if it
833 // does, readability declines when putting it into a single line.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000834 if (I[1]->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000835 return 0;
836 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000837 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000838 return 0;
839 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000840 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000841
Daniel Jasper79dffb42014-05-07 09:48:30 +0000842 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000843 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000844 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000845 return 0;
846
847 return 2;
848 }
849 return 0;
850 }
851
Daniel Jasper64989962014-02-07 13:45:27 +0000852 /// Returns the modified column limit for \p I if it is inside a macro and
853 /// needs a trailing '\'.
854 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000855 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000856 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
857 unsigned Limit) {
858 if (I[0]->InPPDirective && I + 1 != E &&
859 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
860 return Limit < 2 ? 0 : Limit - 2;
861 }
862 return Limit;
863 }
864
Daniel Jasper56f8b432013-11-06 23:12:09 +0000865 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
866 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000867 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
868 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000869 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000870 }
871
Daniel Jasper234379f2013-12-24 13:31:25 +0000872 bool containsMustBreak(const AnnotatedLine *Line) {
873 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
874 if (Tok->MustBreakBefore)
875 return true;
876 }
877 return false;
878 }
879
Daniel Jasper56f8b432013-11-06 23:12:09 +0000880 const FormatStyle &Style;
881};
882
Daniel Jasperf7935112012-12-03 18:12:45 +0000883class UnwrappedLineFormatter {
884public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000885 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000886 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000887 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000888 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
889 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000890
Daniel Jasper56f8b432013-11-06 23:12:09 +0000891 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000892 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000893 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000894 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
895 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000896 auto CacheIt = PenaltyCache.find(CacheKey);
897 if (DryRun && CacheIt != PenaltyCache.end())
898 return CacheIt->second;
899
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000900 assert(!Lines.empty());
901 unsigned Penalty = 0;
902 std::vector<int> IndentForLevel;
903 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
904 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000905 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000906 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
907 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000908 I != E; ++I) {
909 const AnnotatedLine &TheLine = **I;
910 const FormatToken *FirstTok = TheLine.First;
911 int Offset = getIndentOffset(*FirstTok);
912
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000913 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000914 unsigned Indent;
915 if (TheLine.InPPDirective) {
916 Indent = TheLine.Level * Style.IndentWidth;
917 } else {
918 while (IndentForLevel.size() <= TheLine.Level)
919 IndentForLevel.push_back(-1);
920 IndentForLevel.resize(TheLine.Level + 1);
921 Indent = getIndent(IndentForLevel, TheLine.Level);
922 }
923 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000924 if (static_cast<int>(Indent) + Offset >= 0)
925 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000926
927 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000928 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000929 if (MergedLines > 0 && Style.ColumnLimit == 0) {
930 // Disallow line merging if there is a break at the start of one of the
931 // input lines.
932 for (unsigned i = 0; i < MergedLines; ++i) {
933 if (I[i + 1]->First->NewlinesBefore > 0)
934 MergedLines = 0;
935 }
936 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000937 if (!DryRun) {
938 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000939 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000940 }
941 }
942 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000943
Daniel Jasper9c199562013-11-28 15:58:55 +0000944 bool FixIndentation =
945 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000946 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000947 if (PreviousLine && PreviousLine->Affected && !DryRun) {
948 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000949 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
950 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
951 /*IndentLevel=*/0, /*Spaces=*/0,
952 /*TargetColumn=*/0);
953 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000954 } else if (TheLine.Type != LT_Invalid &&
955 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000956 if (FirstTok->WhitespaceRange.isValid()) {
957 if (!DryRun)
958 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
959 Indent, TheLine.InPPDirective);
960 } else {
961 Indent = LevelIndent = FirstTok->OriginalColumn;
962 }
963
964 // If everything fits on a single line, just put it there.
965 unsigned ColumnLimit = Style.ColumnLimit;
966 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000967 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000968 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
969 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
970 }
971
Daniel Jasper616de8642014-11-23 16:46:28 +0000972 if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
973 TheLine.Type == LT_ImportStatement) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000974 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000975 while (State.NextToken) {
976 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000977 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000978 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000979 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000980 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000981 NoColumnLimitFormatter Formatter(Indenter);
982 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000983 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000984 } else {
985 Penalty += format(TheLine, Indent, DryRun);
986 }
987
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000988 if (!TheLine.InPPDirective)
989 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000990 } else if (TheLine.ChildrenAffected) {
991 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000992 } else {
993 // Format the first token if necessary, and notify the WhitespaceManager
994 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000995 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000996 if (Tok == TheLine.First &&
997 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
998 unsigned LevelIndent = Tok->OriginalColumn;
999 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001000 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +00001001 if ((PreviousLine && PreviousLine->Affected) ||
1002 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001003 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
1004 TheLine.InPPDirective);
1005 } else {
1006 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1007 }
1008 }
1009
1010 if (static_cast<int>(LevelIndent) - Offset >= 0)
1011 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +00001012 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001013 IndentForLevel[TheLine.Level] = LevelIndent;
1014 } else if (!DryRun) {
1015 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1016 }
1017 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001018 }
1019 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +00001020 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001021 Tok->Finalized = true;
1022 }
1023 }
1024 PreviousLine = *I;
1025 }
Daniel Jasperc359ad02014-04-15 08:13:47 +00001026 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001027 return Penalty;
1028 }
1029
1030private:
1031 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001032 ///
1033 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001034 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1035 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001036 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001037
Daniel Jasperacc33662013-02-08 08:22:00 +00001038 // If the ObjC method declaration does not fit on a line, we should format
1039 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001040 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001041 State.Stack.back().BreakBeforeParameter = true;
1042
Daniel Jasper4b866272013-02-01 11:00:45 +00001043 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001044 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001045 }
1046
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001047 /// \brief An edge in the solution space from \c Previous->State to \c State,
1048 /// inserting a newline dependent on the \c NewLine.
1049 struct StateNode {
1050 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001051 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001052 LineState State;
1053 bool NewLine;
1054 StateNode *Previous;
1055 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001056
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001057 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1058 ///
1059 /// In case of equal penalties, we want to prefer states that were inserted
1060 /// first. During state generation we make sure that we insert states first
1061 /// that break the line as late as possible.
1062 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1063
1064 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1065 /// \c State has the given \c OrderedPenalty.
1066 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1067
1068 /// \brief The BFS queue type.
1069 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1070 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001071
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001072 /// \brief Get the offset of the line relatively to the level.
1073 ///
1074 /// For example, 'public:' labels in classes are offset by 1 or 2
1075 /// characters to the left from their level.
1076 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001077 if (Style.Language == FormatStyle::LK_Java)
1078 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001079 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1080 return Style.AccessModifierOffset;
1081 return 0;
1082 }
1083
1084 /// \brief Add a new line and the required indent before the first Token
1085 /// of the \c UnwrappedLine if there was no structural parsing error.
1086 void formatFirstToken(FormatToken &RootToken,
1087 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1088 unsigned Indent, bool InPPDirective) {
1089 unsigned Newlines =
1090 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1091 // Remove empty lines before "}" where applicable.
1092 if (RootToken.is(tok::r_brace) &&
1093 (!RootToken.Next ||
1094 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1095 Newlines = std::min(Newlines, 1u);
1096 if (Newlines == 0 && !RootToken.IsFirst)
1097 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001098 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1099 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001100
Daniel Jasper11164bd2014-03-21 12:58:53 +00001101 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001102 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1103 PreviousLine->Last->is(tok::l_brace) &&
Nico Weber34272652014-11-13 16:25:37 +00001104 PreviousLine->First->isNot(tok::kw_namespace) &&
1105 !startsExternCBlock(*PreviousLine))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001106 Newlines = 1;
1107
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001108 // Insert extra new line before access specifiers.
1109 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1110 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1111 ++Newlines;
1112
1113 // Remove empty lines after access specifiers.
1114 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1115 Newlines = std::min(1u, Newlines);
1116
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001117 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1118 Indent, InPPDirective &&
1119 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001120 }
1121
1122 /// \brief Get the indent of \p Level from \p IndentForLevel.
1123 ///
1124 /// \p IndentForLevel must contain the indent for the level \c l
1125 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1126 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001127 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001128 if (IndentForLevel[Level] != -1)
1129 return IndentForLevel[Level];
1130 if (Level == 0)
1131 return 0;
1132 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1133 }
1134
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001135 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1136 assert(!A.Last->Next);
1137 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001138 if (B.Affected)
1139 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001140 A.Last->Next = B.First;
1141 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001142 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001143 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1144 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1145 Tok->TotalLength += LengthA;
1146 A.Last = Tok;
1147 }
1148 }
1149
1150 unsigned getColumnLimit(bool InPPDirective) const {
1151 // In preprocessor directives reserve two chars for trailing " \"
1152 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1153 }
1154
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001155 struct CompareLineStatePointers {
1156 bool operator()(LineState *obj1, LineState *obj2) const {
1157 return *obj1 < *obj2;
1158 }
1159 };
1160
Daniel Jasper4b866272013-02-01 11:00:45 +00001161 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001162 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001163 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1164 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1165 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001166 /// to a state where all tokens are placed. Returns the penalty.
1167 ///
1168 /// If \p DryRun is \c false, directly applies the changes.
1169 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001170 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001171
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001172 // Increasing count of \c StateNode items we have created. This is used to
1173 // create a deterministic order independent of the container.
1174 unsigned Count = 0;
1175 QueueType Queue;
1176
Daniel Jasper4b866272013-02-01 11:00:45 +00001177 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001178 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001179 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001180 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1181 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001182
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001183 unsigned Penalty = 0;
1184
Daniel Jasper4b866272013-02-01 11:00:45 +00001185 // While not empty, take first element and follow edges.
1186 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001187 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001188 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001189 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001190 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001191 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001192 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001193 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001194
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001195 // Cut off the analysis of certain solutions if the analysis gets too
1196 // complex. See description of IgnoreStackForComparison.
1197 if (Count > 10000)
1198 Node->State.IgnoreStackForComparison = true;
1199
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001200 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001201 // State already examined with lower penalty.
1202 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001203
Manuel Klimek71814b42013-10-11 21:25:45 +00001204 FormatDecision LastFormat = Node->State.NextToken->Decision;
1205 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001206 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001207 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001208 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001209 }
1210
Manuel Klimek71814b42013-10-11 21:25:45 +00001211 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001212 // We were unable to find a solution, do nothing.
1213 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001214 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001215 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001216 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001217
Daniel Jasper4b866272013-02-01 11:00:45 +00001218 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001219 if (!DryRun)
1220 reconstructPath(InitialState, Queue.top().second);
1221
Alexander Kornienko49149672013-05-10 11:56:10 +00001222 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1223 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001224
1225 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001226 }
1227
1228 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001229 std::deque<StateNode *> Path;
1230 // We do not need a break before the initial token.
1231 while (Current->Previous) {
1232 Path.push_front(Current);
1233 Current = Current->Previous;
1234 }
1235 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1236 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001237 unsigned Penalty = 0;
1238 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1239 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1240
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001241 DEBUG({
1242 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001243 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001244 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001245 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001246 }
1247 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001248 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001249 }
1250
Manuel Klimekaf491072013-02-13 10:54:19 +00001251 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001252 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001253 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001254 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001255 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001256 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001257 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001258 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001259 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001260 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001261
1262 StateNode *Node = new (Allocator.Allocate())
1263 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001264 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1265 return;
1266
Daniel Jasperde0328a2013-08-16 11:20:30 +00001267 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001268
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001269 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1270 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001271 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001272
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001273 /// \brief If the \p State's next token is an r_brace closing a nested block,
1274 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001275 ///
1276 /// Returns \c true if all children could be placed successfully and adapts
1277 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1278 /// creates changes using \c Whitespaces.
1279 ///
1280 /// The crucial idea here is that children always get formatted upon
1281 /// encountering the closing brace right after the nested block. Now, if we
1282 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1283 /// \c false), the entire block has to be kept on the same line (which is only
1284 /// possible if it fits on the line, only contains a single statement, etc.
1285 ///
1286 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1287 /// break after the "{", format all lines with correct indentation and the put
1288 /// the closing "}" on yet another new line.
1289 ///
1290 /// This enables us to keep the simple structure of the
1291 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1292 /// break or don't break.
1293 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1294 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001295 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001296 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1297 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1298 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001299 // The previous token does not open a block. Nothing to do. We don't
1300 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001301 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001302
1303 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001304 int AdditionalIndent =
1305 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001306 if (State.Stack.size() < 2 ||
Daniel Jasper4b444492014-11-21 13:38:53 +00001307 !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
Daniel Jasperb16b9692014-05-21 12:51:23 +00001308 AdditionalIndent = State.Stack.back().Indent -
1309 Previous.Children[0]->Level * Style.IndentWidth;
1310 }
1311
Daniel Jasper9c199562013-11-28 15:58:55 +00001312 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1313 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001314 return true;
1315 }
1316
Daniel Jasper56346192014-10-27 16:31:46 +00001317 if (Previous.Children[0]->First->MustBreakBefore)
1318 return false;
1319
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001320 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001321 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001322 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001323
Daniel Jasper21397a32014-04-09 12:21:48 +00001324 // Cannot merge into one line if this line ends on a comment.
1325 if (Previous.is(tok::comment))
1326 return false;
1327
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001328 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001329 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001330 return false;
1331
Daniel Jasper98583d52014-04-15 08:28:06 +00001332 // If the child line exceeds the column limit, we wouldn't want to merge it.
1333 // We add +2 for the trailing " }".
1334 if (Style.ColumnLimit > 0 &&
1335 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1336 Style.ColumnLimit)
1337 return false;
1338
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001339 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001340 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001341 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001342 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001343 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001344 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001345 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001346
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001347 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001348 return true;
1349 }
1350
Daniel Jasperde0328a2013-08-16 11:20:30 +00001351 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001352 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001353 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001354 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001355
1356 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001357
1358 // Cache to store the penalty of formatting a vector of AnnotatedLines
1359 // starting from a specific additional offset. Improves performance if there
1360 // are many nested blocks.
1361 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1362 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001363};
1364
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001365class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001366public:
Daniel Jasper23376252014-09-09 14:37:39 +00001367 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001368 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001369 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001370 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1371 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1372 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1373 FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +00001374 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1375 getFormattingLangOpts(Style)));
1376 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001377
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001378 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001379 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1380 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001381 }
1382
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001383 ArrayRef<FormatToken *> lex() {
1384 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001385 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001386 do {
1387 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001388 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001389 if (Tokens.back()->NewlinesBefore > 0)
1390 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001391 } while (Tokens.back()->Tok.isNot(tok::eof));
1392 return Tokens;
1393 }
1394
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001395 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001396
1397private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001398 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001399 if (tryMerge_TMacro())
1400 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001401 if (tryMergeConflictMarkers())
1402 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001403
1404 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001405 if (tryMergeJSRegexLiteral())
1406 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001407 if (tryMergeEscapeSequence())
1408 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001409
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001410 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1411 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1412 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1413 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001414 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001415 // FIXME: We probably need to change token type to mimic operator with the
1416 // correct priority.
1417 if (tryMergeTokens(JSIdentity))
1418 return;
1419 if (tryMergeTokens(JSNotIdentity))
1420 return;
1421 if (tryMergeTokens(JSShiftEqual))
1422 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001423 if (tryMergeTokens(JSRightArrow))
1424 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001425 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001426 }
1427
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001428 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1429 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001430 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001431
1432 SmallVectorImpl<FormatToken *>::const_iterator First =
1433 Tokens.end() - Kinds.size();
1434 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001435 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001436 unsigned AddLength = 0;
1437 for (unsigned i = 1; i < Kinds.size(); ++i) {
1438 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1439 First[i]->WhitespaceRange.getEnd())
1440 return false;
1441 AddLength += First[i]->TokenText.size();
1442 }
1443 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1444 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1445 First[0]->TokenText.size() + AddLength);
1446 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001447 return true;
1448 }
1449
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001450 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001451 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001452 bool tryMergeEscapeSequence() {
1453 if (Tokens.size() < 2)
1454 return false;
1455 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +00001456 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001457 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001458 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001459 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001460 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1461 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001462 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +00001463 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001464 return true;
1465 }
1466
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001467 // Try to determine whether the current token ends a JavaScript regex literal.
1468 // We heuristically assume that this is a regex literal if we find two
1469 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001470 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1471 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001472 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001473 if (Tokens.size() < 2)
1474 return false;
1475 // If a regex literal ends in "\//", this gets represented by an unknown
1476 // token "\" and a comment.
1477 bool MightEndWithEscapedSlash =
1478 Tokens.back()->is(tok::comment) &&
1479 Tokens.back()->TokenText.startswith("//") &&
1480 Tokens[Tokens.size() - 2]->TokenText == "\\";
1481 if (!MightEndWithEscapedSlash &&
1482 (Tokens.back()->isNot(tok::slash) ||
1483 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1484 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001485 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001486 unsigned TokenCount = 0;
1487 unsigned LastColumn = Tokens.back()->OriginalColumn;
1488 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1489 ++TokenCount;
1490 if (I[0]->is(tok::slash) && I + 1 != E &&
1491 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1492 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1493 tok::question, tok::kw_return) ||
1494 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001495 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +00001496 // This regex literal ends in '\//'. Skip past the '//' of the last
1497 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +00001498 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1499 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +00001500 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001501 Tokens.resize(Tokens.size() - TokenCount);
1502 Tokens.back()->Tok.setKind(tok::unknown);
1503 Tokens.back()->Type = TT_RegexLiteral;
1504 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1505 return true;
1506 }
1507
1508 // There can't be a newline inside a regex literal.
1509 if (I[0]->NewlinesBefore > 0)
1510 return false;
1511 }
1512 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001513 }
1514
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001515 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001516 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001517 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001518 FormatToken *Last = Tokens.back();
1519 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001520 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001521
1522 FormatToken *String = Tokens[Tokens.size() - 2];
1523 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001524 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001525
1526 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001527 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001528
1529 FormatToken *Macro = Tokens[Tokens.size() - 4];
1530 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001531 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001532
1533 const char *Start = Macro->TokenText.data();
1534 const char *End = Last->TokenText.data() + Last->TokenText.size();
1535 String->TokenText = StringRef(Start, End - Start);
1536 String->IsFirst = Macro->IsFirst;
1537 String->LastNewlineOffset = Macro->LastNewlineOffset;
1538 String->WhitespaceRange = Macro->WhitespaceRange;
1539 String->OriginalColumn = Macro->OriginalColumn;
1540 String->ColumnWidth = encoding::columnWidthWithTabs(
1541 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1542
1543 Tokens.pop_back();
1544 Tokens.pop_back();
1545 Tokens.pop_back();
1546 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001547 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001548 }
1549
Manuel Klimek68b03042014-04-14 09:14:11 +00001550 bool tryMergeConflictMarkers() {
1551 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1552 return false;
1553
1554 // Conflict lines look like:
1555 // <marker> <text from the vcs>
1556 // For example:
1557 // >>>>>>> /file/in/file/system at revision 1234
1558 //
1559 // We merge all tokens in a line that starts with a conflict marker
1560 // into a single token with a special token type that the unwrapped line
1561 // parser will use to correctly rebuild the underlying code.
1562
1563 FileID ID;
1564 // Get the position of the first token in the line.
1565 unsigned FirstInLineOffset;
1566 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1567 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1568 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1569 // Calculate the offset of the start of the current line.
1570 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1571 if (LineOffset == StringRef::npos) {
1572 LineOffset = 0;
1573 } else {
1574 ++LineOffset;
1575 }
1576
1577 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1578 StringRef LineStart;
1579 if (FirstSpace == StringRef::npos) {
1580 LineStart = Buffer.substr(LineOffset);
1581 } else {
1582 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1583 }
1584
1585 TokenType Type = TT_Unknown;
1586 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1587 Type = TT_ConflictStart;
1588 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1589 LineStart == "====") {
1590 Type = TT_ConflictAlternative;
1591 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1592 Type = TT_ConflictEnd;
1593 }
1594
1595 if (Type != TT_Unknown) {
1596 FormatToken *Next = Tokens.back();
1597
1598 Tokens.resize(FirstInLineIndex + 1);
1599 // We do not need to build a complete token here, as we will skip it
1600 // during parsing anyway (as we must not touch whitespace around conflict
1601 // markers).
1602 Tokens.back()->Type = Type;
1603 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1604
1605 Tokens.push_back(Next);
1606 return true;
1607 }
1608
1609 return false;
1610 }
1611
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001612 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001613 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001614 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001615 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001616 Token Greater = FormatTok->Tok;
1617 FormatTok = new (Allocator.Allocate()) FormatToken;
1618 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001619 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001620 FormatTok->Tok.getLocation().getLocWithOffset(1);
1621 FormatTok->WhitespaceRange =
1622 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001623 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001624 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001625 GreaterStashed = false;
1626 return FormatTok;
1627 }
1628
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001629 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001630 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001631 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001632 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001633 FormatTok->IsFirst = IsFirstToken;
1634 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001635
1636 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001637 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001638 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001639 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1640 switch (FormatTok->TokenText[i]) {
1641 case '\n':
1642 ++FormatTok->NewlinesBefore;
1643 // FIXME: This is technically incorrect, as it could also
1644 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001645 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1646 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1647 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001648 FormatTok->HasUnescapedNewline = true;
1649 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1650 Column = 0;
1651 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001652 case '\r':
1653 case '\f':
1654 case '\v':
1655 Column = 0;
1656 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001657 case ' ':
1658 ++Column;
1659 break;
1660 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001661 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001662 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001663 case '\\':
1664 ++Column;
1665 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1666 FormatTok->TokenText[i + 1] != '\n'))
1667 FormatTok->Type = TT_ImplicitStringLiteral;
1668 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001669 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001670 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001671 ++Column;
1672 break;
1673 }
1674 }
1675
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001676 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001677 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001678 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001679
Daniel Jasper8369aa52013-07-16 20:28:33 +00001680 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001681 }
Manuel Klimekef920692013-01-07 07:56:50 +00001682
Manuel Klimek1abf7892013-01-04 23:34:14 +00001683 // In case the token starts with escaped newlines, we want to
1684 // take them into account as whitespace - this pattern is quite frequent
1685 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001686 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001687 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1688 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001689 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001690 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001691 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001692 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001693 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001694
1695 FormatTok->WhitespaceRange = SourceRange(
1696 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1697
Manuel Klimek31c85922013-08-29 15:21:40 +00001698 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001699
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001700 TrailingWhitespace = 0;
1701 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001702 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001703 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001704 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001705 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001706 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001707 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001708 FormatTok->Tok.setIdentifierInfo(&Info);
1709 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001710 if (Style.Language == FormatStyle::LK_Java &&
1711 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1712 FormatTok->Tok.setKind(tok::identifier);
1713 FormatTok->Tok.setIdentifierInfo(nullptr);
1714 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001715 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001716 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001717 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001718 GreaterStashed = true;
1719 }
1720
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001721 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001722
Alexander Kornienko39856b72013-09-10 09:38:25 +00001723 StringRef Text = FormatTok->TokenText;
1724 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001725 if (FirstNewlinePos == StringRef::npos) {
1726 // FIXME: ColumnWidth actually depends on the start column, we need to
1727 // take this into account when the token is moved.
1728 FormatTok->ColumnWidth =
1729 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1730 Column += FormatTok->ColumnWidth;
1731 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001732 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001733 // FIXME: ColumnWidth actually depends on the start column, we need to
1734 // take this into account when the token is moved.
1735 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1736 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1737
Alexander Kornienko39856b72013-09-10 09:38:25 +00001738 // The last line of the token always starts in column 0.
1739 // Thus, the length can be precomputed even in the presence of tabs.
1740 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1741 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1742 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001743 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001744 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001745
Daniel Jaspere1e43192014-04-01 12:55:11 +00001746 FormatTok->IsForEachMacro =
1747 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1748 FormatTok->Tok.getIdentifierInfo());
1749
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001750 return FormatTok;
1751 }
1752
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001753 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001754 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001755 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001756 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001757 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001758 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001759 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001760 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001761 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001762 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001763 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001764 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001765 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001766 // Index (in 'Tokens') of the last token that starts a new line.
1767 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001768 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001769 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001770
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001771 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001772
Daniel Jasper8369aa52013-07-16 20:28:33 +00001773 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001774 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001775 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1776 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001777 // For formatting, treat unterminated string literals like normal string
1778 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001779 if (Tok.is(tok::unknown)) {
1780 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1781 Tok.Tok.setKind(tok::string_literal);
1782 Tok.IsUnterminatedLiteral = true;
1783 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1784 Tok.TokenText == "''") {
1785 Tok.Tok.setKind(tok::char_constant);
1786 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001787 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001788
1789 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1790 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001791 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001792 }
1793
Daniel Jasper471894432014-08-06 13:40:26 +00001794 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001795
1796 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1797 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001798 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001799 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001800 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001801
1802 void resetLexer(unsigned Offset) {
1803 StringRef Buffer = SourceMgr.getBufferData(ID);
1804 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1805 getFormattingLangOpts(Style), Buffer.begin(),
1806 Buffer.begin() + Offset, Buffer.end()));
1807 Lex->SetKeepWhitespaceMode(true);
1808 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001809};
1810
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001811static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1812 switch (Language) {
1813 case FormatStyle::LK_Cpp:
1814 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001815 case FormatStyle::LK_Java:
1816 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001817 case FormatStyle::LK_JavaScript:
1818 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001819 case FormatStyle::LK_Proto:
1820 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001821 default:
1822 return "Unknown";
1823 }
1824}
1825
Daniel Jasperf7935112012-12-03 18:12:45 +00001826class Formatter : public UnwrappedLineConsumer {
1827public:
Daniel Jasper23376252014-09-09 14:37:39 +00001828 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001829 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001830 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1831 Whitespaces(SourceMgr, Style,
1832 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001833 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001834 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001835 DEBUG(llvm::dbgs() << "File encoding: "
1836 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1837 : "unknown")
1838 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001839 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1840 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001841 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001842
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001843 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001844 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001845 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001846
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001847 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1848 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001849 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001850 assert(UnwrappedLines.rbegin()->empty());
1851 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1852 ++Run) {
1853 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1854 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1855 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1856 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1857 }
1858 tooling::Replacements RunResult =
1859 format(AnnotatedLines, StructuralError, Tokens);
1860 DEBUG({
1861 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1862 for (tooling::Replacements::iterator I = RunResult.begin(),
1863 E = RunResult.end();
1864 I != E; ++I) {
1865 llvm::dbgs() << I->toString() << "\n";
1866 }
1867 });
1868 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1869 delete AnnotatedLines[i];
1870 }
1871 Result.insert(RunResult.begin(), RunResult.end());
1872 Whitespaces.reset();
1873 }
1874 return Result;
1875 }
1876
1877 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1878 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001879 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001880 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001881 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001882 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001883 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001884 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001885 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001886 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001887 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001888
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001889 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001890 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1891 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001892 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001893 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001894 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001895 return Whitespaces.generateReplacements();
1896 }
1897
1898private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001899 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001900 // Returns \c true if at least one line between I and E or one of their
1901 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001902 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1903 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1904 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001905 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001906 while (I != E) {
1907 AnnotatedLine *Line = *I;
1908 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1909
1910 // If a line is part of a preprocessor directive, it needs to be formatted
1911 // if any token within the directive is affected.
1912 if (Line->InPPDirective) {
1913 FormatToken *Last = Line->Last;
1914 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1915 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1916 Last = (*PPEnd)->Last;
1917 ++PPEnd;
1918 }
1919
1920 if (affectsTokenRange(*Line->First, *Last,
1921 /*IncludeLeadingNewlines=*/false)) {
1922 SomeLineAffected = true;
1923 markAllAsAffected(I, PPEnd);
1924 }
1925 I = PPEnd;
1926 continue;
1927 }
1928
Daniel Jasper38c82402013-11-29 09:27:43 +00001929 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001930 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001931
Daniel Jasper38c82402013-11-29 09:27:43 +00001932 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001933 ++I;
1934 }
1935 return SomeLineAffected;
1936 }
1937
Daniel Jasper9c199562013-11-28 15:58:55 +00001938 // Determines whether 'Line' is affected by the SourceRanges given as input.
1939 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001940 bool nonPPLineAffected(AnnotatedLine *Line,
1941 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001942 bool SomeLineAffected = false;
1943 Line->ChildrenAffected =
1944 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1945 if (Line->ChildrenAffected)
1946 SomeLineAffected = true;
1947
1948 // Stores whether one of the line's tokens is directly affected.
1949 bool SomeTokenAffected = false;
1950 // Stores whether we need to look at the leading newlines of the next token
1951 // in order to determine whether it was affected.
1952 bool IncludeLeadingNewlines = false;
1953
1954 // Stores whether the first child line of any of this line's tokens is
1955 // affected.
1956 bool SomeFirstChildAffected = false;
1957
1958 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1959 // Determine whether 'Tok' was affected.
1960 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1961 SomeTokenAffected = true;
1962
1963 // Determine whether the first child of 'Tok' was affected.
1964 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1965 SomeFirstChildAffected = true;
1966
1967 IncludeLeadingNewlines = Tok->Children.empty();
1968 }
1969
1970 // Was this line moved, i.e. has it previously been on the same line as an
1971 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001972 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1973 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001974
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001975 bool IsContinuedComment =
1976 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1977 Line->First->NewlinesBefore < 2 && PreviousLine &&
1978 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001979
1980 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1981 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001982 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001983 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001984 }
1985 return SomeLineAffected;
1986 }
1987
Daniel Jasper5500f612013-11-25 11:08:59 +00001988 // Marks all lines between I and E as well as all their children as affected.
1989 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1990 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1991 while (I != E) {
1992 (*I)->Affected = true;
1993 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1994 ++I;
1995 }
1996 }
1997
1998 // Returns true if the range from 'First' to 'Last' intersects with one of the
1999 // input ranges.
2000 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
2001 bool IncludeLeadingNewlines) {
2002 SourceLocation Start = First.WhitespaceRange.getBegin();
2003 if (!IncludeLeadingNewlines)
2004 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00002005 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00002006 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00002007 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
2008 return affectsCharSourceRange(Range);
2009 }
2010
2011 // Returns true if one of the input ranges intersect the leading empty lines
2012 // before 'Tok'.
2013 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
2014 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
2015 Tok.WhitespaceRange.getBegin(),
2016 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2017 return affectsCharSourceRange(EmptyLineRange);
2018 }
2019
2020 // Returns true if 'Range' intersects with one of the input ranges.
2021 bool affectsCharSourceRange(const CharSourceRange &Range) {
2022 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2023 E = Ranges.end();
2024 I != E; ++I) {
2025 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2026 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2027 return true;
2028 }
2029 return false;
2030 }
2031
Alexander Kornienko9e649af2013-09-11 12:25:57 +00002032 static bool inputUsesCRLF(StringRef Text) {
2033 return Text.count('\r') * 2 > Text.count('\n');
2034 }
2035
Manuel Klimek71814b42013-10-11 21:25:45 +00002036 void
2037 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002038 unsigned CountBoundToVariable = 0;
2039 unsigned CountBoundToType = 0;
2040 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002041 bool HasBinPackedFunction = false;
2042 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002043 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002044 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002045 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002046 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002047 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002048 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002049 bool SpacesBefore =
2050 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2051 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2052 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002053 if (SpacesBefore && !SpacesAfter)
2054 ++CountBoundToVariable;
2055 else if (!SpacesBefore && SpacesAfter)
2056 ++CountBoundToType;
2057 }
2058
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002059 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002060 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002061 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002062 if (Tok->is(TT_TemplateCloser) &&
2063 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002064 HasCpp03IncompatibleFormat = true;
2065 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002066
2067 if (Tok->PackingKind == PPK_BinPacked)
2068 HasBinPackedFunction = true;
2069 if (Tok->PackingKind == PPK_OnePerLine)
2070 HasOnePerLineFunction = true;
2071
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002072 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002073 }
2074 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002075 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002076 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002077 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002078 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002079 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002080 }
2081 if (Style.Standard == FormatStyle::LS_Auto) {
2082 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2083 : FormatStyle::LS_Cpp03;
2084 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002085 BinPackInconclusiveFunctions =
2086 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002087 }
2088
Craig Topperfb6b25b2014-03-15 04:29:04 +00002089 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002090 assert(!UnwrappedLines.empty());
2091 UnwrappedLines.back().push_back(TheLine);
2092 }
2093
Craig Topperfb6b25b2014-03-15 04:29:04 +00002094 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002095 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002096 }
2097
2098 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002099 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002100 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002101 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002102 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002103 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002104
2105 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002106 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002107};
2108
Craig Topperaf35e852013-06-30 22:29:28 +00002109} // end anonymous namespace
2110
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002111tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2112 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002113 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002114 if (Style.DisableFormat)
2115 return tooling::Replacements();
2116 return reformat(Style, SourceMgr,
2117 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2118}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002119
Daniel Jasper23376252014-09-09 14:37:39 +00002120tooling::Replacements reformat(const FormatStyle &Style,
2121 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002122 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002123 if (Style.DisableFormat)
2124 return tooling::Replacements();
2125 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002126 return formatter.format();
2127}
2128
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002129tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002130 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002131 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002132 if (Style.DisableFormat)
2133 return tooling::Replacements();
2134
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002135 FileManager Files((FileSystemOptions()));
2136 DiagnosticsEngine Diagnostics(
2137 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2138 new DiagnosticOptions);
2139 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002140 std::unique_ptr<llvm::MemoryBuffer> Buf =
2141 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002142 const clang::FileEntry *Entry =
2143 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002144 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002145 FileID ID =
2146 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002147 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2148 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002149 for (const tooling::Range &Range : Ranges) {
2150 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2151 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002152 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2153 }
Daniel Jasper23376252014-09-09 14:37:39 +00002154 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002155}
2156
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002157LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002158 LangOptions LangOpts;
2159 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002160 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2161 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002162 LangOpts.LineComment = 1;
Daniel Jasper30a24062014-11-14 09:02:28 +00002163 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2164 Style.Language != FormatStyle::LK_Java;
2165 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002166 LangOpts.Bool = 1;
2167 LangOpts.ObjC1 = 1;
2168 LangOpts.ObjC2 = 1;
2169 return LangOpts;
2170}
2171
Edwin Vaned544aa72013-09-30 13:31:48 +00002172const char *StyleOptionHelpDescription =
2173 "Coding style, currently supports:\n"
2174 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2175 "Use -style=file to load style configuration from\n"
2176 ".clang-format file located in one of the parent\n"
2177 "directories of the source file (or current\n"
2178 "directory for stdin).\n"
2179 "Use -style=\"{key: value, ...}\" to set specific\n"
2180 "parameters, e.g.:\n"
2181 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2182
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002183static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002184 if (FileName.endswith(".java")) {
2185 return FormatStyle::LK_Java;
2186 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002187 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002188 } else if (FileName.endswith_lower(".proto") ||
2189 FileName.endswith_lower(".protodevel")) {
2190 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002191 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002192 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002193}
2194
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002195FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2196 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002197 FormatStyle Style = getLLVMStyle();
2198 Style.Language = getLanguageByFileName(FileName);
2199 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002200 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2201 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002202 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002203 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002204
2205 if (StyleName.startswith("{")) {
2206 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002207 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002208 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2209 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002210 }
2211 return Style;
2212 }
2213
2214 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002215 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002216 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2217 << " style\n";
2218 return Style;
2219 }
2220
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002221 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002222 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002223 SmallString<128> Path(FileName);
2224 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002225 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002226 Directory = llvm::sys::path::parent_path(Directory)) {
2227 if (!llvm::sys::fs::is_directory(Directory))
2228 continue;
2229 SmallString<128> ConfigFile(Directory);
2230
2231 llvm::sys::path::append(ConfigFile, ".clang-format");
2232 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2233 bool IsFile = false;
2234 // Ignore errors from is_regular_file: we only need to know if we can read
2235 // the file or not.
2236 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2237
2238 if (!IsFile) {
2239 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2240 ConfigFile = Directory;
2241 llvm::sys::path::append(ConfigFile, "_clang-format");
2242 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2243 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2244 }
2245
2246 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002247 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2248 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2249 if (std::error_code EC = Text.getError()) {
2250 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002251 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002252 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002253 if (std::error_code ec =
2254 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002255 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002256 if (!UnsuitableConfigFiles.empty())
2257 UnsuitableConfigFiles.append(", ");
2258 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002259 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002260 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002261 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2262 << "\n";
2263 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002264 }
2265 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2266 return Style;
2267 }
2268 }
2269 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2270 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002271 if (!UnsuitableConfigFiles.empty()) {
2272 llvm::errs() << "Configuration file(s) do(es) not support "
2273 << getLanguageName(Style.Language) << ": "
2274 << UnsuitableConfigFiles << "\n";
2275 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002276 return Style;
2277}
2278
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002279} // namespace format
2280} // namespace clang