blob: acd520ef546395b1b282e4205c6215acafa129b4 [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);
Daniel Jasper498f5582015-12-25 08:53:31 +000050 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000051 }
52};
53
54template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
55 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
56 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
57 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
58 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
59 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
60 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
61 }
62};
63
64template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
65 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
66 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
67 IO.enumCase(Value, "false", FormatStyle::UT_Never);
68 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
69 IO.enumCase(Value, "true", FormatStyle::UT_Always);
70 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
71 }
72};
73
Daniel Jasperd74cf402014-04-08 12:46:38 +000074template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
75 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
76 IO.enumCase(Value, "None", FormatStyle::SFS_None);
77 IO.enumCase(Value, "false", FormatStyle::SFS_None);
78 IO.enumCase(Value, "All", FormatStyle::SFS_All);
79 IO.enumCase(Value, "true", FormatStyle::SFS_All);
80 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000081 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000082 }
83};
84
Daniel Jasperac043c92014-09-15 11:11:00 +000085template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
86 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
87 IO.enumCase(Value, "All", FormatStyle::BOS_All);
88 IO.enumCase(Value, "true", FormatStyle::BOS_All);
89 IO.enumCase(Value, "None", FormatStyle::BOS_None);
90 IO.enumCase(Value, "false", FormatStyle::BOS_None);
91 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
92 }
93};
94
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000095template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
96 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
97 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
98 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000099 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000100 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
101 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000102 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000103 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000104 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 }
106};
107
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000108template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000109struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
110 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
111 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
112 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
113 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
114 IO.enumCase(Value, "TopLevelDefinitions",
115 FormatStyle::RTBS_TopLevelDefinitions);
116 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
117 }
118};
119
120template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000121struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
122 static void
123 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000124 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
125 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
126 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
127
128 // For backward compatibility.
129 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
130 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
131 }
132};
133
Alexander Kornienkod6538332013-05-07 15:32:14 +0000134template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000135struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000136 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000137 FormatStyle::NamespaceIndentationKind &Value) {
138 IO.enumCase(Value, "None", FormatStyle::NI_None);
139 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
140 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000141 }
142};
143
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000144template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
145 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
146 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
147 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
148 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
149
150 // For backward compatibility.
151 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
152 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
153 }
154};
155
Jacques Pienaarfc275112015-02-18 23:48:37 +0000156template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
157 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000158 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
159 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
160 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
161
Alp Toker958027b2014-07-14 19:42:55 +0000162 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000163 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
164 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
165 }
166};
167
168template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000169struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000170 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000171 FormatStyle::SpaceBeforeParensOptions &Value) {
172 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000173 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000174 FormatStyle::SBPO_ControlStatements);
175 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000176
177 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000178 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
179 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000180 }
181};
182
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000183template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000184 static void mapping(IO &IO, FormatStyle &Style) {
185 // When reading, read the language first, we need it for getPredefinedStyle.
186 IO.mapOptional("Language", Style.Language);
187
Alexander Kornienko49149672013-05-10 11:56:10 +0000188 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000189 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
190 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000191 ArrayRef<StringRef> Styles(StylesArray);
192 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
193 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000194 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000195 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000196 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000197 IO.mapOptional("# BasedOnStyle", StyleName);
198 break;
199 }
200 }
201 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 StringRef BasedOnStyle;
203 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000204 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000205 FormatStyle::LanguageKind OldLanguage = Style.Language;
206 FormatStyle::LanguageKind Language =
207 ((FormatStyle *)IO.getContext())->Language;
208 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000209 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
210 return;
211 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000212 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000213 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000214 }
215
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000216 // For backward compatibility.
217 if (!IO.outputting()) {
218 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
219 IO.mapOptional("IndentFunctionDeclarationAfterType",
220 Style.IndentWrappedFunctionNames);
221 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
222 IO.mapOptional("SpaceAfterControlStatementKeyword",
223 Style.SpaceBeforeParens);
224 }
225
Alexander Kornienkod6538332013-05-07 15:32:14 +0000226 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000227 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000228 IO.mapOptional("AlignConsecutiveAssignments",
229 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000230 IO.mapOptional("AlignConsecutiveDeclarations",
231 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000232 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000233 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000234 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
236 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000237 IO.mapOptional("AllowShortBlocksOnASingleLine",
238 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000239 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
240 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000241 IO.mapOptional("AllowShortFunctionsOnASingleLine",
242 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000243 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
244 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000245 IO.mapOptional("AllowShortLoopsOnASingleLine",
246 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000247 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
248 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000249 IO.mapOptional("AlwaysBreakAfterReturnType",
250 Style.AlwaysBreakAfterReturnType);
251 // If AlwaysBreakAfterDefinitionReturnType was specified but
252 // AlwaysBreakAfterReturnType was not, initialize the latter from the
253 // former for backwards compatibility.
254 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
255 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
256 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
257 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
258 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
259 FormatStyle::DRTBS_TopLevel)
260 Style.AlwaysBreakAfterReturnType =
261 FormatStyle::RTBS_TopLevelDefinitions;
262 }
263
Alexander Kornienko58611712013-07-04 12:02:44 +0000264 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
265 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000266 IO.mapOptional("AlwaysBreakTemplateDeclarations",
267 Style.AlwaysBreakTemplateDeclarations);
268 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
269 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000270 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000271 IO.mapOptional("BreakBeforeBinaryOperators",
272 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000273 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000274 IO.mapOptional("BreakBeforeTernaryOperators",
275 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000276 IO.mapOptional("BreakConstructorInitializersBeforeComma",
277 Style.BreakConstructorInitializersBeforeComma);
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000278 IO.mapOptional("BreakAfterJavaFieldAnnotations",
279 Style.BreakAfterJavaFieldAnnotations);
280 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000281 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000282 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000283 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
284 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000285 IO.mapOptional("ConstructorInitializerIndentWidth",
286 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000287 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
288 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000289 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000290 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000291 IO.mapOptional("ExperimentalAutoDetectBinPacking",
292 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000293 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000294 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000295 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000296 IO.mapOptional("IndentWidth", Style.IndentWidth);
297 IO.mapOptional("IndentWrappedFunctionNames",
298 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000299 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
300 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000301 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
302 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000303 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000304 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000305 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000306 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000307 IO.mapOptional("ObjCSpaceBeforeProtocolList",
308 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000309 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
310 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000311 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000312 IO.mapOptional("PenaltyBreakFirstLessLess",
313 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000314 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000315 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
316 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
317 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000318 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000319 IO.mapOptional("ReflowComments", Style.ReflowComments);
320 IO.mapOptional("SortIncludes", Style.SortIncludes);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000321 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000322 IO.mapOptional("SpaceBeforeAssignmentOperators",
323 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000324 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
325 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
326 IO.mapOptional("SpacesBeforeTrailingComments",
327 Style.SpacesBeforeTrailingComments);
328 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
329 IO.mapOptional("SpacesInContainerLiterals",
330 Style.SpacesInContainerLiterals);
331 IO.mapOptional("SpacesInCStyleCastParentheses",
332 Style.SpacesInCStyleCastParentheses);
333 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
334 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
335 IO.mapOptional("Standard", Style.Standard);
336 IO.mapOptional("TabWidth", Style.TabWidth);
337 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000338 }
339};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000340
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000341template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
342 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
343 IO.mapOptional("AfterClass", Wrapping.AfterClass);
344 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
345 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
346 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
347 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
348 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
349 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
350 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
351 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
352 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
353 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
354 }
355};
356
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000357template <> struct MappingTraits<FormatStyle::IncludeCategory> {
358 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
359 IO.mapOptional("Regex", Category.Regex);
360 IO.mapOptional("Priority", Category.Priority);
361 }
362};
363
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000364// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000365// IO.getContext() should contain a pointer to the FormatStyle structure, that
366// will be used to get default values for missing keys.
367// If the first element has no Language specified, it will be treated as the
368// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000369template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000370 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
371 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000372 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000373 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000374 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000375 if (Index >= Seq.size()) {
376 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000377 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000378 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000379 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000380 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000381 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000382 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000383 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000384 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000385 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000386 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000387 }
388};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000389} // namespace yaml
390} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000391
Daniel Jasperf7935112012-12-03 18:12:45 +0000392namespace clang {
393namespace format {
394
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000395const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000396 static ParseErrorCategory C;
397 return C;
398}
399std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000400 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000401}
402
403const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
404 return "clang-format.parse_error";
405}
406
407std::string ParseErrorCategory::message(int EV) const {
408 switch (static_cast<ParseError>(EV)) {
409 case ParseError::Success:
410 return "Success";
411 case ParseError::Error:
412 return "Invalid argument";
413 case ParseError::Unsuitable:
414 return "Unsuitable";
415 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000416 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000417}
418
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000419static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000420 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
421 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000422 FormatStyle Expanded = Style;
423 Expanded.BraceWrapping = {false, false, false, false, false, false,
424 false, false, false, false, false};
425 switch (Style.BreakBeforeBraces) {
426 case FormatStyle::BS_Linux:
427 Expanded.BraceWrapping.AfterClass = true;
428 Expanded.BraceWrapping.AfterFunction = true;
429 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000430 break;
431 case FormatStyle::BS_Mozilla:
432 Expanded.BraceWrapping.AfterClass = true;
433 Expanded.BraceWrapping.AfterEnum = true;
434 Expanded.BraceWrapping.AfterFunction = true;
435 Expanded.BraceWrapping.AfterStruct = true;
436 Expanded.BraceWrapping.AfterUnion = true;
437 break;
438 case FormatStyle::BS_Stroustrup:
439 Expanded.BraceWrapping.AfterFunction = true;
440 Expanded.BraceWrapping.BeforeCatch = true;
441 Expanded.BraceWrapping.BeforeElse = true;
442 break;
443 case FormatStyle::BS_Allman:
444 Expanded.BraceWrapping.AfterClass = true;
445 Expanded.BraceWrapping.AfterControlStatement = true;
446 Expanded.BraceWrapping.AfterEnum = true;
447 Expanded.BraceWrapping.AfterFunction = true;
448 Expanded.BraceWrapping.AfterNamespace = true;
449 Expanded.BraceWrapping.AfterObjCDeclaration = true;
450 Expanded.BraceWrapping.AfterStruct = true;
451 Expanded.BraceWrapping.BeforeCatch = true;
452 Expanded.BraceWrapping.BeforeElse = true;
453 break;
454 case FormatStyle::BS_GNU:
455 Expanded.BraceWrapping = {true, true, true, true, true, true,
456 true, true, true, true, true};
457 break;
458 case FormatStyle::BS_WebKit:
459 Expanded.BraceWrapping.AfterFunction = true;
460 break;
461 default:
462 break;
463 }
464 return Expanded;
465}
466
Daniel Jasperf7935112012-12-03 18:12:45 +0000467FormatStyle getLLVMStyle() {
468 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000469 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000470 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000471 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000472 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000473 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000474 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000475 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000476 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000477 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000478 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000479 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000480 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000481 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000482 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000483 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000484 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000485 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000486 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000487 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000488 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000489 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000490 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000491 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000492 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
493 false, false, false, false, false};
Nico Weber2cd92f12015-10-15 16:03:01 +0000494 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000495 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
496 LLVMStyle.BreakStringLiterals = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000497 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000498 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000499 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000500 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000501 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000502 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000503 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000504 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000505 LLVMStyle.ForEachMacros.push_back("foreach");
506 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
507 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000508 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
509 {"^(<|\"(gtest|isl|json)/)", 3},
510 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000511 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000512 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000513 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000514 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000515 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000516 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000517 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000518 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000519 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000520 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000521 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000522 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000523 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000524 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000525 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000526 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000527 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000528 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000529 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000530 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000531 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000532 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000533 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000534 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000535
Daniel Jasper19a541e2013-12-19 16:45:34 +0000536 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000537 LLVMStyle.PenaltyBreakFirstLessLess = 120;
538 LLVMStyle.PenaltyBreakString = 1000;
539 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000540 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000541 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000542
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000543 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000544 LLVMStyle.SortIncludes = true;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000545
Daniel Jasperf7935112012-12-03 18:12:45 +0000546 return LLVMStyle;
547}
548
Nico Weber514ecc82014-02-02 20:50:45 +0000549FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000550 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000551 GoogleStyle.Language = Language;
552
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000554 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000555 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000556 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000557 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000558 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000559 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000560 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000561 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000562 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000563 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000564 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000565 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000566 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000567 GoogleStyle.SpacesBeforeTrailingComments = 2;
568 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000569
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000570 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000571 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000572
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000573 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000574 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000575 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000576 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000577 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000578 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000579 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000580 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
581 GoogleStyle.ColumnLimit = 100;
582 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000583 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000584 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000585 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000586 GoogleStyle.AlignOperands = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000587 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
588 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000589 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasperd196abb2016-01-08 08:14:58 +0000590 GoogleStyle.CommentPragmas = "@(export|visibility) {";
Daniel Jasper8f83a902014-05-09 10:28:58 +0000591 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000592 GoogleStyle.SpacesInContainerLiterals = false;
593 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000594 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000595 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000596 }
597
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 return GoogleStyle;
599}
600
Nico Weber514ecc82014-02-02 20:50:45 +0000601FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
602 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000603 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000604 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000605 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000606 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000607 ChromiumStyle.IndentWidth = 4;
Nico Weber450425c2014-11-26 16:43:18 +0000608 } else {
609 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
610 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
611 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
612 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
613 ChromiumStyle.BinPackParameters = false;
614 ChromiumStyle.DerivePointerAlignment = false;
615 }
Nico Weberb10423a2015-12-22 22:42:56 +0000616 ChromiumStyle.SortIncludes = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000617 return ChromiumStyle;
618}
619
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000620FormatStyle getMozillaStyle() {
621 FormatStyle MozillaStyle = getLLVMStyle();
622 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000623 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Zachary Turner448592e2015-12-18 22:20:15 +0000624 MozillaStyle.AlwaysBreakAfterReturnType =
625 FormatStyle::RTBS_TopLevelDefinitions;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000626 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
627 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000628 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000629 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000630 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
631 MozillaStyle.ConstructorInitializerIndentWidth = 2;
632 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000633 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000634 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000635 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000636 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
637 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000638 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000639 return MozillaStyle;
640}
641
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000642FormatStyle getWebKitStyle() {
643 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000644 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000645 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000646 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000647 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000648 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000649 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000650 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000651 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000652 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000653 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000654 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000655 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000656 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000657 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000658 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000659 return Style;
660}
661
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000662FormatStyle getGNUStyle() {
663 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000664 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000665 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000666 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000667 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000668 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000669 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000670 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000671 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000672 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000673 return Style;
674}
675
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000676FormatStyle getNoStyle() {
677 FormatStyle NoStyle = getLLVMStyle();
678 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000679 NoStyle.SortIncludes = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000680 return NoStyle;
681}
682
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000683bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
684 FormatStyle *Style) {
685 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000686 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000687 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000688 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000689 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000690 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000691 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000692 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000693 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000694 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000695 } else if (Name.equals_lower("gnu")) {
696 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000697 } else if (Name.equals_lower("none")) {
698 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000699 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000700 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000701 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000702
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000703 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000704 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000705}
706
Rafael Espindolac0809172014-06-12 14:02:15 +0000707std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000708 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000709 FormatStyle::LanguageKind Language = Style->Language;
710 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000711 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000712 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000713
714 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000715 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000716 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
717 // values for the fields, keys for which are missing from the configuration.
718 // Mapping also uses the context to get the language to find the correct
719 // base style.
720 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000721 Input >> Styles;
722 if (Input.error())
723 return Input.error();
724
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000725 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000726 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000727 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000728 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000729 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000730 for (unsigned j = 0; j < i; ++j) {
731 if (Styles[i].Language == Styles[j].Language) {
732 DEBUG(llvm::dbgs()
733 << "Duplicate languages in the config file on positions " << j
734 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000735 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000736 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000737 }
738 }
739 // Look for a suitable configuration starting from the end, so we can
740 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000741 // configuration (which can only be at slot 0) after it.
742 for (int i = Styles.size() - 1; i >= 0; --i) {
743 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000744 Styles[i].Language == FormatStyle::LK_None) {
745 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000746 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000747 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000748 }
749 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000750 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000751}
752
753std::string configurationAsText(const FormatStyle &Style) {
754 std::string Text;
755 llvm::raw_string_ostream Stream(Text);
756 llvm::yaml::Output Output(Stream);
757 // We use the same mapping method for input and output, so we need a non-const
758 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000759 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000760 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000761 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000762}
763
Craig Topperaf35e852013-06-30 22:29:28 +0000764namespace {
765
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000766class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000767public:
Daniel Jasper23376252014-09-09 14:37:39 +0000768 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000769 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000770 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000771 LessStashed(false), Column(0), TrailingWhitespace(0),
772 SourceMgr(SourceMgr), ID(ID), Style(Style),
773 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000774 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
775 MacroBlockBeginRegex(Style.MacroBlockBegin),
776 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000777 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
778 getFormattingLangOpts(Style)));
779 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000780
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000781 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000782 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
783 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000784 }
785
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000786 ArrayRef<FormatToken *> lex() {
787 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000788 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000789 do {
790 Tokens.push_back(getNextToken());
Daniel Jasper265309e2015-10-18 07:02:28 +0000791 if (Style.Language == FormatStyle::LK_JavaScript)
792 tryParseJSRegexLiteral();
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000793 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000794 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000795 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000796 } while (Tokens.back()->Tok.isNot(tok::eof));
797 return Tokens;
798 }
799
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000800 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000801
802private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000803 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000804 if (tryMerge_TMacro())
805 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000806 if (tryMergeConflictMarkers())
807 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000808 if (tryMergeLessLess())
809 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000810
811 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000812 if (tryMergeTemplateString())
813 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000814
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000815 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
816 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
817 tok::equal};
818 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
819 tok::greaterequal};
820 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000821 // FIXME: Investigate what token type gives the correct operator priority.
822 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000823 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000824 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000825 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000826 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000827 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000828 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000829 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000830 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000831 }
832
Jacques Pienaarfc275112015-02-18 23:48:37 +0000833 bool tryMergeLessLess() {
834 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000835 if (Tokens.size() < 3)
836 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000837
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000838 bool FourthTokenIsLess = false;
839 if (Tokens.size() > 3)
840 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000841
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000842 auto First = Tokens.end() - 3;
843 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
844 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000845 return false;
846
847 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000848 if (First[1]->WhitespaceRange.getBegin() !=
849 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000850 return false;
851
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000852 First[0]->Tok.setKind(tok::lessless);
853 First[0]->TokenText = "<<";
854 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000855 Tokens.erase(Tokens.end() - 2);
856 return true;
857 }
858
Manuel Klimek79e06082015-05-21 12:23:34 +0000859 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000860 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000861 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000862
863 SmallVectorImpl<FormatToken *>::const_iterator First =
864 Tokens.end() - Kinds.size();
865 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000866 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000867 unsigned AddLength = 0;
868 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000869 if (!First[i]->is(Kinds[i]) ||
870 First[i]->WhitespaceRange.getBegin() !=
871 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000872 return false;
873 AddLength += First[i]->TokenText.size();
874 }
875 Tokens.resize(Tokens.size() - Kinds.size() + 1);
876 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
877 First[0]->TokenText.size() + AddLength);
878 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000879 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000880 return true;
881 }
882
Daniel Jasper265309e2015-10-18 07:02:28 +0000883 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
884 bool precedesOperand(FormatToken *Tok) {
885 // NB: This is not entirely correct, as an r_paren can introduce an operand
886 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
887 // corner case to not matter in practice, though.
888 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
889 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
890 tok::colon, tok::question, tok::tilde) ||
891 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
892 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
893 tok::kw_typeof, Keywords.kw_instanceof,
894 Keywords.kw_in) ||
895 Tok->isBinaryOperator();
896 }
897
898 bool canPrecedeRegexLiteral(FormatToken *Prev) {
899 if (!Prev)
900 return true;
901
902 // Regex literals can only follow after prefix unary operators, not after
903 // postfix unary operators. If the '++' is followed by a non-operand
904 // introducing token, the slash here is the operand and not the start of a
905 // regex.
906 if (Prev->isOneOf(tok::plusplus, tok::minusminus))
907 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
908
909 // The previous token must introduce an operand location where regex
910 // literals can occur.
911 if (!precedesOperand(Prev))
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000912 return false;
Daniel Jasper265309e2015-10-18 07:02:28 +0000913
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000914 return true;
915 }
916
Daniel Jasper265309e2015-10-18 07:02:28 +0000917 // Tries to parse a JavaScript Regex literal starting at the current token,
918 // if that begins with a slash and is in a location where JavaScript allows
919 // regex literals. Changes the current token to a regex literal and updates
920 // its text if successful.
921 void tryParseJSRegexLiteral() {
922 FormatToken *RegexToken = Tokens.back();
923 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
924 return;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000925
Daniel Jasper265309e2015-10-18 07:02:28 +0000926 FormatToken *Prev = nullptr;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000927 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
Daniel Jasper265309e2015-10-18 07:02:28 +0000928 // NB: Because previous pointers are not initialized yet, this cannot use
929 // Token.getPreviousNonComment.
930 if ((*I)->isNot(tok::comment)) {
931 Prev = *I;
932 break;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000933 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000934 }
Daniel Jasper265309e2015-10-18 07:02:28 +0000935
936 if (!canPrecedeRegexLiteral(Prev))
937 return;
938
939 // 'Manually' lex ahead in the current file buffer.
940 const char *Offset = Lex->getBufferLocation();
941 const char *RegexBegin = Offset - RegexToken->TokenText.size();
942 StringRef Buffer = Lex->getBuffer();
943 bool InCharacterClass = false;
944 bool HaveClosingSlash = false;
945 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
946 // Regular expressions are terminated with a '/', which can only be
947 // escaped using '\' or a character class between '[' and ']'.
948 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
949 switch (*Offset) {
950 case '\\':
951 // Skip the escaped character.
952 ++Offset;
953 break;
954 case '[':
955 InCharacterClass = true;
956 break;
957 case ']':
958 InCharacterClass = false;
959 break;
960 case '/':
961 if (!InCharacterClass)
962 HaveClosingSlash = true;
963 break;
964 }
965 }
966
967 RegexToken->Type = TT_RegexLiteral;
968 // Treat regex literals like other string_literals.
969 RegexToken->Tok.setKind(tok::string_literal);
970 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
971 RegexToken->ColumnWidth = RegexToken->TokenText.size();
972
973 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000974 }
975
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000976 bool tryMergeTemplateString() {
977 if (Tokens.size() < 2)
978 return false;
979
980 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000981 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000982 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
983 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000984 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
985 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000986 return false;
987 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
988 // Unknown token that's not actually a backtick, or a comment that doesn't
989 // contain a backtick.
990 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000991 return false;
992
993 unsigned TokenCount = 0;
994 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000995 unsigned EndColumnInFirstLine =
996 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000997 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
998 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000999 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001000 IsMultiline = true;
1001
1002 // If there was a preceding template string, this must be the start of a
1003 // template string, not the end.
1004 if (I[0]->is(TT_TemplateString))
1005 return false;
1006
1007 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
1008 // Keep track of the rhs offset of the last token to wrap across lines -
1009 // its the rhs offset of the first line of the template string, used to
1010 // determine its width.
1011 if (I[0]->IsMultiline)
1012 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
1013 // If the token has newlines, the token before it (if it exists) is the
1014 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +00001015 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001016 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001017 IsMultiline = true;
1018 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001019 continue;
1020 }
1021
1022 Tokens.resize(Tokens.size() - TokenCount);
1023 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +00001024 const char *EndOffset =
1025 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
1026 if (CommentBacktickPos != 0) {
1027 // If the backtick was not the first character (e.g. in a comment),
1028 // re-lex after the backtick position.
1029 SourceLocation Loc = EndBacktick->Tok.getLocation();
1030 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
1031 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001032 Tokens.back()->TokenText =
1033 StringRef(Tokens.back()->TokenText.data(),
1034 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +00001035
1036 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
1037 if (EndOriginalColumn == 0) {
1038 SourceLocation Loc = EndBacktick->Tok.getLocation();
1039 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
1040 }
1041 // If the ` is further down within the token (e.g. in a comment).
1042 EndOriginalColumn += CommentBacktickPos;
1043
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001044 if (IsMultiline) {
1045 // ColumnWidth is from backtick to last token in line.
1046 // LastLineColumnWidth is 0 to backtick.
1047 // x = `some content
1048 // until here`;
1049 Tokens.back()->ColumnWidth =
1050 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001051 // +1 for the ` itself.
1052 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001053 Tokens.back()->IsMultiline = true;
1054 } else {
1055 // Token simply spans from start to end, +1 for the ` itself.
1056 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001057 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001058 }
1059 return true;
1060 }
1061 return false;
1062 }
1063
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001064 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001065 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001066 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001067 FormatToken *Last = Tokens.back();
1068 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001069 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001070
1071 FormatToken *String = Tokens[Tokens.size() - 2];
1072 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001073 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001074
1075 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001076 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001077
1078 FormatToken *Macro = Tokens[Tokens.size() - 4];
1079 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001080 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001081
1082 const char *Start = Macro->TokenText.data();
1083 const char *End = Last->TokenText.data() + Last->TokenText.size();
1084 String->TokenText = StringRef(Start, End - Start);
1085 String->IsFirst = Macro->IsFirst;
1086 String->LastNewlineOffset = Macro->LastNewlineOffset;
1087 String->WhitespaceRange = Macro->WhitespaceRange;
1088 String->OriginalColumn = Macro->OriginalColumn;
1089 String->ColumnWidth = encoding::columnWidthWithTabs(
1090 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001091 String->NewlinesBefore = Macro->NewlinesBefore;
1092 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001093
1094 Tokens.pop_back();
1095 Tokens.pop_back();
1096 Tokens.pop_back();
1097 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001098 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001099 }
1100
Manuel Klimek68b03042014-04-14 09:14:11 +00001101 bool tryMergeConflictMarkers() {
1102 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1103 return false;
1104
1105 // Conflict lines look like:
1106 // <marker> <text from the vcs>
1107 // For example:
1108 // >>>>>>> /file/in/file/system at revision 1234
1109 //
1110 // We merge all tokens in a line that starts with a conflict marker
1111 // into a single token with a special token type that the unwrapped line
1112 // parser will use to correctly rebuild the underlying code.
1113
1114 FileID ID;
1115 // Get the position of the first token in the line.
1116 unsigned FirstInLineOffset;
1117 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1118 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1119 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1120 // Calculate the offset of the start of the current line.
1121 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1122 if (LineOffset == StringRef::npos) {
1123 LineOffset = 0;
1124 } else {
1125 ++LineOffset;
1126 }
1127
1128 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1129 StringRef LineStart;
1130 if (FirstSpace == StringRef::npos) {
1131 LineStart = Buffer.substr(LineOffset);
1132 } else {
1133 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1134 }
1135
1136 TokenType Type = TT_Unknown;
1137 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1138 Type = TT_ConflictStart;
1139 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1140 LineStart == "====") {
1141 Type = TT_ConflictAlternative;
1142 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1143 Type = TT_ConflictEnd;
1144 }
1145
1146 if (Type != TT_Unknown) {
1147 FormatToken *Next = Tokens.back();
1148
1149 Tokens.resize(FirstInLineIndex + 1);
1150 // We do not need to build a complete token here, as we will skip it
1151 // during parsing anyway (as we must not touch whitespace around conflict
1152 // markers).
1153 Tokens.back()->Type = Type;
1154 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1155
1156 Tokens.push_back(Next);
1157 return true;
1158 }
1159
1160 return false;
1161 }
1162
Jacques Pienaarfc275112015-02-18 23:48:37 +00001163 FormatToken *getStashedToken() {
1164 // Create a synthesized second '>' or '<' token.
1165 Token Tok = FormatTok->Tok;
1166 StringRef TokenText = FormatTok->TokenText;
1167
1168 unsigned OriginalColumn = FormatTok->OriginalColumn;
1169 FormatTok = new (Allocator.Allocate()) FormatToken;
1170 FormatTok->Tok = Tok;
1171 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001172 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1173 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001174 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1175 FormatTok->TokenText = TokenText;
1176 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001177 FormatTok->OriginalColumn = OriginalColumn + 1;
1178
Jacques Pienaarfc275112015-02-18 23:48:37 +00001179 return FormatTok;
1180 }
1181
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001182 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001183 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001185 return getStashedToken();
1186 }
1187 if (LessStashed) {
1188 LessStashed = false;
1189 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001190 }
1191
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001192 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001193 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001194 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001195 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001196 FormatTok->IsFirst = IsFirstToken;
1197 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001198
1199 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001200 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001201 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001202 StringRef Text = FormatTok->TokenText;
1203 auto EscapesNewline = [&](int pos) {
1204 // A '\r' here is just part of '\r\n'. Skip it.
1205 if (pos >= 0 && Text[pos] == '\r')
1206 --pos;
1207 // See whether there is an odd number of '\' before this.
1208 unsigned count = 0;
1209 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001210 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001211 break;
1212 return count & 1;
1213 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001214 // FIXME: This miscounts tok:unknown tokens that are not just
1215 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001216 for (int i = 0, e = Text.size(); i != e; ++i) {
1217 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001218 case '\n':
1219 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001220 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001221 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1222 Column = 0;
1223 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001224 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001225 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1226 Column = 0;
1227 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001228 case '\f':
1229 case '\v':
1230 Column = 0;
1231 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001232 case ' ':
1233 ++Column;
1234 break;
1235 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001236 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001237 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001238 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001239 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001240 FormatTok->Type = TT_ImplicitStringLiteral;
1241 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001242 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001243 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001244 break;
1245 }
Daniel Jaspere1f72a62016-01-09 21:12:45 +00001246 if (FormatTok->Type == TT_ImplicitStringLiteral)
1247 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001248 }
1249
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001250 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001251 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001252 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001253
Daniel Jasper8369aa52013-07-16 20:28:33 +00001254 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001255 }
Manuel Klimekef920692013-01-07 07:56:50 +00001256
Manuel Klimek1abf7892013-01-04 23:34:14 +00001257 // In case the token starts with escaped newlines, we want to
1258 // take them into account as whitespace - this pattern is quite frequent
1259 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001260 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001261 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1262 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001263 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001264 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001265 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001266 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001267 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001268 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001269
1270 FormatTok->WhitespaceRange = SourceRange(
1271 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1272
Manuel Klimek31c85922013-08-29 15:21:40 +00001273 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001274
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001275 TrailingWhitespace = 0;
1276 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001277 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001278 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001279 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001280 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001281 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001282 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001283 FormatTok->Tok.setIdentifierInfo(&Info);
1284 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001285 if (Style.Language == FormatStyle::LK_Java &&
Daniel Jasper72a1b6a2015-12-22 15:47:56 +00001286 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1287 tok::kw_operator)) {
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001288 FormatTok->Tok.setKind(tok::identifier);
1289 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasper09840ef2015-11-20 15:58:50 +00001290 } else if (Style.Language == FormatStyle::LK_JavaScript &&
Daniel Jasper72a1b6a2015-12-22 15:47:56 +00001291 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1292 tok::kw_operator)) {
Daniel Jasper09840ef2015-11-20 15:58:50 +00001293 FormatTok->Tok.setKind(tok::identifier);
1294 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001295 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001296 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001297 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001298 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001299 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001300 } else if (FormatTok->Tok.is(tok::lessless)) {
1301 FormatTok->Tok.setKind(tok::less);
1302 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1303 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001304 }
1305
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001306 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001307
Alexander Kornienko39856b72013-09-10 09:38:25 +00001308 StringRef Text = FormatTok->TokenText;
1309 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001310 if (FirstNewlinePos == StringRef::npos) {
1311 // FIXME: ColumnWidth actually depends on the start column, we need to
1312 // take this into account when the token is moved.
1313 FormatTok->ColumnWidth =
1314 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1315 Column += FormatTok->ColumnWidth;
1316 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001317 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001318 // FIXME: ColumnWidth actually depends on the start column, we need to
1319 // take this into account when the token is moved.
1320 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1321 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1322
Alexander Kornienko39856b72013-09-10 09:38:25 +00001323 // The last line of the token always starts in column 0.
1324 // Thus, the length can be precomputed even in the presence of tabs.
1325 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1326 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1327 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001328 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001329 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001330
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001331 if (Style.Language == FormatStyle::LK_Cpp) {
1332 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1333 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1334 tok::pp_define) &&
1335 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1336 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1337 FormatTok->Type = TT_ForEachMacro;
1338 } else if (FormatTok->is(tok::identifier)) {
1339 if (MacroBlockBeginRegex.match(Text)) {
1340 FormatTok->Type = TT_MacroBlockBegin;
1341 } else if (MacroBlockEndRegex.match(Text)) {
1342 FormatTok->Type = TT_MacroBlockEnd;
1343 }
1344 }
1345 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001346
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001347 return FormatTok;
1348 }
1349
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001350 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001351 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001352 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001353 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001354 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001355 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001356 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001357 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001358 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001359 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001360 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001361 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001362 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001363 // Index (in 'Tokens') of the last token that starts a new line.
1364 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001365 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001366 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001367
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001368 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001369
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001370 llvm::Regex MacroBlockBeginRegex;
1371 llvm::Regex MacroBlockEndRegex;
1372
Daniel Jasper8369aa52013-07-16 20:28:33 +00001373 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001374 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001375 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1376 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001377 // For formatting, treat unterminated string literals like normal string
1378 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001379 if (Tok.is(tok::unknown)) {
1380 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1381 Tok.Tok.setKind(tok::string_literal);
1382 Tok.IsUnterminatedLiteral = true;
1383 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1384 Tok.TokenText == "''") {
1385 Tok.Tok.setKind(tok::char_constant);
1386 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001387 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001388
1389 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1390 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001391 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001392 }
1393
Daniel Jasper471894432014-08-06 13:40:26 +00001394 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001395
1396 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1397 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001398 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001399 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001400 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001401
1402 void resetLexer(unsigned Offset) {
1403 StringRef Buffer = SourceMgr.getBufferData(ID);
1404 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1405 getFormattingLangOpts(Style), Buffer.begin(),
1406 Buffer.begin() + Offset, Buffer.end()));
1407 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001408 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001409 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001410};
1411
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001412static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1413 switch (Language) {
1414 case FormatStyle::LK_Cpp:
1415 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001416 case FormatStyle::LK_Java:
1417 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001418 case FormatStyle::LK_JavaScript:
1419 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001420 case FormatStyle::LK_Proto:
1421 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001422 default:
1423 return "Unknown";
1424 }
1425}
1426
Daniel Jasperf7935112012-12-03 18:12:45 +00001427class Formatter : public UnwrappedLineConsumer {
1428public:
Daniel Jasper23376252014-09-09 14:37:39 +00001429 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001430 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001431 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1432 Whitespaces(SourceMgr, Style,
1433 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001434 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001435 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001436 DEBUG(llvm::dbgs() << "File encoding: "
1437 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1438 : "unknown")
1439 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001440 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1441 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001442 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001443
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001444 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001445 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001446 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001447
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001448 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1449 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001450 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001451 assert(UnwrappedLines.rbegin()->empty());
1452 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1453 ++Run) {
1454 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1455 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1456 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1457 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1458 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001459 tooling::Replacements RunResult =
1460 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001461 DEBUG({
1462 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1463 for (tooling::Replacements::iterator I = RunResult.begin(),
1464 E = RunResult.end();
1465 I != E; ++I) {
1466 llvm::dbgs() << I->toString() << "\n";
1467 }
1468 });
1469 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1470 delete AnnotatedLines[i];
1471 }
1472 Result.insert(RunResult.begin(), RunResult.end());
1473 Whitespaces.reset();
1474 }
1475 return Result;
1476 }
1477
1478 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001479 FormatTokenLexer &Tokens,
1480 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001481 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001482 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001483 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001484 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001485 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001486 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001487 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001488 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001489 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001490
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001491 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001492 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1493 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001494 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001495 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1496 IncompleteFormat)
1497 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001498 return Whitespaces.generateReplacements();
1499 }
1500
1501private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001502 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001503 // Returns \c true if at least one line between I and E or one of their
1504 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001505 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1506 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1507 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001508 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001509 while (I != E) {
1510 AnnotatedLine *Line = *I;
1511 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1512
1513 // If a line is part of a preprocessor directive, it needs to be formatted
1514 // if any token within the directive is affected.
1515 if (Line->InPPDirective) {
1516 FormatToken *Last = Line->Last;
1517 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1518 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1519 Last = (*PPEnd)->Last;
1520 ++PPEnd;
1521 }
1522
1523 if (affectsTokenRange(*Line->First, *Last,
1524 /*IncludeLeadingNewlines=*/false)) {
1525 SomeLineAffected = true;
1526 markAllAsAffected(I, PPEnd);
1527 }
1528 I = PPEnd;
1529 continue;
1530 }
1531
Daniel Jasper38c82402013-11-29 09:27:43 +00001532 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001533 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001534
Daniel Jasper38c82402013-11-29 09:27:43 +00001535 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001536 ++I;
1537 }
1538 return SomeLineAffected;
1539 }
1540
Daniel Jasper9c199562013-11-28 15:58:55 +00001541 // Determines whether 'Line' is affected by the SourceRanges given as input.
1542 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001543 bool nonPPLineAffected(AnnotatedLine *Line,
1544 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001545 bool SomeLineAffected = false;
1546 Line->ChildrenAffected =
1547 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1548 if (Line->ChildrenAffected)
1549 SomeLineAffected = true;
1550
1551 // Stores whether one of the line's tokens is directly affected.
1552 bool SomeTokenAffected = false;
1553 // Stores whether we need to look at the leading newlines of the next token
1554 // in order to determine whether it was affected.
1555 bool IncludeLeadingNewlines = false;
1556
1557 // Stores whether the first child line of any of this line's tokens is
1558 // affected.
1559 bool SomeFirstChildAffected = false;
1560
1561 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1562 // Determine whether 'Tok' was affected.
1563 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1564 SomeTokenAffected = true;
1565
1566 // Determine whether the first child of 'Tok' was affected.
1567 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1568 SomeFirstChildAffected = true;
1569
1570 IncludeLeadingNewlines = Tok->Children.empty();
1571 }
1572
1573 // Was this line moved, i.e. has it previously been on the same line as an
1574 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001575 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1576 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001577
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001578 bool IsContinuedComment =
1579 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1580 Line->First->NewlinesBefore < 2 && PreviousLine &&
1581 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001582
1583 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1584 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001585 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001586 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001587 }
1588 return SomeLineAffected;
1589 }
1590
Daniel Jasper5500f612013-11-25 11:08:59 +00001591 // Marks all lines between I and E as well as all their children as affected.
1592 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1593 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1594 while (I != E) {
1595 (*I)->Affected = true;
1596 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1597 ++I;
1598 }
1599 }
1600
1601 // Returns true if the range from 'First' to 'Last' intersects with one of the
1602 // input ranges.
1603 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1604 bool IncludeLeadingNewlines) {
1605 SourceLocation Start = First.WhitespaceRange.getBegin();
1606 if (!IncludeLeadingNewlines)
1607 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001608 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001609 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001610 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1611 return affectsCharSourceRange(Range);
1612 }
1613
1614 // Returns true if one of the input ranges intersect the leading empty lines
1615 // before 'Tok'.
1616 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1617 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1618 Tok.WhitespaceRange.getBegin(),
1619 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1620 return affectsCharSourceRange(EmptyLineRange);
1621 }
1622
1623 // Returns true if 'Range' intersects with one of the input ranges.
1624 bool affectsCharSourceRange(const CharSourceRange &Range) {
1625 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1626 E = Ranges.end();
1627 I != E; ++I) {
1628 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1629 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1630 return true;
1631 }
1632 return false;
1633 }
1634
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001635 static bool inputUsesCRLF(StringRef Text) {
1636 return Text.count('\r') * 2 > Text.count('\n');
1637 }
1638
Daniel Jasper352f0df2015-07-18 16:35:30 +00001639 bool
1640 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1641 for (const AnnotatedLine* Line : Lines) {
1642 if (hasCpp03IncompatibleFormat(Line->Children))
1643 return true;
1644 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1645 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1646 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1647 return true;
1648 if (Tok->is(TT_TemplateCloser) &&
1649 Tok->Previous->is(TT_TemplateCloser))
1650 return true;
1651 }
1652 }
1653 }
1654 return false;
1655 }
1656
1657 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1658 int AlignmentDiff = 0;
1659 for (const AnnotatedLine* Line : Lines) {
1660 AlignmentDiff += countVariableAlignments(Line->Children);
1661 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1662 if (!Tok->is(TT_PointerOrReference))
1663 continue;
1664 bool SpaceBefore =
1665 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1666 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1667 Tok->Next->WhitespaceRange.getEnd();
1668 if (SpaceBefore && !SpaceAfter)
1669 ++AlignmentDiff;
1670 if (!SpaceBefore && SpaceAfter)
1671 --AlignmentDiff;
1672 }
1673 }
1674 return AlignmentDiff;
1675 }
1676
Manuel Klimek71814b42013-10-11 21:25:45 +00001677 void
1678 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001679 bool HasBinPackedFunction = false;
1680 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001681 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001682 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001683 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001684 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001685 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001686 if (Tok->PackingKind == PPK_BinPacked)
1687 HasBinPackedFunction = true;
1688 if (Tok->PackingKind == PPK_OnePerLine)
1689 HasOnePerLineFunction = true;
1690
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001691 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001692 }
1693 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001694 if (Style.DerivePointerAlignment)
1695 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1696 ? FormatStyle::PAS_Left
1697 : FormatStyle::PAS_Right;
1698 if (Style.Standard == FormatStyle::LS_Auto)
1699 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1700 ? FormatStyle::LS_Cpp11
1701 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001702 BinPackInconclusiveFunctions =
1703 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001704 }
1705
Craig Topperfb6b25b2014-03-15 04:29:04 +00001706 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001707 assert(!UnwrappedLines.empty());
1708 UnwrappedLines.back().push_back(TheLine);
1709 }
1710
Craig Topperfb6b25b2014-03-15 04:29:04 +00001711 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001712 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001713 }
1714
1715 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001716 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001717 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001718 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001719 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001720 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001721
1722 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001723 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001724};
1725
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001726struct IncludeDirective {
1727 StringRef Filename;
1728 StringRef Text;
1729 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001730 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001731};
1732
Craig Topperaf35e852013-06-30 22:29:28 +00001733} // end anonymous namespace
1734
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001735// Determines whether 'Ranges' intersects with ('Start', 'End').
1736static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1737 unsigned End) {
1738 for (auto Range : Ranges) {
1739 if (Range.getOffset() < End &&
1740 Range.getOffset() + Range.getLength() > Start)
1741 return true;
1742 }
1743 return false;
1744}
1745
1746// Sorts a block of includes given by 'Includes' alphabetically adding the
1747// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1748// order.
1749static void sortIncludes(const FormatStyle &Style,
1750 const SmallVectorImpl<IncludeDirective> &Includes,
1751 ArrayRef<tooling::Range> Ranges, StringRef FileName,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001752 tooling::Replacements &Replaces, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001753 if (!affectsRange(Ranges, Includes.front().Offset,
1754 Includes.back().Offset + Includes.back().Text.size()))
1755 return;
1756 SmallVector<unsigned, 16> Indices;
1757 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1758 Indices.push_back(i);
1759 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001760 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1761 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001762 });
1763
1764 // If the #includes are out of order, we generate a single replacement fixing
1765 // the entire block. Otherwise, no replacement is generated.
1766 bool OutOfOrder = false;
1767 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1768 if (Indices[i] != i) {
1769 OutOfOrder = true;
1770 break;
1771 }
1772 }
1773 if (!OutOfOrder)
1774 return;
1775
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001776 std::string result;
1777 bool CursorMoved = false;
1778 for (unsigned Index : Indices) {
1779 if (!result.empty())
1780 result += "\n";
1781 result += Includes[Index].Text;
1782
1783 if (Cursor && !CursorMoved) {
1784 unsigned Start = Includes[Index].Offset;
1785 unsigned End = Start + Includes[Index].Text.size();
1786 if (*Cursor >= Start && *Cursor < End) {
1787 *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
1788 CursorMoved = true;
1789 }
1790 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001791 }
1792
1793 // Sorting #includes shouldn't change their total number of characters.
1794 // This would otherwise mess up 'Ranges'.
1795 assert(result.size() ==
1796 Includes.back().Offset + Includes.back().Text.size() -
1797 Includes.front().Offset);
1798
1799 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1800 result.size(), result));
1801}
1802
1803tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1804 ArrayRef<tooling::Range> Ranges,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001805 StringRef FileName, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001806 tooling::Replacements Replaces;
Daniel Jasperda446772015-11-16 12:38:56 +00001807 if (!Style.SortIncludes)
1808 return Replaces;
1809
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001810 unsigned Prev = 0;
1811 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001812 llvm::Regex IncludeRegex(
Nico Weberff063702015-10-21 17:13:45 +00001813 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001814 SmallVector<StringRef, 4> Matches;
1815 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001816
1817 // In compiled files, consider the first #include to be the main #include of
1818 // the file if it is not a system #include. This ensures that the header
1819 // doesn't have hidden dependencies
1820 // (http://llvm.org/docs/CodingStandards.html#include-style).
1821 //
1822 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1823 // cases where the first #include is unlikely to be the main header.
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001824 bool IsSource = FileName.endswith(".c") || FileName.endswith(".cc") ||
1825 FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1826 FileName.endswith(".cxx") || FileName.endswith(".m") ||
1827 FileName.endswith(".mm");
1828 StringRef FileStem = llvm::sys::path::stem(FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001829 bool FirstIncludeBlock = true;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001830 bool MainIncludeFound = false;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001831
1832 // Create pre-compiled regular expressions for the #include categories.
1833 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001834 for (const auto &Category : Style.IncludeCategories)
1835 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001836
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001837 bool FormattingOff = false;
1838
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001839 for (;;) {
1840 auto Pos = Code.find('\n', SearchFrom);
1841 StringRef Line =
1842 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001843
1844 StringRef Trimmed = Line.trim();
1845 if (Trimmed == "// clang-format off")
1846 FormattingOff = true;
1847 else if (Trimmed == "// clang-format on")
1848 FormattingOff = false;
1849
1850 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001851 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001852 StringRef IncludeName = Matches[2];
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001853 int Category = INT_MAX;
1854 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1855 if (CategoryRegexs[i].match(IncludeName)) {
1856 Category = Style.IncludeCategories[i].Priority;
1857 break;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001858 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001859 }
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001860 if (IsSource && !MainIncludeFound && Category > 0 &&
1861 FirstIncludeBlock && IncludeName.startswith("\"")) {
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001862 StringRef HeaderStem =
1863 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001864 if (FileStem.startswith(HeaderStem)) {
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001865 Category = 0;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001866 MainIncludeFound = true;
1867 }
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001868 }
Nico Weberff063702015-10-21 17:13:45 +00001869 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001870 } else if (!IncludesInBlock.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001871 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1872 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001873 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001874 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001875 }
1876 Prev = Pos + 1;
1877 }
1878 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1879 break;
1880 SearchFrom = Pos + 1;
1881 }
1882 if (!IncludesInBlock.empty())
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001883 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001884 return Replaces;
1885}
1886
Daniel Jasper23376252014-09-09 14:37:39 +00001887tooling::Replacements reformat(const FormatStyle &Style,
1888 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001889 ArrayRef<CharSourceRange> Ranges,
1890 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001891 FormatStyle Expanded = expandPresets(Style);
1892 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001893 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001894 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001895 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001896}
1897
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001898tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001899 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001900 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001901 if (Style.DisableFormat)
1902 return tooling::Replacements();
1903
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001904 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1905 new vfs::InMemoryFileSystem);
1906 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001907 DiagnosticsEngine Diagnostics(
1908 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1909 new DiagnosticOptions);
1910 SourceManager SourceMgr(Diagnostics, Files);
Daniel Jasper88c16342016-01-09 15:56:57 +00001911 InMemoryFileSystem->addFile(
1912 FileName, 0, llvm::MemoryBuffer::getMemBuffer(
1913 Code, FileName, /*RequiresNullTerminator=*/false));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001914 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1915 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001916 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1917 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001918 for (const tooling::Range &Range : Ranges) {
1919 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1920 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001921 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1922 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001923 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001924}
1925
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001926LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001927 LangOptions LangOpts;
1928 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001929 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1930 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001931 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001932 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001933 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001934 LangOpts.Bool = 1;
1935 LangOpts.ObjC1 = 1;
1936 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001937 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001938 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001939 return LangOpts;
1940}
1941
Edwin Vaned544aa72013-09-30 13:31:48 +00001942const char *StyleOptionHelpDescription =
1943 "Coding style, currently supports:\n"
1944 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1945 "Use -style=file to load style configuration from\n"
1946 ".clang-format file located in one of the parent\n"
1947 "directories of the source file (or current\n"
1948 "directory for stdin).\n"
1949 "Use -style=\"{key: value, ...}\" to set specific\n"
1950 "parameters, e.g.:\n"
1951 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1952
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001953static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasper498f5582015-12-25 08:53:31 +00001954 if (FileName.endswith(".java"))
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001955 return FormatStyle::LK_Java;
Daniel Jasper498f5582015-12-25 08:53:31 +00001956 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
1957 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
1958 if (FileName.endswith_lower(".proto") ||
1959 FileName.endswith_lower(".protodevel"))
Daniel Jasper7052ce62014-01-19 09:04:08 +00001960 return FormatStyle::LK_Proto;
Daniel Jasper498f5582015-12-25 08:53:31 +00001961 if (FileName.endswith_lower(".td"))
1962 return FormatStyle::LK_TableGen;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001963 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001964}
1965
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001966FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1967 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001968 FormatStyle Style = getLLVMStyle();
1969 Style.Language = getLanguageByFileName(FileName);
1970 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001971 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1972 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001973 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001974 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001975
1976 if (StyleName.startswith("{")) {
1977 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001978 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001979 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1980 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001981 }
1982 return Style;
1983 }
1984
1985 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001986 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001987 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1988 << " style\n";
1989 return Style;
1990 }
1991
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001992 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001993 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001994 SmallString<128> Path(FileName);
1995 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001996 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001997 Directory = llvm::sys::path::parent_path(Directory)) {
1998 if (!llvm::sys::fs::is_directory(Directory))
1999 continue;
2000 SmallString<128> ConfigFile(Directory);
2001
2002 llvm::sys::path::append(ConfigFile, ".clang-format");
2003 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2004 bool IsFile = false;
2005 // Ignore errors from is_regular_file: we only need to know if we can read
2006 // the file or not.
2007 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2008
2009 if (!IsFile) {
2010 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2011 ConfigFile = Directory;
2012 llvm::sys::path::append(ConfigFile, "_clang-format");
2013 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2014 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2015 }
2016
2017 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002018 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2019 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2020 if (std::error_code EC = Text.getError()) {
2021 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002022 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002023 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002024 if (std::error_code ec =
2025 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002026 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002027 if (!UnsuitableConfigFiles.empty())
2028 UnsuitableConfigFiles.append(", ");
2029 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002030 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002031 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002032 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2033 << "\n";
2034 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002035 }
2036 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2037 return Style;
2038 }
2039 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002040 if (!UnsuitableConfigFiles.empty()) {
2041 llvm::errs() << "Configuration file(s) do(es) not support "
2042 << getLanguageName(Style.Language) << ": "
2043 << UnsuitableConfigFiles << "\n";
2044 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002045 return Style;
2046}
2047
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002048} // namespace format
2049} // namespace clang