blob: b997486f979cd13b94b7ce82b130bafbc1e4c28e [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 Jasper85c472d2015-09-29 07:53:08 +000016#include "clang/Format/Format.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000017#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000019#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000030#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Chandler Carruth10346662014-04-22 03:17:02 +000035#define DEBUG_TYPE "format-formatter"
36
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000037using clang::format::FormatStyle;
38
Daniel Jaspere1e43192014-04-01 12:55:11 +000039LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +000040LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
Daniel Jaspere1e43192014-04-01 12:55:11 +000041
Alexander Kornienkod6538332013-05-07 15:32:14 +000042namespace llvm {
43namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000044template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
45 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
46 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000047 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000048 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000049 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000050 }
51};
52
53template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
54 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
55 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
56 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
57 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
58 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
59 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
60 }
61};
62
63template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
64 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
65 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
66 IO.enumCase(Value, "false", FormatStyle::UT_Never);
67 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
68 IO.enumCase(Value, "true", FormatStyle::UT_Always);
69 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
70 }
71};
72
Daniel Jasperd74cf402014-04-08 12:46:38 +000073template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
74 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
75 IO.enumCase(Value, "None", FormatStyle::SFS_None);
76 IO.enumCase(Value, "false", FormatStyle::SFS_None);
77 IO.enumCase(Value, "All", FormatStyle::SFS_All);
78 IO.enumCase(Value, "true", FormatStyle::SFS_All);
79 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000080 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000081 }
82};
83
Daniel Jasperac043c92014-09-15 11:11:00 +000084template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
85 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
86 IO.enumCase(Value, "All", FormatStyle::BOS_All);
87 IO.enumCase(Value, "true", FormatStyle::BOS_All);
88 IO.enumCase(Value, "None", FormatStyle::BOS_None);
89 IO.enumCase(Value, "false", FormatStyle::BOS_None);
90 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
91 }
92};
93
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000094template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
95 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
96 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
97 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000098 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
100 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000101 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000102 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000103 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 }
105};
106
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000107template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000108struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
109 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
110 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
111 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
112 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
113 IO.enumCase(Value, "TopLevelDefinitions",
114 FormatStyle::RTBS_TopLevelDefinitions);
115 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
116 }
117};
118
119template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000120struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
121 static void
122 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000123 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
124 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
125 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
126
127 // For backward compatibility.
128 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
129 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
130 }
131};
132
Alexander Kornienkod6538332013-05-07 15:32:14 +0000133template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000135 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000136 FormatStyle::NamespaceIndentationKind &Value) {
137 IO.enumCase(Value, "None", FormatStyle::NI_None);
138 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
139 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000140 }
141};
142
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000143template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
144 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
145 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
146 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
147 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
148
149 // For backward compatibility.
150 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
151 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
152 }
153};
154
Jacques Pienaarfc275112015-02-18 23:48:37 +0000155template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
156 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000157 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
158 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
159 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
160
Alp Toker958027b2014-07-14 19:42:55 +0000161 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000162 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
163 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
164 }
165};
166
167template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000168struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000169 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000170 FormatStyle::SpaceBeforeParensOptions &Value) {
171 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000172 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000173 FormatStyle::SBPO_ControlStatements);
174 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000175
176 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000177 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
178 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000179 }
180};
181
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000182template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000183 static void mapping(IO &IO, FormatStyle &Style) {
184 // When reading, read the language first, we need it for getPredefinedStyle.
185 IO.mapOptional("Language", Style.Language);
186
Alexander Kornienko49149672013-05-10 11:56:10 +0000187 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000188 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
189 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000190 ArrayRef<StringRef> Styles(StylesArray);
191 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
192 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000193 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000194 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000195 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000196 IO.mapOptional("# BasedOnStyle", StyleName);
197 break;
198 }
199 }
200 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 StringRef BasedOnStyle;
202 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000203 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000204 FormatStyle::LanguageKind OldLanguage = Style.Language;
205 FormatStyle::LanguageKind Language =
206 ((FormatStyle *)IO.getContext())->Language;
207 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000208 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
209 return;
210 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000211 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000212 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 }
214
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000215 // For backward compatibility.
216 if (!IO.outputting()) {
217 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
218 IO.mapOptional("IndentFunctionDeclarationAfterType",
219 Style.IndentWrappedFunctionNames);
220 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
221 IO.mapOptional("SpaceAfterControlStatementKeyword",
222 Style.SpaceBeforeParens);
223 }
224
Alexander Kornienkod6538332013-05-07 15:32:14 +0000225 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000226 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000227 IO.mapOptional("AlignConsecutiveAssignments",
228 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000229 IO.mapOptional("AlignConsecutiveDeclarations",
230 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000232 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000233 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000234 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
235 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000236 IO.mapOptional("AllowShortBlocksOnASingleLine",
237 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000238 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
239 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000240 IO.mapOptional("AllowShortFunctionsOnASingleLine",
241 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000242 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
243 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000244 IO.mapOptional("AllowShortLoopsOnASingleLine",
245 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000246 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
247 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000248 IO.mapOptional("AlwaysBreakAfterReturnType",
249 Style.AlwaysBreakAfterReturnType);
250 // If AlwaysBreakAfterDefinitionReturnType was specified but
251 // AlwaysBreakAfterReturnType was not, initialize the latter from the
252 // former for backwards compatibility.
253 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
254 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
255 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
256 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
257 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
258 FormatStyle::DRTBS_TopLevel)
259 Style.AlwaysBreakAfterReturnType =
260 FormatStyle::RTBS_TopLevelDefinitions;
261 }
262
Alexander Kornienko58611712013-07-04 12:02:44 +0000263 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
264 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000265 IO.mapOptional("AlwaysBreakTemplateDeclarations",
266 Style.AlwaysBreakTemplateDeclarations);
267 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
268 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000269 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000270 IO.mapOptional("BreakBeforeBinaryOperators",
271 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000272 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000273 IO.mapOptional("BreakBeforeTernaryOperators",
274 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000275 IO.mapOptional("BreakConstructorInitializersBeforeComma",
276 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000277 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000278 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000279 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
280 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000281 IO.mapOptional("ConstructorInitializerIndentWidth",
282 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000283 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
284 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000285 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000286 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000287 IO.mapOptional("ExperimentalAutoDetectBinPacking",
288 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000289 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000290 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000291 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000292 IO.mapOptional("IndentWidth", Style.IndentWidth);
293 IO.mapOptional("IndentWrappedFunctionNames",
294 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000295 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
296 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000297 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
298 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000299 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000300 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000301 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000302 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000303 IO.mapOptional("ObjCSpaceBeforeProtocolList",
304 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000305 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
306 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000307 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000308 IO.mapOptional("PenaltyBreakFirstLessLess",
309 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000310 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000311 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
312 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
313 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000314 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000315 IO.mapOptional("ReflowComments", Style.ReflowComments);
316 IO.mapOptional("SortIncludes", Style.SortIncludes);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000317 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000318 IO.mapOptional("SpaceBeforeAssignmentOperators",
319 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000320 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
321 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
322 IO.mapOptional("SpacesBeforeTrailingComments",
323 Style.SpacesBeforeTrailingComments);
324 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
325 IO.mapOptional("SpacesInContainerLiterals",
326 Style.SpacesInContainerLiterals);
327 IO.mapOptional("SpacesInCStyleCastParentheses",
328 Style.SpacesInCStyleCastParentheses);
329 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
330 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
331 IO.mapOptional("Standard", Style.Standard);
332 IO.mapOptional("TabWidth", Style.TabWidth);
333 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000334 }
335};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000336
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000337template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
338 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
339 IO.mapOptional("AfterClass", Wrapping.AfterClass);
340 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
341 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
342 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
343 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
344 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
345 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
346 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
347 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
348 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
349 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
350 }
351};
352
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000353template <> struct MappingTraits<FormatStyle::IncludeCategory> {
354 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
355 IO.mapOptional("Regex", Category.Regex);
356 IO.mapOptional("Priority", Category.Priority);
357 }
358};
359
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000360// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000361// IO.getContext() should contain a pointer to the FormatStyle structure, that
362// will be used to get default values for missing keys.
363// If the first element has no Language specified, it will be treated as the
364// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000365template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000366 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
367 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000368 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000369 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000370 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000371 if (Index >= Seq.size()) {
372 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000373 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000374 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000375 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000376 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000377 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000378 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000379 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000380 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000381 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000382 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000383 }
384};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000385} // namespace yaml
386} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000387
Daniel Jasperf7935112012-12-03 18:12:45 +0000388namespace clang {
389namespace format {
390
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000391const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000392 static ParseErrorCategory C;
393 return C;
394}
395std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000396 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000397}
398
399const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
400 return "clang-format.parse_error";
401}
402
403std::string ParseErrorCategory::message(int EV) const {
404 switch (static_cast<ParseError>(EV)) {
405 case ParseError::Success:
406 return "Success";
407 case ParseError::Error:
408 return "Invalid argument";
409 case ParseError::Unsuitable:
410 return "Unsuitable";
411 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000412 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000413}
414
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000415static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000416 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
417 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000418 FormatStyle Expanded = Style;
419 Expanded.BraceWrapping = {false, false, false, false, false, false,
420 false, false, false, false, false};
421 switch (Style.BreakBeforeBraces) {
422 case FormatStyle::BS_Linux:
423 Expanded.BraceWrapping.AfterClass = true;
424 Expanded.BraceWrapping.AfterFunction = true;
425 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000426 break;
427 case FormatStyle::BS_Mozilla:
428 Expanded.BraceWrapping.AfterClass = true;
429 Expanded.BraceWrapping.AfterEnum = true;
430 Expanded.BraceWrapping.AfterFunction = true;
431 Expanded.BraceWrapping.AfterStruct = true;
432 Expanded.BraceWrapping.AfterUnion = true;
433 break;
434 case FormatStyle::BS_Stroustrup:
435 Expanded.BraceWrapping.AfterFunction = true;
436 Expanded.BraceWrapping.BeforeCatch = true;
437 Expanded.BraceWrapping.BeforeElse = true;
438 break;
439 case FormatStyle::BS_Allman:
440 Expanded.BraceWrapping.AfterClass = true;
441 Expanded.BraceWrapping.AfterControlStatement = true;
442 Expanded.BraceWrapping.AfterEnum = true;
443 Expanded.BraceWrapping.AfterFunction = true;
444 Expanded.BraceWrapping.AfterNamespace = true;
445 Expanded.BraceWrapping.AfterObjCDeclaration = true;
446 Expanded.BraceWrapping.AfterStruct = true;
447 Expanded.BraceWrapping.BeforeCatch = true;
448 Expanded.BraceWrapping.BeforeElse = true;
449 break;
450 case FormatStyle::BS_GNU:
451 Expanded.BraceWrapping = {true, true, true, true, true, true,
452 true, true, true, true, true};
453 break;
454 case FormatStyle::BS_WebKit:
455 Expanded.BraceWrapping.AfterFunction = true;
456 break;
457 default:
458 break;
459 }
460 return Expanded;
461}
462
Daniel Jasperf7935112012-12-03 18:12:45 +0000463FormatStyle getLLVMStyle() {
464 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000465 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000466 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000467 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000468 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000469 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000470 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000471 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000472 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000473 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000474 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000475 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000476 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000477 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000478 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000479 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000480 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000481 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000482 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000483 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000484 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000485 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000486 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000487 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000488 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
489 false, false, false, false, false};
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000490 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Nico Weber2cd92f12015-10-15 16:03:01 +0000491 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000492 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000493 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000494 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000495 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000496 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000497 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000498 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000499 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000500 LLVMStyle.ForEachMacros.push_back("foreach");
501 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
502 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000503 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
504 {"^(<|\"(gtest|isl|json)/)", 3},
505 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000506 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000507 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000508 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000509 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000510 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000511 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000512 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000513 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000514 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000515 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000516 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000517 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000518 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000519 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000520 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000521 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000522 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000523 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000524 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000525 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000526 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000527 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000528 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000529 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000530
Daniel Jasper19a541e2013-12-19 16:45:34 +0000531 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000532 LLVMStyle.PenaltyBreakFirstLessLess = 120;
533 LLVMStyle.PenaltyBreakString = 1000;
534 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000535 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000536 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000537
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000538 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000539 LLVMStyle.SortIncludes = true;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000540
Daniel Jasperf7935112012-12-03 18:12:45 +0000541 return LLVMStyle;
542}
543
Nico Weber514ecc82014-02-02 20:50:45 +0000544FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000545 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000546 GoogleStyle.Language = Language;
547
Daniel Jasperf7935112012-12-03 18:12:45 +0000548 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000549 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000550 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000551 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000552 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000553 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000554 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000555 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000556 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000557 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000558 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000559 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000560 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000561 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000562 GoogleStyle.SpacesBeforeTrailingComments = 2;
563 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000564
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000565 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000566 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000567
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000568 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000569 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000570 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000571 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000572 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000573 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000574 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000575 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
576 GoogleStyle.ColumnLimit = 100;
577 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000578 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000579 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000580 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000581 GoogleStyle.AlignOperands = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000582 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
583 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000584 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000585 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000586 GoogleStyle.SpacesInContainerLiterals = false;
587 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000588 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000589 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000590 }
591
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 return GoogleStyle;
593}
594
Nico Weber514ecc82014-02-02 20:50:45 +0000595FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
596 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000597 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000598 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000599 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000600 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000601 ChromiumStyle.IndentWidth = 4;
Nico Weber450425c2014-11-26 16:43:18 +0000602 } else {
603 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
604 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
605 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
606 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
607 ChromiumStyle.BinPackParameters = false;
608 ChromiumStyle.DerivePointerAlignment = false;
609 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000610 return ChromiumStyle;
611}
612
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000613FormatStyle getMozillaStyle() {
614 FormatStyle MozillaStyle = getLLVMStyle();
615 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000616 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Zachary Turner448592e2015-12-18 22:20:15 +0000617 MozillaStyle.AlwaysBreakAfterReturnType =
618 FormatStyle::RTBS_TopLevelDefinitions;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000619 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
620 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000621 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000622 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000623 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
624 MozillaStyle.ConstructorInitializerIndentWidth = 2;
625 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000626 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000627 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000628 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000629 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
630 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000631 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000632 return MozillaStyle;
633}
634
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000635FormatStyle getWebKitStyle() {
636 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000637 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000638 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000639 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000640 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000641 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000642 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000643 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000644 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000645 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000646 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000647 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000648 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000649 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000650 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000651 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000652 return Style;
653}
654
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000655FormatStyle getGNUStyle() {
656 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000657 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000658 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000659 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000660 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000661 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000662 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000663 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000664 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000665 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000666 return Style;
667}
668
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000669FormatStyle getNoStyle() {
670 FormatStyle NoStyle = getLLVMStyle();
671 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000672 NoStyle.SortIncludes = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000673 return NoStyle;
674}
675
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000676bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
677 FormatStyle *Style) {
678 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000679 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000680 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000681 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000682 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000683 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000684 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000685 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000686 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000687 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000688 } else if (Name.equals_lower("gnu")) {
689 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000690 } else if (Name.equals_lower("none")) {
691 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000692 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000693 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000694 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000695
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000696 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000697 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000698}
699
Rafael Espindolac0809172014-06-12 14:02:15 +0000700std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000701 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000702 FormatStyle::LanguageKind Language = Style->Language;
703 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000704 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000705 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000706
707 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000708 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000709 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
710 // values for the fields, keys for which are missing from the configuration.
711 // Mapping also uses the context to get the language to find the correct
712 // base style.
713 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000714 Input >> Styles;
715 if (Input.error())
716 return Input.error();
717
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000718 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000719 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000720 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000721 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000722 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000723 for (unsigned j = 0; j < i; ++j) {
724 if (Styles[i].Language == Styles[j].Language) {
725 DEBUG(llvm::dbgs()
726 << "Duplicate languages in the config file on positions " << j
727 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000728 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000729 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000730 }
731 }
732 // Look for a suitable configuration starting from the end, so we can
733 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000734 // configuration (which can only be at slot 0) after it.
735 for (int i = Styles.size() - 1; i >= 0; --i) {
736 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000737 Styles[i].Language == FormatStyle::LK_None) {
738 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000739 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000740 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000741 }
742 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000743 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000744}
745
746std::string configurationAsText(const FormatStyle &Style) {
747 std::string Text;
748 llvm::raw_string_ostream Stream(Text);
749 llvm::yaml::Output Output(Stream);
750 // We use the same mapping method for input and output, so we need a non-const
751 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000752 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000753 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000754 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000755}
756
Craig Topperaf35e852013-06-30 22:29:28 +0000757namespace {
758
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000759class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000760public:
Daniel Jasper23376252014-09-09 14:37:39 +0000761 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000762 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000763 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000764 LessStashed(false), Column(0), TrailingWhitespace(0),
765 SourceMgr(SourceMgr), ID(ID), Style(Style),
766 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000767 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
768 MacroBlockBeginRegex(Style.MacroBlockBegin),
769 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000770 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
771 getFormattingLangOpts(Style)));
772 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000773
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000774 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000775 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
776 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000777 }
778
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000779 ArrayRef<FormatToken *> lex() {
780 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000781 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000782 do {
783 Tokens.push_back(getNextToken());
Daniel Jasper265309e2015-10-18 07:02:28 +0000784 if (Style.Language == FormatStyle::LK_JavaScript)
785 tryParseJSRegexLiteral();
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000786 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000787 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000788 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000789 } while (Tokens.back()->Tok.isNot(tok::eof));
790 return Tokens;
791 }
792
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000793 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000794
795private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000796 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000797 if (tryMerge_TMacro())
798 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000799 if (tryMergeConflictMarkers())
800 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000801 if (tryMergeLessLess())
802 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000803
804 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000805 if (tryMergeTemplateString())
806 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000807
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000808 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
809 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
810 tok::equal};
811 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
812 tok::greaterequal};
813 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000814 // FIXME: Investigate what token type gives the correct operator priority.
815 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000816 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000817 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000818 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000819 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000820 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000821 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000822 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000823 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000824 }
825
Jacques Pienaarfc275112015-02-18 23:48:37 +0000826 bool tryMergeLessLess() {
827 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000828 if (Tokens.size() < 3)
829 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000830
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000831 bool FourthTokenIsLess = false;
832 if (Tokens.size() > 3)
833 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000834
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000835 auto First = Tokens.end() - 3;
836 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
837 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000838 return false;
839
840 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000841 if (First[1]->WhitespaceRange.getBegin() !=
842 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000843 return false;
844
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000845 First[0]->Tok.setKind(tok::lessless);
846 First[0]->TokenText = "<<";
847 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000848 Tokens.erase(Tokens.end() - 2);
849 return true;
850 }
851
Manuel Klimek79e06082015-05-21 12:23:34 +0000852 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000853 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000854 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000855
856 SmallVectorImpl<FormatToken *>::const_iterator First =
857 Tokens.end() - Kinds.size();
858 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000859 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000860 unsigned AddLength = 0;
861 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000862 if (!First[i]->is(Kinds[i]) ||
863 First[i]->WhitespaceRange.getBegin() !=
864 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000865 return false;
866 AddLength += First[i]->TokenText.size();
867 }
868 Tokens.resize(Tokens.size() - Kinds.size() + 1);
869 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
870 First[0]->TokenText.size() + AddLength);
871 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000872 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000873 return true;
874 }
875
Daniel Jasper265309e2015-10-18 07:02:28 +0000876 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
877 bool precedesOperand(FormatToken *Tok) {
878 // NB: This is not entirely correct, as an r_paren can introduce an operand
879 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
880 // corner case to not matter in practice, though.
881 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
882 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
883 tok::colon, tok::question, tok::tilde) ||
884 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
885 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
886 tok::kw_typeof, Keywords.kw_instanceof,
887 Keywords.kw_in) ||
888 Tok->isBinaryOperator();
889 }
890
891 bool canPrecedeRegexLiteral(FormatToken *Prev) {
892 if (!Prev)
893 return true;
894
895 // Regex literals can only follow after prefix unary operators, not after
896 // postfix unary operators. If the '++' is followed by a non-operand
897 // introducing token, the slash here is the operand and not the start of a
898 // regex.
899 if (Prev->isOneOf(tok::plusplus, tok::minusminus))
900 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
901
902 // The previous token must introduce an operand location where regex
903 // literals can occur.
904 if (!precedesOperand(Prev))
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000905 return false;
Daniel Jasper265309e2015-10-18 07:02:28 +0000906
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000907 return true;
908 }
909
Daniel Jasper265309e2015-10-18 07:02:28 +0000910 // Tries to parse a JavaScript Regex literal starting at the current token,
911 // if that begins with a slash and is in a location where JavaScript allows
912 // regex literals. Changes the current token to a regex literal and updates
913 // its text if successful.
914 void tryParseJSRegexLiteral() {
915 FormatToken *RegexToken = Tokens.back();
916 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
917 return;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000918
Daniel Jasper265309e2015-10-18 07:02:28 +0000919 FormatToken *Prev = nullptr;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000920 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
Daniel Jasper265309e2015-10-18 07:02:28 +0000921 // NB: Because previous pointers are not initialized yet, this cannot use
922 // Token.getPreviousNonComment.
923 if ((*I)->isNot(tok::comment)) {
924 Prev = *I;
925 break;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000926 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000927 }
Daniel Jasper265309e2015-10-18 07:02:28 +0000928
929 if (!canPrecedeRegexLiteral(Prev))
930 return;
931
932 // 'Manually' lex ahead in the current file buffer.
933 const char *Offset = Lex->getBufferLocation();
934 const char *RegexBegin = Offset - RegexToken->TokenText.size();
935 StringRef Buffer = Lex->getBuffer();
936 bool InCharacterClass = false;
937 bool HaveClosingSlash = false;
938 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
939 // Regular expressions are terminated with a '/', which can only be
940 // escaped using '\' or a character class between '[' and ']'.
941 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
942 switch (*Offset) {
943 case '\\':
944 // Skip the escaped character.
945 ++Offset;
946 break;
947 case '[':
948 InCharacterClass = true;
949 break;
950 case ']':
951 InCharacterClass = false;
952 break;
953 case '/':
954 if (!InCharacterClass)
955 HaveClosingSlash = true;
956 break;
957 }
958 }
959
960 RegexToken->Type = TT_RegexLiteral;
961 // Treat regex literals like other string_literals.
962 RegexToken->Tok.setKind(tok::string_literal);
963 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
964 RegexToken->ColumnWidth = RegexToken->TokenText.size();
965
966 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000967 }
968
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000969 bool tryMergeTemplateString() {
970 if (Tokens.size() < 2)
971 return false;
972
973 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000974 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000975 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
976 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000977 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
978 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000979 return false;
980 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
981 // Unknown token that's not actually a backtick, or a comment that doesn't
982 // contain a backtick.
983 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000984 return false;
985
986 unsigned TokenCount = 0;
987 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000988 unsigned EndColumnInFirstLine =
989 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000990 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
991 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000992 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000993 IsMultiline = true;
994
995 // If there was a preceding template string, this must be the start of a
996 // template string, not the end.
997 if (I[0]->is(TT_TemplateString))
998 return false;
999
1000 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
1001 // Keep track of the rhs offset of the last token to wrap across lines -
1002 // its the rhs offset of the first line of the template string, used to
1003 // determine its width.
1004 if (I[0]->IsMultiline)
1005 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
1006 // If the token has newlines, the token before it (if it exists) is the
1007 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +00001008 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001009 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001010 IsMultiline = true;
1011 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001012 continue;
1013 }
1014
1015 Tokens.resize(Tokens.size() - TokenCount);
1016 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +00001017 const char *EndOffset =
1018 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
1019 if (CommentBacktickPos != 0) {
1020 // If the backtick was not the first character (e.g. in a comment),
1021 // re-lex after the backtick position.
1022 SourceLocation Loc = EndBacktick->Tok.getLocation();
1023 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
1024 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001025 Tokens.back()->TokenText =
1026 StringRef(Tokens.back()->TokenText.data(),
1027 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +00001028
1029 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
1030 if (EndOriginalColumn == 0) {
1031 SourceLocation Loc = EndBacktick->Tok.getLocation();
1032 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
1033 }
1034 // If the ` is further down within the token (e.g. in a comment).
1035 EndOriginalColumn += CommentBacktickPos;
1036
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001037 if (IsMultiline) {
1038 // ColumnWidth is from backtick to last token in line.
1039 // LastLineColumnWidth is 0 to backtick.
1040 // x = `some content
1041 // until here`;
1042 Tokens.back()->ColumnWidth =
1043 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001044 // +1 for the ` itself.
1045 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001046 Tokens.back()->IsMultiline = true;
1047 } else {
1048 // Token simply spans from start to end, +1 for the ` itself.
1049 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001050 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001051 }
1052 return true;
1053 }
1054 return false;
1055 }
1056
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001057 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001058 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001059 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001060 FormatToken *Last = Tokens.back();
1061 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001062 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001063
1064 FormatToken *String = Tokens[Tokens.size() - 2];
1065 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001066 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001067
1068 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001069 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001070
1071 FormatToken *Macro = Tokens[Tokens.size() - 4];
1072 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001073 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001074
1075 const char *Start = Macro->TokenText.data();
1076 const char *End = Last->TokenText.data() + Last->TokenText.size();
1077 String->TokenText = StringRef(Start, End - Start);
1078 String->IsFirst = Macro->IsFirst;
1079 String->LastNewlineOffset = Macro->LastNewlineOffset;
1080 String->WhitespaceRange = Macro->WhitespaceRange;
1081 String->OriginalColumn = Macro->OriginalColumn;
1082 String->ColumnWidth = encoding::columnWidthWithTabs(
1083 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001084 String->NewlinesBefore = Macro->NewlinesBefore;
1085 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001086
1087 Tokens.pop_back();
1088 Tokens.pop_back();
1089 Tokens.pop_back();
1090 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001091 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001092 }
1093
Manuel Klimek68b03042014-04-14 09:14:11 +00001094 bool tryMergeConflictMarkers() {
1095 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1096 return false;
1097
1098 // Conflict lines look like:
1099 // <marker> <text from the vcs>
1100 // For example:
1101 // >>>>>>> /file/in/file/system at revision 1234
1102 //
1103 // We merge all tokens in a line that starts with a conflict marker
1104 // into a single token with a special token type that the unwrapped line
1105 // parser will use to correctly rebuild the underlying code.
1106
1107 FileID ID;
1108 // Get the position of the first token in the line.
1109 unsigned FirstInLineOffset;
1110 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1111 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1112 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1113 // Calculate the offset of the start of the current line.
1114 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1115 if (LineOffset == StringRef::npos) {
1116 LineOffset = 0;
1117 } else {
1118 ++LineOffset;
1119 }
1120
1121 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1122 StringRef LineStart;
1123 if (FirstSpace == StringRef::npos) {
1124 LineStart = Buffer.substr(LineOffset);
1125 } else {
1126 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1127 }
1128
1129 TokenType Type = TT_Unknown;
1130 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1131 Type = TT_ConflictStart;
1132 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1133 LineStart == "====") {
1134 Type = TT_ConflictAlternative;
1135 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1136 Type = TT_ConflictEnd;
1137 }
1138
1139 if (Type != TT_Unknown) {
1140 FormatToken *Next = Tokens.back();
1141
1142 Tokens.resize(FirstInLineIndex + 1);
1143 // We do not need to build a complete token here, as we will skip it
1144 // during parsing anyway (as we must not touch whitespace around conflict
1145 // markers).
1146 Tokens.back()->Type = Type;
1147 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1148
1149 Tokens.push_back(Next);
1150 return true;
1151 }
1152
1153 return false;
1154 }
1155
Jacques Pienaarfc275112015-02-18 23:48:37 +00001156 FormatToken *getStashedToken() {
1157 // Create a synthesized second '>' or '<' token.
1158 Token Tok = FormatTok->Tok;
1159 StringRef TokenText = FormatTok->TokenText;
1160
1161 unsigned OriginalColumn = FormatTok->OriginalColumn;
1162 FormatTok = new (Allocator.Allocate()) FormatToken;
1163 FormatTok->Tok = Tok;
1164 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001165 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1166 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001167 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1168 FormatTok->TokenText = TokenText;
1169 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001170 FormatTok->OriginalColumn = OriginalColumn + 1;
1171
Jacques Pienaarfc275112015-02-18 23:48:37 +00001172 return FormatTok;
1173 }
1174
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001175 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001176 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001177 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001178 return getStashedToken();
1179 }
1180 if (LessStashed) {
1181 LessStashed = false;
1182 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001183 }
1184
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001185 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001186 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001187 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001188 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001189 FormatTok->IsFirst = IsFirstToken;
1190 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001191
1192 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001193 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001194 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001195 StringRef Text = FormatTok->TokenText;
1196 auto EscapesNewline = [&](int pos) {
1197 // A '\r' here is just part of '\r\n'. Skip it.
1198 if (pos >= 0 && Text[pos] == '\r')
1199 --pos;
1200 // See whether there is an odd number of '\' before this.
1201 unsigned count = 0;
1202 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001203 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001204 break;
1205 return count & 1;
1206 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001207 // FIXME: This miscounts tok:unknown tokens that are not just
1208 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001209 for (int i = 0, e = Text.size(); i != e; ++i) {
1210 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001211 case '\n':
1212 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001213 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001214 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1215 Column = 0;
1216 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001217 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001218 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1219 Column = 0;
1220 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001221 case '\f':
1222 case '\v':
1223 Column = 0;
1224 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001225 case ' ':
1226 ++Column;
1227 break;
1228 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001229 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001230 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001231 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001232 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001233 FormatTok->Type = TT_ImplicitStringLiteral;
1234 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001235 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001236 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001237 break;
1238 }
1239 }
1240
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001241 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001242 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001243 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001244
Daniel Jasper8369aa52013-07-16 20:28:33 +00001245 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001246 }
Manuel Klimekef920692013-01-07 07:56:50 +00001247
Manuel Klimek1abf7892013-01-04 23:34:14 +00001248 // In case the token starts with escaped newlines, we want to
1249 // take them into account as whitespace - this pattern is quite frequent
1250 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001251 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001252 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1253 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001254 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001255 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001256 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001257 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001258 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001259 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001260
1261 FormatTok->WhitespaceRange = SourceRange(
1262 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1263
Manuel Klimek31c85922013-08-29 15:21:40 +00001264 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001265
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001266 TrailingWhitespace = 0;
1267 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001268 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001269 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001270 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001271 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001272 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001273 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001274 FormatTok->Tok.setIdentifierInfo(&Info);
1275 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001276 if (Style.Language == FormatStyle::LK_Java &&
1277 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1278 FormatTok->Tok.setKind(tok::identifier);
1279 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasper09840ef2015-11-20 15:58:50 +00001280 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1281 FormatTok->isOneOf(tok::kw_struct, tok::kw_union)) {
1282 FormatTok->Tok.setKind(tok::identifier);
1283 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001284 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001285 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001286 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001287 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001288 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001289 } else if (FormatTok->Tok.is(tok::lessless)) {
1290 FormatTok->Tok.setKind(tok::less);
1291 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1292 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001293 }
1294
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001295 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001296
Alexander Kornienko39856b72013-09-10 09:38:25 +00001297 StringRef Text = FormatTok->TokenText;
1298 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001299 if (FirstNewlinePos == StringRef::npos) {
1300 // FIXME: ColumnWidth actually depends on the start column, we need to
1301 // take this into account when the token is moved.
1302 FormatTok->ColumnWidth =
1303 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1304 Column += FormatTok->ColumnWidth;
1305 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001306 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001307 // FIXME: ColumnWidth actually depends on the start column, we need to
1308 // take this into account when the token is moved.
1309 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1310 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1311
Alexander Kornienko39856b72013-09-10 09:38:25 +00001312 // The last line of the token always starts in column 0.
1313 // Thus, the length can be precomputed even in the presence of tabs.
1314 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1315 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1316 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001317 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001318 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001319
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001320 if (Style.Language == FormatStyle::LK_Cpp) {
1321 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1322 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1323 tok::pp_define) &&
1324 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1325 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1326 FormatTok->Type = TT_ForEachMacro;
1327 } else if (FormatTok->is(tok::identifier)) {
1328 if (MacroBlockBeginRegex.match(Text)) {
1329 FormatTok->Type = TT_MacroBlockBegin;
1330 } else if (MacroBlockEndRegex.match(Text)) {
1331 FormatTok->Type = TT_MacroBlockEnd;
1332 }
1333 }
1334 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001335
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001336 return FormatTok;
1337 }
1338
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001339 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001340 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001341 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001342 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001343 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001344 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001345 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001346 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001347 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001348 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001349 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001350 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001351 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001352 // Index (in 'Tokens') of the last token that starts a new line.
1353 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001354 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001355 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001356
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001357 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001358
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001359 llvm::Regex MacroBlockBeginRegex;
1360 llvm::Regex MacroBlockEndRegex;
1361
Daniel Jasper8369aa52013-07-16 20:28:33 +00001362 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001363 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001364 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1365 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001366 // For formatting, treat unterminated string literals like normal string
1367 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001368 if (Tok.is(tok::unknown)) {
1369 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1370 Tok.Tok.setKind(tok::string_literal);
1371 Tok.IsUnterminatedLiteral = true;
1372 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1373 Tok.TokenText == "''") {
1374 Tok.Tok.setKind(tok::char_constant);
1375 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001376 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001377
1378 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1379 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001380 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001381 }
1382
Daniel Jasper471894432014-08-06 13:40:26 +00001383 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001384
1385 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1386 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001387 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001388 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001389 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001390
1391 void resetLexer(unsigned Offset) {
1392 StringRef Buffer = SourceMgr.getBufferData(ID);
1393 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1394 getFormattingLangOpts(Style), Buffer.begin(),
1395 Buffer.begin() + Offset, Buffer.end()));
1396 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001397 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001398 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001399};
1400
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001401static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1402 switch (Language) {
1403 case FormatStyle::LK_Cpp:
1404 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001405 case FormatStyle::LK_Java:
1406 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001407 case FormatStyle::LK_JavaScript:
1408 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001409 case FormatStyle::LK_Proto:
1410 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001411 default:
1412 return "Unknown";
1413 }
1414}
1415
Daniel Jasperf7935112012-12-03 18:12:45 +00001416class Formatter : public UnwrappedLineConsumer {
1417public:
Daniel Jasper23376252014-09-09 14:37:39 +00001418 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001419 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001420 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1421 Whitespaces(SourceMgr, Style,
1422 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001423 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001424 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001425 DEBUG(llvm::dbgs() << "File encoding: "
1426 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1427 : "unknown")
1428 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001429 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1430 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001431 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001432
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001433 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001434 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001435 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001436
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001437 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1438 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001439 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001440 assert(UnwrappedLines.rbegin()->empty());
1441 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1442 ++Run) {
1443 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1444 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1445 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1446 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1447 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001448 tooling::Replacements RunResult =
1449 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001450 DEBUG({
1451 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1452 for (tooling::Replacements::iterator I = RunResult.begin(),
1453 E = RunResult.end();
1454 I != E; ++I) {
1455 llvm::dbgs() << I->toString() << "\n";
1456 }
1457 });
1458 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1459 delete AnnotatedLines[i];
1460 }
1461 Result.insert(RunResult.begin(), RunResult.end());
1462 Whitespaces.reset();
1463 }
1464 return Result;
1465 }
1466
1467 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001468 FormatTokenLexer &Tokens,
1469 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001470 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001471 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001472 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001473 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001474 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001475 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001476 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001477 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001478 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001479
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001480 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001481 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1482 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001483 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001484 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1485 IncompleteFormat)
1486 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001487 return Whitespaces.generateReplacements();
1488 }
1489
1490private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001491 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001492 // Returns \c true if at least one line between I and E or one of their
1493 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001494 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1495 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1496 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001497 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001498 while (I != E) {
1499 AnnotatedLine *Line = *I;
1500 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1501
1502 // If a line is part of a preprocessor directive, it needs to be formatted
1503 // if any token within the directive is affected.
1504 if (Line->InPPDirective) {
1505 FormatToken *Last = Line->Last;
1506 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1507 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1508 Last = (*PPEnd)->Last;
1509 ++PPEnd;
1510 }
1511
1512 if (affectsTokenRange(*Line->First, *Last,
1513 /*IncludeLeadingNewlines=*/false)) {
1514 SomeLineAffected = true;
1515 markAllAsAffected(I, PPEnd);
1516 }
1517 I = PPEnd;
1518 continue;
1519 }
1520
Daniel Jasper38c82402013-11-29 09:27:43 +00001521 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001522 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001523
Daniel Jasper38c82402013-11-29 09:27:43 +00001524 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001525 ++I;
1526 }
1527 return SomeLineAffected;
1528 }
1529
Daniel Jasper9c199562013-11-28 15:58:55 +00001530 // Determines whether 'Line' is affected by the SourceRanges given as input.
1531 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001532 bool nonPPLineAffected(AnnotatedLine *Line,
1533 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001534 bool SomeLineAffected = false;
1535 Line->ChildrenAffected =
1536 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1537 if (Line->ChildrenAffected)
1538 SomeLineAffected = true;
1539
1540 // Stores whether one of the line's tokens is directly affected.
1541 bool SomeTokenAffected = false;
1542 // Stores whether we need to look at the leading newlines of the next token
1543 // in order to determine whether it was affected.
1544 bool IncludeLeadingNewlines = false;
1545
1546 // Stores whether the first child line of any of this line's tokens is
1547 // affected.
1548 bool SomeFirstChildAffected = false;
1549
1550 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1551 // Determine whether 'Tok' was affected.
1552 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1553 SomeTokenAffected = true;
1554
1555 // Determine whether the first child of 'Tok' was affected.
1556 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1557 SomeFirstChildAffected = true;
1558
1559 IncludeLeadingNewlines = Tok->Children.empty();
1560 }
1561
1562 // Was this line moved, i.e. has it previously been on the same line as an
1563 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001564 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1565 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001566
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001567 bool IsContinuedComment =
1568 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1569 Line->First->NewlinesBefore < 2 && PreviousLine &&
1570 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001571
1572 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1573 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001574 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001575 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001576 }
1577 return SomeLineAffected;
1578 }
1579
Daniel Jasper5500f612013-11-25 11:08:59 +00001580 // Marks all lines between I and E as well as all their children as affected.
1581 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1582 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1583 while (I != E) {
1584 (*I)->Affected = true;
1585 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1586 ++I;
1587 }
1588 }
1589
1590 // Returns true if the range from 'First' to 'Last' intersects with one of the
1591 // input ranges.
1592 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1593 bool IncludeLeadingNewlines) {
1594 SourceLocation Start = First.WhitespaceRange.getBegin();
1595 if (!IncludeLeadingNewlines)
1596 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001597 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001598 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001599 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1600 return affectsCharSourceRange(Range);
1601 }
1602
1603 // Returns true if one of the input ranges intersect the leading empty lines
1604 // before 'Tok'.
1605 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1606 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1607 Tok.WhitespaceRange.getBegin(),
1608 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1609 return affectsCharSourceRange(EmptyLineRange);
1610 }
1611
1612 // Returns true if 'Range' intersects with one of the input ranges.
1613 bool affectsCharSourceRange(const CharSourceRange &Range) {
1614 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1615 E = Ranges.end();
1616 I != E; ++I) {
1617 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1618 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1619 return true;
1620 }
1621 return false;
1622 }
1623
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001624 static bool inputUsesCRLF(StringRef Text) {
1625 return Text.count('\r') * 2 > Text.count('\n');
1626 }
1627
Daniel Jasper352f0df2015-07-18 16:35:30 +00001628 bool
1629 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1630 for (const AnnotatedLine* Line : Lines) {
1631 if (hasCpp03IncompatibleFormat(Line->Children))
1632 return true;
1633 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1634 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1635 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1636 return true;
1637 if (Tok->is(TT_TemplateCloser) &&
1638 Tok->Previous->is(TT_TemplateCloser))
1639 return true;
1640 }
1641 }
1642 }
1643 return false;
1644 }
1645
1646 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1647 int AlignmentDiff = 0;
1648 for (const AnnotatedLine* Line : Lines) {
1649 AlignmentDiff += countVariableAlignments(Line->Children);
1650 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1651 if (!Tok->is(TT_PointerOrReference))
1652 continue;
1653 bool SpaceBefore =
1654 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1655 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1656 Tok->Next->WhitespaceRange.getEnd();
1657 if (SpaceBefore && !SpaceAfter)
1658 ++AlignmentDiff;
1659 if (!SpaceBefore && SpaceAfter)
1660 --AlignmentDiff;
1661 }
1662 }
1663 return AlignmentDiff;
1664 }
1665
Manuel Klimek71814b42013-10-11 21:25:45 +00001666 void
1667 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001668 bool HasBinPackedFunction = false;
1669 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001670 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001671 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001672 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001673 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001674 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001675 if (Tok->PackingKind == PPK_BinPacked)
1676 HasBinPackedFunction = true;
1677 if (Tok->PackingKind == PPK_OnePerLine)
1678 HasOnePerLineFunction = true;
1679
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001680 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001681 }
1682 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001683 if (Style.DerivePointerAlignment)
1684 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1685 ? FormatStyle::PAS_Left
1686 : FormatStyle::PAS_Right;
1687 if (Style.Standard == FormatStyle::LS_Auto)
1688 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1689 ? FormatStyle::LS_Cpp11
1690 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001691 BinPackInconclusiveFunctions =
1692 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001693 }
1694
Craig Topperfb6b25b2014-03-15 04:29:04 +00001695 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001696 assert(!UnwrappedLines.empty());
1697 UnwrappedLines.back().push_back(TheLine);
1698 }
1699
Craig Topperfb6b25b2014-03-15 04:29:04 +00001700 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001701 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001702 }
1703
1704 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001705 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001706 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001707 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001708 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001709 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001710
1711 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001712 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001713};
1714
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001715struct IncludeDirective {
1716 StringRef Filename;
1717 StringRef Text;
1718 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001719 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001720};
1721
Craig Topperaf35e852013-06-30 22:29:28 +00001722} // end anonymous namespace
1723
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001724// Determines whether 'Ranges' intersects with ('Start', 'End').
1725static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1726 unsigned End) {
1727 for (auto Range : Ranges) {
1728 if (Range.getOffset() < End &&
1729 Range.getOffset() + Range.getLength() > Start)
1730 return true;
1731 }
1732 return false;
1733}
1734
1735// Sorts a block of includes given by 'Includes' alphabetically adding the
1736// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1737// order.
1738static void sortIncludes(const FormatStyle &Style,
1739 const SmallVectorImpl<IncludeDirective> &Includes,
1740 ArrayRef<tooling::Range> Ranges, StringRef FileName,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001741 tooling::Replacements &Replaces, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001742 if (!affectsRange(Ranges, Includes.front().Offset,
1743 Includes.back().Offset + Includes.back().Text.size()))
1744 return;
1745 SmallVector<unsigned, 16> Indices;
1746 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1747 Indices.push_back(i);
1748 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001749 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1750 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001751 });
1752
1753 // If the #includes are out of order, we generate a single replacement fixing
1754 // the entire block. Otherwise, no replacement is generated.
1755 bool OutOfOrder = false;
1756 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1757 if (Indices[i] != i) {
1758 OutOfOrder = true;
1759 break;
1760 }
1761 }
1762 if (!OutOfOrder)
1763 return;
1764
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001765 std::string result;
1766 bool CursorMoved = false;
1767 for (unsigned Index : Indices) {
1768 if (!result.empty())
1769 result += "\n";
1770 result += Includes[Index].Text;
1771
1772 if (Cursor && !CursorMoved) {
1773 unsigned Start = Includes[Index].Offset;
1774 unsigned End = Start + Includes[Index].Text.size();
1775 if (*Cursor >= Start && *Cursor < End) {
1776 *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
1777 CursorMoved = true;
1778 }
1779 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001780 }
1781
1782 // Sorting #includes shouldn't change their total number of characters.
1783 // This would otherwise mess up 'Ranges'.
1784 assert(result.size() ==
1785 Includes.back().Offset + Includes.back().Text.size() -
1786 Includes.front().Offset);
1787
1788 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1789 result.size(), result));
1790}
1791
1792tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1793 ArrayRef<tooling::Range> Ranges,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001794 StringRef FileName, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001795 tooling::Replacements Replaces;
Daniel Jasperda446772015-11-16 12:38:56 +00001796 if (!Style.SortIncludes)
1797 return Replaces;
1798
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001799 unsigned Prev = 0;
1800 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001801 llvm::Regex IncludeRegex(
Nico Weberff063702015-10-21 17:13:45 +00001802 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001803 SmallVector<StringRef, 4> Matches;
1804 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001805
1806 // In compiled files, consider the first #include to be the main #include of
1807 // the file if it is not a system #include. This ensures that the header
1808 // doesn't have hidden dependencies
1809 // (http://llvm.org/docs/CodingStandards.html#include-style).
1810 //
1811 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1812 // cases where the first #include is unlikely to be the main header.
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001813 bool IsSource = FileName.endswith(".c") || FileName.endswith(".cc") ||
1814 FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1815 FileName.endswith(".cxx") || FileName.endswith(".m") ||
1816 FileName.endswith(".mm");
1817 StringRef FileStem = llvm::sys::path::stem(FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001818 bool FirstIncludeBlock = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001819
1820 // Create pre-compiled regular expressions for the #include categories.
1821 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001822 for (const auto &Category : Style.IncludeCategories)
1823 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001824
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001825 bool FormattingOff = false;
1826
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001827 for (;;) {
1828 auto Pos = Code.find('\n', SearchFrom);
1829 StringRef Line =
1830 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001831
1832 StringRef Trimmed = Line.trim();
1833 if (Trimmed == "// clang-format off")
1834 FormattingOff = true;
1835 else if (Trimmed == "// clang-format on")
1836 FormattingOff = false;
1837
1838 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001839 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001840 StringRef IncludeName = Matches[2];
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001841 int Category = INT_MAX;
1842 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1843 if (CategoryRegexs[i].match(IncludeName)) {
1844 Category = Style.IncludeCategories[i].Priority;
1845 break;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001846 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001847 }
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001848 if (IsSource && Category > 0 && FirstIncludeBlock &&
1849 IncludeName.startswith("\"")) {
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001850 StringRef HeaderStem =
1851 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
1852 if (FileStem.startswith(HeaderStem))
1853 Category = 0;
1854 }
Nico Weberff063702015-10-21 17:13:45 +00001855 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001856 } else if (!IncludesInBlock.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001857 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1858 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001859 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001860 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001861 }
1862 Prev = Pos + 1;
1863 }
1864 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1865 break;
1866 SearchFrom = Pos + 1;
1867 }
1868 if (!IncludesInBlock.empty())
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001869 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001870 return Replaces;
1871}
1872
Daniel Jasper23376252014-09-09 14:37:39 +00001873tooling::Replacements reformat(const FormatStyle &Style,
1874 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001875 ArrayRef<CharSourceRange> Ranges,
1876 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001877 FormatStyle Expanded = expandPresets(Style);
1878 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001879 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001880 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001881 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001882}
1883
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001884tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001885 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001886 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001887 if (Style.DisableFormat)
1888 return tooling::Replacements();
1889
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001890 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1891 new vfs::InMemoryFileSystem);
1892 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001893 DiagnosticsEngine Diagnostics(
1894 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1895 new DiagnosticOptions);
1896 SourceManager SourceMgr(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001897 InMemoryFileSystem->addFile(FileName, 0,
1898 llvm::MemoryBuffer::getMemBuffer(Code, FileName));
1899 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1900 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001901 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1902 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001903 for (const tooling::Range &Range : Ranges) {
1904 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1905 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001906 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1907 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001908 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001909}
1910
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001911LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001912 LangOptions LangOpts;
1913 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001914 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1915 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001916 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001917 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001918 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001919 LangOpts.Bool = 1;
1920 LangOpts.ObjC1 = 1;
1921 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001922 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001923 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001924 return LangOpts;
1925}
1926
Edwin Vaned544aa72013-09-30 13:31:48 +00001927const char *StyleOptionHelpDescription =
1928 "Coding style, currently supports:\n"
1929 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1930 "Use -style=file to load style configuration from\n"
1931 ".clang-format file located in one of the parent\n"
1932 "directories of the source file (or current\n"
1933 "directory for stdin).\n"
1934 "Use -style=\"{key: value, ...}\" to set specific\n"
1935 "parameters, e.g.:\n"
1936 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1937
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001938static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001939 if (FileName.endswith(".java")) {
1940 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001941 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1942 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001943 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001944 } else if (FileName.endswith_lower(".proto") ||
1945 FileName.endswith_lower(".protodevel")) {
1946 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001947 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001948 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001949}
1950
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001951FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1952 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001953 FormatStyle Style = getLLVMStyle();
1954 Style.Language = getLanguageByFileName(FileName);
1955 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001956 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1957 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001958 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001959 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001960
1961 if (StyleName.startswith("{")) {
1962 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001963 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001964 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1965 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001966 }
1967 return Style;
1968 }
1969
1970 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001971 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001972 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1973 << " style\n";
1974 return Style;
1975 }
1976
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001977 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001978 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001979 SmallString<128> Path(FileName);
1980 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001981 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001982 Directory = llvm::sys::path::parent_path(Directory)) {
1983 if (!llvm::sys::fs::is_directory(Directory))
1984 continue;
1985 SmallString<128> ConfigFile(Directory);
1986
1987 llvm::sys::path::append(ConfigFile, ".clang-format");
1988 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1989 bool IsFile = false;
1990 // Ignore errors from is_regular_file: we only need to know if we can read
1991 // the file or not.
1992 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1993
1994 if (!IsFile) {
1995 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1996 ConfigFile = Directory;
1997 llvm::sys::path::append(ConfigFile, "_clang-format");
1998 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1999 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2000 }
2001
2002 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002003 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2004 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2005 if (std::error_code EC = Text.getError()) {
2006 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002007 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002008 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002009 if (std::error_code ec =
2010 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002011 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002012 if (!UnsuitableConfigFiles.empty())
2013 UnsuitableConfigFiles.append(", ");
2014 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002015 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002016 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002017 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2018 << "\n";
2019 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002020 }
2021 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2022 return Style;
2023 }
2024 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002025 if (!UnsuitableConfigFiles.empty()) {
2026 llvm::errs() << "Configuration file(s) do(es) not support "
2027 << getLanguageName(Style.Language) << ": "
2028 << UnsuitableConfigFiles << "\n";
2029 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002030 return Style;
2031}
2032
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002033} // namespace format
2034} // namespace clang