blob: 99787408133b3de99dca4f570285b36aadb54500 [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"
Eric Liu4cfb88a2016-04-25 15:09:22 +000017#include "AffectedRangeManager.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000019#include "FormatTokenLexer.h"
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000020#include "NamespaceEndCommentsFixer.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000021#include "SortJavaScriptImports.h"
22#include "TokenAnalyzer.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000023#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000024#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000026#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000027#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000028#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000029#include "clang/Basic/SourceManager.h"
Marianne Mailhot-Sarrasin4988fa12016-04-14 14:47:37 +000030#include "clang/Basic/VirtualFileSystem.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000031#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000032#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000033#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000034#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000035#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000036#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "llvm/Support/YAMLTraits.h"
Martin Probst081f1762016-06-01 15:19:53 +000038#include <algorithm>
Eric Liu4cfb88a2016-04-25 15:09:22 +000039#include <memory>
Daniel Jasper8b529712012-12-04 13:02:32 +000040#include <string>
41
Chandler Carruth10346662014-04-22 03:17:02 +000042#define DEBUG_TYPE "format-formatter"
43
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000044using clang::format::FormatStyle;
45
Daniel Jaspere1e43192014-04-01 12:55:11 +000046LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +000047LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
Daniel Jaspere1e43192014-04-01 12:55:11 +000048
Alexander Kornienkod6538332013-05-07 15:32:14 +000049namespace llvm {
50namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000051template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
52 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
53 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000054 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000055 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper03a04fe2016-12-12 12:42:29 +000056 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
Daniel Jasper7052ce62014-01-19 09:04:08 +000057 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Daniel Jasper498f5582015-12-25 08:53:31 +000058 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000059 }
60};
61
62template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
63 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
64 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
65 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
66 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
67 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
68 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
69 }
70};
71
72template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
73 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
74 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
75 IO.enumCase(Value, "false", FormatStyle::UT_Never);
76 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
77 IO.enumCase(Value, "true", FormatStyle::UT_Always);
78 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
Marianne Mailhot-Sarrasin51fe2792016-04-14 14:52:26 +000079 IO.enumCase(Value, "ForContinuationAndIndentation",
80 FormatStyle::UT_ForContinuationAndIndentation);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000081 }
82};
83
Daniel Jasperabd1f572016-03-02 22:44:03 +000084template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
85 static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
86 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
87 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
88 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
89 }
90};
91
Daniel Jasperd74cf402014-04-08 12:46:38 +000092template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
93 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
94 IO.enumCase(Value, "None", FormatStyle::SFS_None);
95 IO.enumCase(Value, "false", FormatStyle::SFS_None);
96 IO.enumCase(Value, "All", FormatStyle::SFS_All);
97 IO.enumCase(Value, "true", FormatStyle::SFS_All);
98 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000099 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +0000100 }
101};
102
Daniel Jasperac043c92014-09-15 11:11:00 +0000103template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
104 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
105 IO.enumCase(Value, "All", FormatStyle::BOS_All);
106 IO.enumCase(Value, "true", FormatStyle::BOS_All);
107 IO.enumCase(Value, "None", FormatStyle::BOS_None);
108 IO.enumCase(Value, "false", FormatStyle::BOS_None);
109 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
110 }
111};
112
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000113template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
114 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
115 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
116 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000117 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000118 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
119 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000120 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000121 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000122 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000123 }
124};
125
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000126template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000127struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
128 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
129 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
130 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
131 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
132 IO.enumCase(Value, "TopLevelDefinitions",
133 FormatStyle::RTBS_TopLevelDefinitions);
134 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
135 }
136};
137
138template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000139struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
140 static void
141 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000142 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
143 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
144 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
145
146 // For backward compatibility.
147 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
148 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
149 }
150};
151
Alexander Kornienkod6538332013-05-07 15:32:14 +0000152template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000153struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000154 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000155 FormatStyle::NamespaceIndentationKind &Value) {
156 IO.enumCase(Value, "None", FormatStyle::NI_None);
157 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
158 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000159 }
160};
161
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000162template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
163 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
164 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
165 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
166 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
167
168 // For backward compatibility.
169 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
170 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
171 }
172};
173
Jacques Pienaarfc275112015-02-18 23:48:37 +0000174template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
175 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000176 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
177 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
178 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
179
Alp Toker958027b2014-07-14 19:42:55 +0000180 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000181 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
182 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
183 }
184};
185
186template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000187struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000188 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000189 FormatStyle::SpaceBeforeParensOptions &Value) {
190 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000191 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000192 FormatStyle::SBPO_ControlStatements);
193 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000194
195 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000196 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
197 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000198 }
199};
200
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000201template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000202 static void mapping(IO &IO, FormatStyle &Style) {
203 // When reading, read the language first, we need it for getPredefinedStyle.
204 IO.mapOptional("Language", Style.Language);
205
Alexander Kornienko49149672013-05-10 11:56:10 +0000206 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000207 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
208 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000209 ArrayRef<StringRef> Styles(StylesArray);
210 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
211 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000212 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000213 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000214 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000215 IO.mapOptional("# BasedOnStyle", StyleName);
216 break;
217 }
218 }
219 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000220 StringRef BasedOnStyle;
221 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000222 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000223 FormatStyle::LanguageKind OldLanguage = Style.Language;
224 FormatStyle::LanguageKind Language =
225 ((FormatStyle *)IO.getContext())->Language;
226 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000227 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
228 return;
229 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000230 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000231 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000232 }
233
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000234 // For backward compatibility.
235 if (!IO.outputting()) {
236 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
237 IO.mapOptional("IndentFunctionDeclarationAfterType",
238 Style.IndentWrappedFunctionNames);
239 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
240 IO.mapOptional("SpaceAfterControlStatementKeyword",
241 Style.SpaceBeforeParens);
242 }
243
Alexander Kornienkod6538332013-05-07 15:32:14 +0000244 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000245 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000246 IO.mapOptional("AlignConsecutiveAssignments",
247 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000248 IO.mapOptional("AlignConsecutiveDeclarations",
249 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000250 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000251 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000252 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000253 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
254 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000255 IO.mapOptional("AllowShortBlocksOnASingleLine",
256 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000257 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
258 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000259 IO.mapOptional("AllowShortFunctionsOnASingleLine",
260 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000261 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
262 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000263 IO.mapOptional("AllowShortLoopsOnASingleLine",
264 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000265 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
266 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000267 IO.mapOptional("AlwaysBreakAfterReturnType",
268 Style.AlwaysBreakAfterReturnType);
269 // If AlwaysBreakAfterDefinitionReturnType was specified but
270 // AlwaysBreakAfterReturnType was not, initialize the latter from the
271 // former for backwards compatibility.
272 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
273 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
274 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
275 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
276 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
277 FormatStyle::DRTBS_TopLevel)
278 Style.AlwaysBreakAfterReturnType =
279 FormatStyle::RTBS_TopLevelDefinitions;
280 }
281
Alexander Kornienko58611712013-07-04 12:02:44 +0000282 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
283 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000284 IO.mapOptional("AlwaysBreakTemplateDeclarations",
285 Style.AlwaysBreakTemplateDeclarations);
286 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
287 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000288 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000289 IO.mapOptional("BreakBeforeBinaryOperators",
290 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000291 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000292 IO.mapOptional("BreakBeforeTernaryOperators",
293 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000294 IO.mapOptional("BreakConstructorInitializersBeforeComma",
295 Style.BreakConstructorInitializersBeforeComma);
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000296 IO.mapOptional("BreakAfterJavaFieldAnnotations",
297 Style.BreakAfterJavaFieldAnnotations);
298 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000299 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000300 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000301 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
302 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000303 IO.mapOptional("ConstructorInitializerIndentWidth",
304 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000305 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
306 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000307 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000308 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000309 IO.mapOptional("ExperimentalAutoDetectBinPacking",
310 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000311 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000312 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000313 IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000314 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000315 IO.mapOptional("IndentWidth", Style.IndentWidth);
316 IO.mapOptional("IndentWrappedFunctionNames",
317 Style.IndentWrappedFunctionNames);
Martin Probst0cd74ee2016-06-13 16:39:50 +0000318 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
319 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000320 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
321 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000322 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
323 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000324 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000325 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000326 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000327 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000328 IO.mapOptional("ObjCSpaceBeforeProtocolList",
329 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000330 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
331 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000332 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000333 IO.mapOptional("PenaltyBreakFirstLessLess",
334 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000335 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000336 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
337 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
338 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000339 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000340 IO.mapOptional("ReflowComments", Style.ReflowComments);
341 IO.mapOptional("SortIncludes", Style.SortIncludes);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000342 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000343 IO.mapOptional("SpaceAfterTemplateKeyword", Style.SpaceAfterTemplateKeyword);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000344 IO.mapOptional("SpaceBeforeAssignmentOperators",
345 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000346 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
347 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
348 IO.mapOptional("SpacesBeforeTrailingComments",
349 Style.SpacesBeforeTrailingComments);
350 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
351 IO.mapOptional("SpacesInContainerLiterals",
352 Style.SpacesInContainerLiterals);
353 IO.mapOptional("SpacesInCStyleCastParentheses",
354 Style.SpacesInCStyleCastParentheses);
355 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
356 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
357 IO.mapOptional("Standard", Style.Standard);
358 IO.mapOptional("TabWidth", Style.TabWidth);
359 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000360 }
361};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000362
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000363template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
364 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
365 IO.mapOptional("AfterClass", Wrapping.AfterClass);
366 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
367 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
368 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
369 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
370 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
371 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
372 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
373 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
374 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
375 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
376 }
377};
378
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000379template <> struct MappingTraits<FormatStyle::IncludeCategory> {
380 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
381 IO.mapOptional("Regex", Category.Regex);
382 IO.mapOptional("Priority", Category.Priority);
383 }
384};
385
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000386// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000387// IO.getContext() should contain a pointer to the FormatStyle structure, that
388// will be used to get default values for missing keys.
389// If the first element has no Language specified, it will be treated as the
390// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000391template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000392 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
393 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000394 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000395 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000396 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000397 if (Index >= Seq.size()) {
398 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000399 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000400 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000401 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000402 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000403 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000404 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000405 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000406 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000407 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000408 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000409 }
410};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000411} // namespace yaml
412} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000413
Daniel Jasperf7935112012-12-03 18:12:45 +0000414namespace clang {
415namespace format {
416
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000417const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000418 static ParseErrorCategory C;
419 return C;
420}
421std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000422 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000423}
424
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000425inline llvm::Error make_string_error(const llvm::Twine &Message) {
426 return llvm::make_error<llvm::StringError>(Message,
427 llvm::inconvertibleErrorCode());
428}
429
Reid Kleckner6432d452016-10-19 23:39:55 +0000430const char *ParseErrorCategory::name() const noexcept {
Rafael Espindolad0136702014-06-12 02:50:04 +0000431 return "clang-format.parse_error";
432}
433
434std::string ParseErrorCategory::message(int EV) const {
435 switch (static_cast<ParseError>(EV)) {
436 case ParseError::Success:
437 return "Success";
438 case ParseError::Error:
439 return "Invalid argument";
440 case ParseError::Unsuitable:
441 return "Unsuitable";
442 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000443 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000444}
445
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000446static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000447 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
448 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000449 FormatStyle Expanded = Style;
450 Expanded.BraceWrapping = {false, false, false, false, false, false,
451 false, false, false, false, false};
452 switch (Style.BreakBeforeBraces) {
453 case FormatStyle::BS_Linux:
454 Expanded.BraceWrapping.AfterClass = true;
455 Expanded.BraceWrapping.AfterFunction = true;
456 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000457 break;
458 case FormatStyle::BS_Mozilla:
459 Expanded.BraceWrapping.AfterClass = true;
460 Expanded.BraceWrapping.AfterEnum = true;
461 Expanded.BraceWrapping.AfterFunction = true;
462 Expanded.BraceWrapping.AfterStruct = true;
463 Expanded.BraceWrapping.AfterUnion = true;
464 break;
465 case FormatStyle::BS_Stroustrup:
466 Expanded.BraceWrapping.AfterFunction = true;
467 Expanded.BraceWrapping.BeforeCatch = true;
468 Expanded.BraceWrapping.BeforeElse = true;
469 break;
470 case FormatStyle::BS_Allman:
471 Expanded.BraceWrapping.AfterClass = true;
472 Expanded.BraceWrapping.AfterControlStatement = true;
473 Expanded.BraceWrapping.AfterEnum = true;
474 Expanded.BraceWrapping.AfterFunction = true;
475 Expanded.BraceWrapping.AfterNamespace = true;
476 Expanded.BraceWrapping.AfterObjCDeclaration = true;
477 Expanded.BraceWrapping.AfterStruct = true;
478 Expanded.BraceWrapping.BeforeCatch = true;
479 Expanded.BraceWrapping.BeforeElse = true;
480 break;
481 case FormatStyle::BS_GNU:
482 Expanded.BraceWrapping = {true, true, true, true, true, true,
483 true, true, true, true, true};
484 break;
485 case FormatStyle::BS_WebKit:
486 Expanded.BraceWrapping.AfterFunction = true;
487 break;
488 default:
489 break;
490 }
491 return Expanded;
492}
493
Daniel Jasperf7935112012-12-03 18:12:45 +0000494FormatStyle getLLVMStyle() {
495 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000496 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000497 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000498 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000499 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000500 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000501 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000502 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000503 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000504 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000505 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000506 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000507 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000508 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000509 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000510 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000511 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000512 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000513 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000514 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000515 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000516 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000517 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000518 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000519 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
520 false, false, false, false, false};
Nico Weber2cd92f12015-10-15 16:03:01 +0000521 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000522 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
523 LLVMStyle.BreakStringLiterals = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000524 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000525 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000526 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000527 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000528 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000529 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000530 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000531 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000532 LLVMStyle.ForEachMacros.push_back("foreach");
533 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
534 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000535 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
536 {"^(<|\"(gtest|isl|json)/)", 3},
537 {".*", 1}};
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000538 LLVMStyle.IncludeIsMainRegex = "$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000539 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000540 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000541 LLVMStyle.IndentWidth = 2;
Martin Probstfb2342d2016-06-13 17:50:10 +0000542 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
543 LLVMStyle.JavaScriptWrapImports = true;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000544 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000545 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000546 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000547 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000548 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000549 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000550 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000551 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000552 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000553 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000554 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000555 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000556 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000557 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000558 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000559 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000560 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000561 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000562 LLVMStyle.SpaceAfterCStyleCast = false;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000563 LLVMStyle.SpaceAfterTemplateKeyword = true;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000564 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000565 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000566 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000567
Daniel Jasper19a541e2013-12-19 16:45:34 +0000568 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000569 LLVMStyle.PenaltyBreakFirstLessLess = 120;
570 LLVMStyle.PenaltyBreakString = 1000;
571 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000572 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000573 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000574
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000575 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000576 LLVMStyle.SortIncludes = true;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000577
Daniel Jasperf7935112012-12-03 18:12:45 +0000578 return LLVMStyle;
579}
580
Nico Weber514ecc82014-02-02 20:50:45 +0000581FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000582 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000583 GoogleStyle.Language = Language;
584
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000586 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000587 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000588 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000589 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000590 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000591 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000592 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000593 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000594 GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000595 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000596 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000597 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000598 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000599 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000600 GoogleStyle.SpacesBeforeTrailingComments = 2;
601 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000602
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000603 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000604 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000605
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000606 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000607 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000608 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000609 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000610 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000611 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000612 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000613 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
614 GoogleStyle.ColumnLimit = 100;
615 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000616 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000617 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000618 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000619 GoogleStyle.AlignOperands = false;
Daniel Jasper28d8a5a2016-09-07 23:01:13 +0000620 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000621 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000622 GoogleStyle.BreakBeforeTernaryOperators = false;
Martin Probst6f99d242016-09-21 06:56:38 +0000623 GoogleStyle.CommentPragmas =
624 "(taze:|@(export|requirecss|return|returns|see|visibility)) ";
Daniel Jasper8f83a902014-05-09 10:28:58 +0000625 GoogleStyle.MaxEmptyLinesToKeep = 3;
Martin Probstece8c0c2016-06-13 16:41:28 +0000626 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
Nico Weber514ecc82014-02-02 20:50:45 +0000627 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000628 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
Martin Probst0cd74ee2016-06-13 16:39:50 +0000629 GoogleStyle.JavaScriptWrapImports = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000630 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000631 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000632 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000633 } else if (Language == FormatStyle::LK_ObjC) {
634 GoogleStyle.ColumnLimit = 100;
Nico Weber514ecc82014-02-02 20:50:45 +0000635 }
636
Daniel Jasperf7935112012-12-03 18:12:45 +0000637 return GoogleStyle;
638}
639
Nico Weber514ecc82014-02-02 20:50:45 +0000640FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
641 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000642 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000643 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000644 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000645 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000646 ChromiumStyle.IndentWidth = 4;
Nico Weberea649692017-01-04 02:33:36 +0000647 } else if (Language == FormatStyle::LK_JavaScript) {
648 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
649 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Nico Weber450425c2014-11-26 16:43:18 +0000650 } else {
651 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
652 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
653 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
654 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
655 ChromiumStyle.BinPackParameters = false;
656 ChromiumStyle.DerivePointerAlignment = false;
Nico Weber9e2bc302017-01-31 18:42:05 +0000657 if (Language == FormatStyle::LK_ObjC)
658 ChromiumStyle.ColumnLimit = 80;
Nico Weber450425c2014-11-26 16:43:18 +0000659 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000660 return ChromiumStyle;
661}
662
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000663FormatStyle getMozillaStyle() {
664 FormatStyle MozillaStyle = getLLVMStyle();
665 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000666 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Zachary Turner448592e2015-12-18 22:20:15 +0000667 MozillaStyle.AlwaysBreakAfterReturnType =
Sylvestre Ledrudcb038d2016-12-14 16:09:29 +0000668 FormatStyle::RTBS_TopLevel;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000669 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
670 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000671 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Sylvestre Ledrudcb038d2016-12-14 16:09:29 +0000672 MozillaStyle.BinPackParameters = false;
673 MozillaStyle.BinPackArguments = false;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000674 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000675 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
676 MozillaStyle.ConstructorInitializerIndentWidth = 2;
677 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000678 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000679 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000680 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000681 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
682 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000683 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000684 MozillaStyle.SpaceAfterTemplateKeyword = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000685 return MozillaStyle;
686}
687
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000688FormatStyle getWebKitStyle() {
689 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000690 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000691 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000692 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000693 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000694 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000695 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000696 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000697 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000698 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000699 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000700 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000701 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000702 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000703 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000704 return Style;
705}
706
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000707FormatStyle getGNUStyle() {
708 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000709 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000710 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000711 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000712 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000713 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000714 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000715 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000716 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000717 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000718 return Style;
719}
720
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000721FormatStyle getNoStyle() {
722 FormatStyle NoStyle = getLLVMStyle();
723 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000724 NoStyle.SortIncludes = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000725 return NoStyle;
726}
727
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000728bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
729 FormatStyle *Style) {
730 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000731 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000732 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000733 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000734 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000735 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000736 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000737 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000738 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000739 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000740 } else if (Name.equals_lower("gnu")) {
741 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000742 } else if (Name.equals_lower("none")) {
743 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000744 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000745 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000746 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000747
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000748 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000749 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000750}
751
Rafael Espindolac0809172014-06-12 14:02:15 +0000752std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000753 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000754 FormatStyle::LanguageKind Language = Style->Language;
755 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000756 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000757 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000758
759 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000760 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000761 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
762 // values for the fields, keys for which are missing from the configuration.
763 // Mapping also uses the context to get the language to find the correct
764 // base style.
765 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000766 Input >> Styles;
767 if (Input.error())
768 return Input.error();
769
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000770 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000771 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000772 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000773 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000774 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000775 for (unsigned j = 0; j < i; ++j) {
776 if (Styles[i].Language == Styles[j].Language) {
777 DEBUG(llvm::dbgs()
778 << "Duplicate languages in the config file on positions " << j
779 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000780 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000781 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000782 }
783 }
784 // Look for a suitable configuration starting from the end, so we can
785 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000786 // configuration (which can only be at slot 0) after it.
787 for (int i = Styles.size() - 1; i >= 0; --i) {
788 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000789 Styles[i].Language == FormatStyle::LK_None) {
790 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000791 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000792 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000793 }
794 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000795 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000796}
797
798std::string configurationAsText(const FormatStyle &Style) {
799 std::string Text;
800 llvm::raw_string_ostream Stream(Text);
801 llvm::yaml::Output Output(Stream);
802 // We use the same mapping method for input and output, so we need a non-const
803 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000804 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000805 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000806 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000807}
808
Craig Topperaf35e852013-06-30 22:29:28 +0000809namespace {
810
Daniel Jasper496c1992016-09-07 22:48:53 +0000811class JavaScriptRequoter : public TokenAnalyzer {
Eric Liu4cfb88a2016-04-25 15:09:22 +0000812public:
Daniel Jasper496c1992016-09-07 22:48:53 +0000813 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
814 : TokenAnalyzer(Env, Style) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +0000815
816 tooling::Replacements
817 analyze(TokenAnnotator &Annotator,
818 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +0000819 FormatTokenLexer &Tokens) override {
Eric Liu4cfb88a2016-04-25 15:09:22 +0000820 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
821 AnnotatedLines.end());
Daniel Jasper496c1992016-09-07 22:48:53 +0000822 tooling::Replacements Result;
823 requoteJSStringLiteral(AnnotatedLines, Result);
824 return Result;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000825 }
826
827private:
Daniel Jasper496c1992016-09-07 22:48:53 +0000828 // Replaces double/single-quoted string literal as appropriate, re-escaping
829 // the contents in the process.
Daniel Jasper97439922016-03-17 13:03:41 +0000830 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
Eric Liu4cfb88a2016-04-25 15:09:22 +0000831 tooling::Replacements &Result) {
Daniel Jasper97439922016-03-17 13:03:41 +0000832 for (AnnotatedLine *Line : Lines) {
833 requoteJSStringLiteral(Line->Children, Result);
834 if (!Line->Affected)
835 continue;
836 for (FormatToken *FormatTok = Line->First; FormatTok;
837 FormatTok = FormatTok->Next) {
838 StringRef Input = FormatTok->TokenText;
Martin Probsta1669792016-05-12 11:20:32 +0000839 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
Daniel Jasper97439922016-03-17 13:03:41 +0000840 // NB: testing for not starting with a double quote to avoid
Daniel Jasper496c1992016-09-07 22:48:53 +0000841 // breaking `template strings`.
Eric Liu635423e2016-04-28 07:52:03 +0000842 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
Daniel Jasper97439922016-03-17 13:03:41 +0000843 !Input.startswith("\"")) ||
Eric Liu635423e2016-04-28 07:52:03 +0000844 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
Daniel Jasper97439922016-03-17 13:03:41 +0000845 !Input.startswith("\'")))
846 continue;
847
848 // Change start and end quote.
Eric Liu635423e2016-04-28 07:52:03 +0000849 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
Daniel Jasper97439922016-03-17 13:03:41 +0000850 SourceLocation Start = FormatTok->Tok.getLocation();
851 auto Replace = [&](SourceLocation Start, unsigned Length,
852 StringRef ReplacementText) {
Eric Liu40ef2fb2016-08-01 10:16:37 +0000853 auto Err = Result.add(tooling::Replacement(
854 Env.getSourceManager(), Start, Length, ReplacementText));
855 // FIXME: handle error. For now, print error message and skip the
856 // replacement for release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +0000857 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +0000858 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +0000859 assert(false);
860 }
Daniel Jasper97439922016-03-17 13:03:41 +0000861 };
862 Replace(Start, 1, IsSingle ? "'" : "\"");
863 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
864 IsSingle ? "'" : "\"");
865
866 // Escape internal quotes.
Daniel Jasper97439922016-03-17 13:03:41 +0000867 bool Escaped = false;
868 for (size_t i = 1; i < Input.size() - 1; i++) {
869 switch (Input[i]) {
Eric Liu4cfb88a2016-04-25 15:09:22 +0000870 case '\\':
871 if (!Escaped && i + 1 < Input.size() &&
872 ((IsSingle && Input[i + 1] == '"') ||
873 (!IsSingle && Input[i + 1] == '\''))) {
874 // Remove this \, it's escaping a " or ' that no longer needs
875 // escaping
Eric Liu4cfb88a2016-04-25 15:09:22 +0000876 Replace(Start.getLocWithOffset(i), 1, "");
877 continue;
878 }
879 Escaped = !Escaped;
880 break;
881 case '\"':
882 case '\'':
883 if (!Escaped && IsSingle == (Input[i] == '\'')) {
884 // Escape the quote.
885 Replace(Start.getLocWithOffset(i), 0, "\\");
Eric Liu4cfb88a2016-04-25 15:09:22 +0000886 }
887 Escaped = false;
888 break;
889 default:
890 Escaped = false;
891 break;
Daniel Jasper97439922016-03-17 13:03:41 +0000892 }
893 }
Daniel Jasper97439922016-03-17 13:03:41 +0000894 }
895 }
896 }
Daniel Jasper496c1992016-09-07 22:48:53 +0000897};
898
899class Formatter : public TokenAnalyzer {
900public:
901 Formatter(const Environment &Env, const FormatStyle &Style,
902 bool *IncompleteFormat)
903 : TokenAnalyzer(Env, Style), IncompleteFormat(IncompleteFormat) {}
904
905 tooling::Replacements
906 analyze(TokenAnnotator &Annotator,
907 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
908 FormatTokenLexer &Tokens) override {
909 tooling::Replacements Result;
910 deriveLocalStyle(AnnotatedLines);
911 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
912 AnnotatedLines.end());
913 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
914 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
915 }
916 Annotator.setCommentLineLevels(AnnotatedLines);
917
918 WhitespaceManager Whitespaces(
919 Env.getSourceManager(), Style,
920 inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
921 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
922 Env.getSourceManager(), Whitespaces, Encoding,
923 BinPackInconclusiveFunctions);
924 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
925 IncompleteFormat)
926 .format(AnnotatedLines);
927 for (const auto &R : Whitespaces.generateReplacements())
928 if (Result.add(R))
929 return Result;
930 return Result;
931 }
932
933private:
Daniel Jasper97439922016-03-17 13:03:41 +0000934
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000935 static bool inputUsesCRLF(StringRef Text) {
936 return Text.count('\r') * 2 > Text.count('\n');
937 }
938
Daniel Jasper352f0df2015-07-18 16:35:30 +0000939 bool
940 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +0000941 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +0000942 if (hasCpp03IncompatibleFormat(Line->Children))
943 return true;
944 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
945 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
946 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
947 return true;
948 if (Tok->is(TT_TemplateCloser) &&
949 Tok->Previous->is(TT_TemplateCloser))
950 return true;
951 }
952 }
953 }
954 return false;
955 }
956
957 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
958 int AlignmentDiff = 0;
Eric Liu4cfb88a2016-04-25 15:09:22 +0000959 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +0000960 AlignmentDiff += countVariableAlignments(Line->Children);
961 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
962 if (!Tok->is(TT_PointerOrReference))
963 continue;
964 bool SpaceBefore =
965 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
966 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
967 Tok->Next->WhitespaceRange.getEnd();
968 if (SpaceBefore && !SpaceAfter)
969 ++AlignmentDiff;
970 if (!SpaceBefore && SpaceAfter)
971 --AlignmentDiff;
972 }
973 }
974 return AlignmentDiff;
975 }
976
Manuel Klimek71814b42013-10-11 21:25:45 +0000977 void
978 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000979 bool HasBinPackedFunction = false;
980 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000981 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000982 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000983 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000984 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000985 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000986 if (Tok->PackingKind == PPK_BinPacked)
987 HasBinPackedFunction = true;
988 if (Tok->PackingKind == PPK_OnePerLine)
989 HasOnePerLineFunction = true;
990
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000991 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000992 }
993 }
Eric Liu635423e2016-04-28 07:52:03 +0000994 if (Style.DerivePointerAlignment)
995 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
996 ? FormatStyle::PAS_Left
997 : FormatStyle::PAS_Right;
998 if (Style.Standard == FormatStyle::LS_Auto)
999 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1000 ? FormatStyle::LS_Cpp11
1001 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001002 BinPackInconclusiveFunctions =
1003 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001004 }
1005
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001006 bool BinPackInconclusiveFunctions;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001007 bool *IncompleteFormat;
1008};
1009
1010// This class clean up the erroneous/redundant code around the given ranges in
1011// file.
1012class Cleaner : public TokenAnalyzer {
1013public:
Eric Liu635423e2016-04-28 07:52:03 +00001014 Cleaner(const Environment &Env, const FormatStyle &Style)
1015 : TokenAnalyzer(Env, Style),
Eric Liu4cfb88a2016-04-25 15:09:22 +00001016 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
1017
1018 // FIXME: eliminate unused parameters.
1019 tooling::Replacements
1020 analyze(TokenAnnotator &Annotator,
1021 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +00001022 FormatTokenLexer &Tokens) override {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001023 // FIXME: in the current implementation the granularity of affected range
1024 // is an annotated line. However, this is not sufficient. Furthermore,
1025 // redundant code introduced by replacements does not necessarily
1026 // intercept with ranges of replacements that result in the redundancy.
1027 // To determine if some redundant code is actually introduced by
1028 // replacements(e.g. deletions), we need to come up with a more
1029 // sophisticated way of computing affected ranges.
1030 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
1031 AnnotatedLines.end());
1032
1033 checkEmptyNamespace(AnnotatedLines);
1034
Eric Liuce5e4bc2016-05-18 08:02:56 +00001035 for (auto &Line : AnnotatedLines) {
1036 if (Line->Affected) {
1037 cleanupRight(Line->First, tok::comma, tok::comma);
1038 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
Eric Liu2574d152016-09-13 15:02:43 +00001039 cleanupRight(Line->First, tok::l_paren, tok::comma);
1040 cleanupLeft(Line->First, tok::comma, tok::r_paren);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001041 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
1042 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
Malcolm Parsons5d8cdb82016-10-20 14:58:45 +00001043 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001044 }
1045 }
1046
Eric Liu4cfb88a2016-04-25 15:09:22 +00001047 return generateFixes();
1048 }
1049
1050private:
1051 bool containsOnlyComments(const AnnotatedLine &Line) {
1052 for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
1053 if (Tok->isNot(tok::comment))
1054 return false;
1055 }
1056 return true;
1057 }
1058
1059 // Iterate through all lines and remove any empty (nested) namespaces.
1060 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Eric Liu7956c402016-10-05 15:49:01 +00001061 std::set<unsigned> DeletedLines;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001062 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1063 auto &Line = *AnnotatedLines[i];
1064 if (Line.startsWith(tok::kw_namespace) ||
1065 Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
Eric Liu7956c402016-10-05 15:49:01 +00001066 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001067 }
1068 }
1069
1070 for (auto Line : DeletedLines) {
1071 FormatToken *Tok = AnnotatedLines[Line]->First;
1072 while (Tok) {
1073 deleteToken(Tok);
1074 Tok = Tok->Next;
1075 }
1076 }
1077 }
1078
1079 // The function checks if the namespace, which starts from \p CurrentLine, and
1080 // its nested namespaces are empty and delete them if they are empty. It also
1081 // sets \p NewLine to the last line checked.
1082 // Returns true if the current namespace is empty.
1083 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Eric Liu7956c402016-10-05 15:49:01 +00001084 unsigned CurrentLine, unsigned &NewLine,
1085 std::set<unsigned> &DeletedLines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001086 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
Eric Liu635423e2016-04-28 07:52:03 +00001087 if (Style.BraceWrapping.AfterNamespace) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001088 // If the left brace is in a new line, we should consume it first so that
1089 // it does not make the namespace non-empty.
1090 // FIXME: error handling if there is no left brace.
1091 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1092 NewLine = CurrentLine;
1093 return false;
1094 }
1095 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1096 return false;
1097 }
1098 while (++CurrentLine < End) {
1099 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1100 break;
1101
1102 if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
1103 AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
1104 tok::kw_namespace)) {
Eric Liu7956c402016-10-05 15:49:01 +00001105 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1106 DeletedLines))
Eric Liu4cfb88a2016-04-25 15:09:22 +00001107 return false;
1108 CurrentLine = NewLine;
1109 continue;
1110 }
1111
1112 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1113 continue;
1114
1115 // If there is anything other than comments or nested namespaces in the
1116 // current namespace, the namespace cannot be empty.
1117 NewLine = CurrentLine;
1118 return false;
1119 }
1120
1121 NewLine = CurrentLine;
1122 if (CurrentLine >= End)
1123 return false;
1124
1125 // Check if the empty namespace is actually affected by changed ranges.
1126 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1127 AnnotatedLines[InitLine]->First->Tok.getLocation(),
1128 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1129 return false;
1130
1131 for (unsigned i = InitLine; i <= CurrentLine; ++i) {
1132 DeletedLines.insert(i);
1133 }
1134
1135 return true;
1136 }
1137
Eric Liuce5e4bc2016-05-18 08:02:56 +00001138 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
1139 // of the token in the pair if the left token has \p LK token kind and the
1140 // right token has \p RK token kind. If \p DeleteLeft is true, the left token
1141 // is deleted on match; otherwise, the right token is deleted.
1142 template <typename LeftKind, typename RightKind>
1143 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
1144 bool DeleteLeft) {
1145 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
1146 for (auto *Res = Tok.Next; Res; Res = Res->Next)
1147 if (!Res->is(tok::comment) &&
1148 DeletedTokens.find(Res) == DeletedTokens.end())
1149 return Res;
1150 return nullptr;
1151 };
1152 for (auto *Left = Start; Left;) {
1153 auto *Right = NextNotDeleted(*Left);
1154 if (!Right)
1155 break;
1156 if (Left->is(LK) && Right->is(RK)) {
1157 deleteToken(DeleteLeft ? Left : Right);
Eric Liu01426ff2016-09-09 17:50:49 +00001158 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
1159 deleteToken(Tok);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001160 // If the right token is deleted, we should keep the left token
1161 // unchanged and pair it with the new right token.
1162 if (!DeleteLeft)
1163 continue;
1164 }
1165 Left = Right;
1166 }
1167 }
1168
1169 template <typename LeftKind, typename RightKind>
1170 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
1171 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
1172 }
1173
1174 template <typename LeftKind, typename RightKind>
1175 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
1176 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
1177 }
1178
Eric Liu4cfb88a2016-04-25 15:09:22 +00001179 // Delete the given token.
1180 inline void deleteToken(FormatToken *Tok) {
1181 if (Tok)
1182 DeletedTokens.insert(Tok);
1183 }
1184
1185 tooling::Replacements generateFixes() {
1186 tooling::Replacements Fixes;
1187 std::vector<FormatToken *> Tokens;
1188 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1189 std::back_inserter(Tokens));
1190
1191 // Merge multiple continuous token deletions into one big deletion so that
1192 // the number of replacements can be reduced. This makes computing affected
1193 // ranges more efficient when we run reformat on the changed code.
1194 unsigned Idx = 0;
1195 while (Idx < Tokens.size()) {
1196 unsigned St = Idx, End = Idx;
1197 while ((End + 1) < Tokens.size() &&
1198 Tokens[End]->Next == Tokens[End + 1]) {
1199 End++;
1200 }
1201 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1202 Tokens[End]->Tok.getEndLoc());
Eric Liu40ef2fb2016-08-01 10:16:37 +00001203 auto Err =
1204 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
1205 // FIXME: better error handling. for now just print error message and skip
1206 // for the release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001207 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001208 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001209 assert(false && "Fixes must not conflict!");
1210 }
Eric Liu4cfb88a2016-04-25 15:09:22 +00001211 Idx = End + 1;
1212 }
1213
1214 return Fixes;
1215 }
1216
1217 // Class for less-than inequality comparason for the set `RedundantTokens`.
1218 // We store tokens in the order they appear in the translation unit so that
1219 // we do not need to sort them in `generateFixes()`.
1220 struct FormatTokenLess {
Eric Liu635423e2016-04-28 07:52:03 +00001221 FormatTokenLess(const SourceManager &SM) : SM(SM) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +00001222
Eric Liu2874ac32016-05-18 08:14:49 +00001223 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001224 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
1225 RHS->Tok.getLocation());
1226 }
Eric Liu635423e2016-04-28 07:52:03 +00001227 const SourceManager &SM;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001228 };
1229
1230 // Tokens to be deleted.
1231 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
Daniel Jasperf7935112012-12-03 18:12:45 +00001232};
1233
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001234struct IncludeDirective {
1235 StringRef Filename;
1236 StringRef Text;
1237 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001238 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001239};
1240
Craig Topperaf35e852013-06-30 22:29:28 +00001241} // end anonymous namespace
1242
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001243// Determines whether 'Ranges' intersects with ('Start', 'End').
1244static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1245 unsigned End) {
1246 for (auto Range : Ranges) {
1247 if (Range.getOffset() < End &&
1248 Range.getOffset() + Range.getLength() > Start)
1249 return true;
1250 }
1251 return false;
1252}
1253
Eric Liua992afe2016-08-10 09:32:23 +00001254// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
1255// before sorting/deduplicating. Index is the index of the include under the
1256// cursor in the original set of includes. If this include has duplicates, it is
1257// the index of the first of the duplicates as the others are going to be
1258// removed. OffsetToEOL describes the cursor's position relative to the end of
1259// its current line.
1260// If `Cursor` is not on any #include, `Index` will be UINT_MAX.
1261static std::pair<unsigned, unsigned>
1262FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
1263 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
1264 unsigned CursorIndex = UINT_MAX;
1265 unsigned OffsetToEOL = 0;
1266 for (int i = 0, e = Includes.size(); i != e; ++i) {
1267 unsigned Start = Includes[Indices[i]].Offset;
1268 unsigned End = Start + Includes[Indices[i]].Text.size();
1269 if (!(Cursor >= Start && Cursor < End))
1270 continue;
1271 CursorIndex = Indices[i];
1272 OffsetToEOL = End - Cursor;
1273 // Put the cursor on the only remaining #include among the duplicate
1274 // #includes.
1275 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
1276 CursorIndex = i;
1277 break;
1278 }
1279 return std::make_pair(CursorIndex, OffsetToEOL);
1280}
1281
1282// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
1283// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
1284// source order.
1285// #include directives with the same text will be deduplicated, and only the
1286// first #include in the duplicate #includes remains. If the `Cursor` is
1287// provided and put on a deleted #include, it will be moved to the remaining
1288// #include in the duplicate #includes.
Martin Probstc4a0dd42016-05-20 11:24:24 +00001289static void sortCppIncludes(const FormatStyle &Style,
Eric Liua992afe2016-08-10 09:32:23 +00001290 const SmallVectorImpl<IncludeDirective> &Includes,
1291 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1292 tooling::Replacements &Replaces, unsigned *Cursor) {
1293 unsigned IncludesBeginOffset = Includes.front().Offset;
Daniel Jasperd6a00782016-08-30 21:33:41 +00001294 unsigned IncludesEndOffset =
1295 Includes.back().Offset + Includes.back().Text.size();
1296 unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1297 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001298 return;
1299 SmallVector<unsigned, 16> Indices;
1300 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1301 Indices.push_back(i);
Daniel Jasper94a96fc2016-03-03 17:34:14 +00001302 std::stable_sort(
1303 Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1304 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1305 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1306 });
Eric Liua992afe2016-08-10 09:32:23 +00001307 // The index of the include on which the cursor will be put after
1308 // sorting/deduplicating.
1309 unsigned CursorIndex;
1310 // The offset from cursor to the end of line.
1311 unsigned CursorToEOLOffset;
1312 if (Cursor)
1313 std::tie(CursorIndex, CursorToEOLOffset) =
1314 FindCursorIndex(Includes, Indices, *Cursor);
1315
1316 // Deduplicate #includes.
1317 Indices.erase(std::unique(Indices.begin(), Indices.end(),
1318 [&](unsigned LHSI, unsigned RHSI) {
1319 return Includes[LHSI].Text == Includes[RHSI].Text;
1320 }),
1321 Indices.end());
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001322
1323 // If the #includes are out of order, we generate a single replacement fixing
1324 // the entire block. Otherwise, no replacement is generated.
Eric Liua992afe2016-08-10 09:32:23 +00001325 if (Indices.size() == Includes.size() &&
1326 std::is_sorted(Indices.begin(), Indices.end()))
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001327 return;
1328
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001329 std::string result;
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001330 for (unsigned Index : Indices) {
1331 if (!result.empty())
1332 result += "\n";
1333 result += Includes[Index].Text;
Eric Liua992afe2016-08-10 09:32:23 +00001334 if (Cursor && CursorIndex == Index)
1335 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001336 }
1337
Eric Liu40ef2fb2016-08-01 10:16:37 +00001338 auto Err = Replaces.add(tooling::Replacement(
Eric Liua992afe2016-08-10 09:32:23 +00001339 FileName, Includes.front().Offset, IncludesBlockSize, result));
Eric Liu40ef2fb2016-08-01 10:16:37 +00001340 // FIXME: better error handling. For now, just skip the replacement for the
1341 // release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001342 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001343 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001344 assert(false);
1345 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001346}
1347
Eric Liu659afd52016-05-31 13:34:20 +00001348namespace {
1349
1350// This class manages priorities of #include categories and calculates
1351// priorities for headers.
1352class IncludeCategoryManager {
1353public:
1354 IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
1355 : Style(Style), FileName(FileName) {
1356 FileStem = llvm::sys::path::stem(FileName);
1357 for (const auto &Category : Style.IncludeCategories)
1358 CategoryRegexs.emplace_back(Category.Regex);
1359 IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
1360 FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1361 FileName.endswith(".cxx") || FileName.endswith(".m") ||
1362 FileName.endswith(".mm");
1363 }
1364
1365 // Returns the priority of the category which \p IncludeName belongs to.
1366 // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
1367 // 0. Otherwise, returns the priority of the matching category or INT_MAX.
1368 int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) {
1369 int Ret = INT_MAX;
1370 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
1371 if (CategoryRegexs[i].match(IncludeName)) {
1372 Ret = Style.IncludeCategories[i].Priority;
1373 break;
1374 }
1375 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
1376 Ret = 0;
1377 return Ret;
1378 }
1379
1380private:
1381 bool isMainHeader(StringRef IncludeName) const {
1382 if (!IncludeName.startswith("\""))
1383 return false;
1384 StringRef HeaderStem =
1385 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
1386 if (FileStem.startswith(HeaderStem)) {
1387 llvm::Regex MainIncludeRegex(
1388 (HeaderStem + Style.IncludeIsMainRegex).str());
1389 if (MainIncludeRegex.match(FileStem))
1390 return true;
1391 }
1392 return false;
1393 }
1394
1395 const FormatStyle &Style;
1396 bool IsMainFile;
1397 StringRef FileName;
1398 StringRef FileStem;
1399 SmallVector<llvm::Regex, 4> CategoryRegexs;
1400};
1401
1402const char IncludeRegexPattern[] =
1403 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1404
1405} // anonymous namespace
1406
Martin Probstc4a0dd42016-05-20 11:24:24 +00001407tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
1408 ArrayRef<tooling::Range> Ranges,
1409 StringRef FileName,
1410 tooling::Replacements &Replaces,
1411 unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001412 unsigned Prev = 0;
1413 unsigned SearchFrom = 0;
Eric Liu659afd52016-05-31 13:34:20 +00001414 llvm::Regex IncludeRegex(IncludeRegexPattern);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001415 SmallVector<StringRef, 4> Matches;
1416 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001417
1418 // In compiled files, consider the first #include to be the main #include of
1419 // the file if it is not a system #include. This ensures that the header
1420 // doesn't have hidden dependencies
1421 // (http://llvm.org/docs/CodingStandards.html#include-style).
1422 //
1423 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1424 // cases where the first #include is unlikely to be the main header.
Eric Liu659afd52016-05-31 13:34:20 +00001425 IncludeCategoryManager Categories(Style, FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001426 bool FirstIncludeBlock = true;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001427 bool MainIncludeFound = false;
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001428 bool FormattingOff = false;
1429
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001430 for (;;) {
1431 auto Pos = Code.find('\n', SearchFrom);
1432 StringRef Line =
1433 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001434
1435 StringRef Trimmed = Line.trim();
1436 if (Trimmed == "// clang-format off")
1437 FormattingOff = true;
1438 else if (Trimmed == "// clang-format on")
1439 FormattingOff = false;
1440
1441 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001442 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001443 StringRef IncludeName = Matches[2];
Eric Liu659afd52016-05-31 13:34:20 +00001444 int Category = Categories.getIncludePriority(
1445 IncludeName,
1446 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
1447 if (Category == 0)
1448 MainIncludeFound = true;
Nico Weberff063702015-10-21 17:13:45 +00001449 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001450 } else if (!IncludesInBlock.empty()) {
Martin Probstc4a0dd42016-05-20 11:24:24 +00001451 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1452 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001453 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001454 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001455 }
1456 Prev = Pos + 1;
1457 }
1458 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1459 break;
1460 SearchFrom = Pos + 1;
1461 }
1462 if (!IncludesInBlock.empty())
Martin Probstc4a0dd42016-05-20 11:24:24 +00001463 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1464 return Replaces;
1465}
1466
Martin Probstfa37b182017-01-27 09:09:11 +00001467bool isMpegTS(StringRef Code) {
1468 // MPEG transport streams use the ".ts" file extension. clang-format should
1469 // not attempt to format those. MPEG TS' frame format starts with 0x47 every
1470 // 189 bytes - detect that and return.
1471 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
1472}
1473
Martin Probstc4a0dd42016-05-20 11:24:24 +00001474tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1475 ArrayRef<tooling::Range> Ranges,
1476 StringRef FileName, unsigned *Cursor) {
1477 tooling::Replacements Replaces;
1478 if (!Style.SortIncludes)
1479 return Replaces;
Martin Probstfa37b182017-01-27 09:09:11 +00001480 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
1481 isMpegTS(Code))
1482 return Replaces;
Martin Probstc4a0dd42016-05-20 11:24:24 +00001483 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
1484 return sortJavaScriptImports(Style, Code, Ranges, FileName);
1485 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001486 return Replaces;
1487}
1488
Eric Liu4cfb88a2016-04-25 15:09:22 +00001489template <typename T>
Eric Liu4f8d9942016-07-11 13:53:12 +00001490static llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001491processReplacements(T ProcessFunc, StringRef Code,
1492 const tooling::Replacements &Replaces,
1493 const FormatStyle &Style) {
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001494 if (Replaces.empty())
1495 return tooling::Replacements();
1496
Eric Liu4f8d9942016-07-11 13:53:12 +00001497 auto NewCode = applyAllReplacements(Code, Replaces);
1498 if (!NewCode)
1499 return NewCode.takeError();
Eric Liu40ef2fb2016-08-01 10:16:37 +00001500 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001501 StringRef FileName = Replaces.begin()->getFilePath();
Eric Liu4cfb88a2016-04-25 15:09:22 +00001502
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001503 tooling::Replacements FormatReplaces =
Eric Liu4f8d9942016-07-11 13:53:12 +00001504 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001505
Eric Liu40ef2fb2016-08-01 10:16:37 +00001506 return Replaces.merge(FormatReplaces);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001507}
1508
Eric Liu4f8d9942016-07-11 13:53:12 +00001509llvm::Expected<tooling::Replacements>
1510formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1511 const FormatStyle &Style) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001512 // We need to use lambda function here since there are two versions of
Eric Liubaf58c22016-05-18 13:43:48 +00001513 // `sortIncludes`.
1514 auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
1515 std::vector<tooling::Range> Ranges,
1516 StringRef FileName) -> tooling::Replacements {
1517 return sortIncludes(Style, Code, Ranges, FileName);
1518 };
Eric Liu4f8d9942016-07-11 13:53:12 +00001519 auto SortedReplaces =
Eric Liubaf58c22016-05-18 13:43:48 +00001520 processReplacements(SortIncludes, Code, Replaces, Style);
Eric Liu4f8d9942016-07-11 13:53:12 +00001521 if (!SortedReplaces)
1522 return SortedReplaces.takeError();
Eric Liubaf58c22016-05-18 13:43:48 +00001523
1524 // We need to use lambda function here since there are two versions of
Eric Liu4cfb88a2016-04-25 15:09:22 +00001525 // `reformat`.
1526 auto Reformat = [](const FormatStyle &Style, StringRef Code,
1527 std::vector<tooling::Range> Ranges,
1528 StringRef FileName) -> tooling::Replacements {
1529 return reformat(Style, Code, Ranges, FileName);
1530 };
Eric Liu4f8d9942016-07-11 13:53:12 +00001531 return processReplacements(Reformat, Code, *SortedReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001532}
1533
Eric Liu659afd52016-05-31 13:34:20 +00001534namespace {
1535
1536inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
Eric Liuc0d3a802016-09-23 15:10:56 +00001537 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
Eric Liu659afd52016-05-31 13:34:20 +00001538 llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
1539}
1540
Eric Liuc0d3a802016-09-23 15:10:56 +00001541inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
1542 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
1543}
1544
Eric Liu964782a2016-12-02 11:01:43 +00001545// Returns the offset after skipping a sequence of tokens, matched by \p
1546// GetOffsetAfterSequence, from the start of the code.
1547// \p GetOffsetAfterSequence should be a function that matches a sequence of
1548// tokens and returns an offset after the sequence.
1549unsigned getOffsetAfterTokenSequence(
1550 StringRef FileName, StringRef Code, const FormatStyle &Style,
1551 std::function<unsigned(const SourceManager &, Lexer &, Token &)>
1552 GetOffsetAfterSequense) {
1553 std::unique_ptr<Environment> Env =
1554 Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
1555 const SourceManager &SourceMgr = Env->getSourceManager();
1556 Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
1557 getFormattingLangOpts(Style));
1558 Token Tok;
1559 // Get the first token.
1560 Lex.LexFromRawLexer(Tok);
1561 return GetOffsetAfterSequense(SourceMgr, Lex, Tok);
Eric Liu35288322016-06-06 11:00:13 +00001562}
1563
1564// Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
1565// \p Tok will be the token after this directive; otherwise, it can be any token
1566// after the given \p Tok (including \p Tok).
1567bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
1568 bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1569 Tok.is(tok::raw_identifier) &&
1570 Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
Eric Liu93459d32016-12-19 10:41:05 +00001571 Tok.is(tok::raw_identifier);
Eric Liu35288322016-06-06 11:00:13 +00001572 if (Matched)
1573 Lex.LexFromRawLexer(Tok);
1574 return Matched;
1575}
1576
Eric Liu964782a2016-12-02 11:01:43 +00001577void skipComments(Lexer &Lex, Token &Tok) {
1578 while (Tok.is(tok::comment))
1579 if (Lex.LexFromRawLexer(Tok))
1580 return;
1581}
1582
1583// Returns the offset after header guard directives and any comments
1584// before/after header guards. If no header guard presents in the code, this
1585// will returns the offset after skipping all comments from the start of the
1586// code.
Eric Liu35288322016-06-06 11:00:13 +00001587unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
1588 StringRef Code,
Eric Liu43d67b62016-06-11 11:45:08 +00001589 const FormatStyle &Style) {
Eric Liu964782a2016-12-02 11:01:43 +00001590 return getOffsetAfterTokenSequence(
1591 FileName, Code, Style,
1592 [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1593 skipComments(Lex, Tok);
1594 unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
1595 if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
1596 skipComments(Lex, Tok);
1597 if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
1598 return SM.getFileOffset(Tok.getLocation());
1599 }
1600 return InitialOffset;
1601 });
1602}
1603
1604// Check if a sequence of tokens is like
1605// "#include ("header.h" | <header.h>)".
1606// If it is, \p Tok will be the token after this directive; otherwise, it can be
1607// any token after the given \p Tok (including \p Tok).
1608bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
1609 auto Matched = [&]() {
1610 Lex.LexFromRawLexer(Tok);
1611 return true;
1612 };
1613 if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1614 Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
1615 if (Lex.LexFromRawLexer(Tok))
1616 return false;
1617 if (Tok.is(tok::string_literal))
1618 return Matched();
1619 if (Tok.is(tok::less)) {
1620 while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
1621 }
1622 if (Tok.is(tok::greater))
1623 return Matched();
1624 }
Eric Liu35288322016-06-06 11:00:13 +00001625 }
Eric Liu964782a2016-12-02 11:01:43 +00001626 return false;
1627}
1628
1629// Returns the offset of the last #include directive after which a new
1630// #include can be inserted. This ignores #include's after the #include block(s)
1631// in the beginning of a file to avoid inserting headers into code sections
1632// where new #include's should not be added by default.
1633// These code sections include:
1634// - raw string literals (containing #include).
1635// - #if blocks.
1636// - Special #include's among declarations (e.g. functions).
1637//
1638// If no #include after which a new #include can be inserted, this returns the
1639// offset after skipping all comments from the start of the code.
1640// Inserting after an #include is not allowed if it comes after code that is not
1641// #include (e.g. pre-processing directive that is not #include, declarations).
1642unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
1643 const FormatStyle &Style) {
1644 return getOffsetAfterTokenSequence(
1645 FileName, Code, Style,
1646 [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1647 skipComments(Lex, Tok);
1648 unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
1649 while (checkAndConsumeInclusiveDirective(Lex, Tok))
1650 MaxOffset = SM.getFileOffset(Tok.getLocation());
1651 return MaxOffset;
1652 });
Eric Liu35288322016-06-06 11:00:13 +00001653}
1654
Eric Liuc0d3a802016-09-23 15:10:56 +00001655bool isDeletedHeader(llvm::StringRef HeaderName,
Benjamin Kramerebac56e2016-11-24 15:42:29 +00001656 const std::set<llvm::StringRef> &HeadersToDelete) {
1657 return HeadersToDelete.count(HeaderName) ||
1658 HeadersToDelete.count(HeaderName.trim("\"<>"));
Eric Liuc0d3a802016-09-23 15:10:56 +00001659}
1660
Eric Liu659afd52016-05-31 13:34:20 +00001661// FIXME: insert empty lines between newly created blocks.
1662tooling::Replacements
1663fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
1664 const FormatStyle &Style) {
Nico Weberd96ae862017-02-24 19:10:12 +00001665 if (!Style.IsCpp())
Eric Liu659afd52016-05-31 13:34:20 +00001666 return Replaces;
1667
1668 tooling::Replacements HeaderInsertions;
Eric Liuc0d3a802016-09-23 15:10:56 +00001669 std::set<llvm::StringRef> HeadersToDelete;
Eric Liu40ef2fb2016-08-01 10:16:37 +00001670 tooling::Replacements Result;
Eric Liu659afd52016-05-31 13:34:20 +00001671 for (const auto &R : Replaces) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001672 if (isHeaderInsertion(R)) {
1673 // Replacements from \p Replaces must be conflict-free already, so we can
1674 // simply consume the error.
1675 llvm::consumeError(HeaderInsertions.add(R));
Eric Liuc0d3a802016-09-23 15:10:56 +00001676 } else if (isHeaderDeletion(R)) {
1677 HeadersToDelete.insert(R.getReplacementText());
Eric Liu40ef2fb2016-08-01 10:16:37 +00001678 } else if (R.getOffset() == UINT_MAX) {
Eric Liu659afd52016-05-31 13:34:20 +00001679 llvm::errs() << "Insertions other than header #include insertion are "
1680 "not supported! "
1681 << R.getReplacementText() << "\n";
Eric Liu40ef2fb2016-08-01 10:16:37 +00001682 } else {
1683 llvm::consumeError(Result.add(R));
1684 }
Eric Liu659afd52016-05-31 13:34:20 +00001685 }
Eric Liuc0d3a802016-09-23 15:10:56 +00001686 if (HeaderInsertions.empty() && HeadersToDelete.empty())
Eric Liu659afd52016-05-31 13:34:20 +00001687 return Replaces;
Eric Liu659afd52016-05-31 13:34:20 +00001688
1689 llvm::Regex IncludeRegex(IncludeRegexPattern);
1690 llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)");
1691 SmallVector<StringRef, 4> Matches;
1692
1693 StringRef FileName = Replaces.begin()->getFilePath();
1694 IncludeCategoryManager Categories(Style, FileName);
1695
1696 // Record the offset of the end of the last include in each category.
1697 std::map<int, int> CategoryEndOffsets;
1698 // All possible priorities.
1699 // Add 0 for main header and INT_MAX for headers that are not in any category.
1700 std::set<int> Priorities = {0, INT_MAX};
1701 for (const auto &Category : Style.IncludeCategories)
1702 Priorities.insert(Category.Priority);
1703 int FirstIncludeOffset = -1;
Eric Liu35288322016-06-06 11:00:13 +00001704 // All new headers should be inserted after this offset.
1705 unsigned MinInsertOffset =
1706 getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style);
Eric Liu303baf52016-06-03 12:52:59 +00001707 StringRef TrimmedCode = Code.drop_front(MinInsertOffset);
Eric Liu21d10322016-12-09 11:45:50 +00001708 // Max insertion offset in the original code.
Eric Liu964782a2016-12-02 11:01:43 +00001709 unsigned MaxInsertOffset =
Eric Liu21d10322016-12-09 11:45:50 +00001710 MinInsertOffset +
Eric Liu964782a2016-12-02 11:01:43 +00001711 getMaxHeaderInsertionOffset(FileName, TrimmedCode, Style);
Eric Liu659afd52016-05-31 13:34:20 +00001712 SmallVector<StringRef, 32> Lines;
Eric Liu303baf52016-06-03 12:52:59 +00001713 TrimmedCode.split(Lines, '\n');
Eric Liu35288322016-06-06 11:00:13 +00001714 unsigned Offset = MinInsertOffset;
1715 unsigned NextLineOffset;
Eric Liu3753f912016-06-14 14:09:21 +00001716 std::set<StringRef> ExistingIncludes;
Eric Liu659afd52016-05-31 13:34:20 +00001717 for (auto Line : Lines) {
Eric Liu35288322016-06-06 11:00:13 +00001718 NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
Eric Liu659afd52016-05-31 13:34:20 +00001719 if (IncludeRegex.match(Line, &Matches)) {
Eric Liuc0d3a802016-09-23 15:10:56 +00001720 // The header name with quotes or angle brackets.
Eric Liu659afd52016-05-31 13:34:20 +00001721 StringRef IncludeName = Matches[2];
Eric Liu3753f912016-06-14 14:09:21 +00001722 ExistingIncludes.insert(IncludeName);
Eric Liu964782a2016-12-02 11:01:43 +00001723 // Only record the offset of current #include if we can insert after it.
1724 if (Offset <= MaxInsertOffset) {
1725 int Category = Categories.getIncludePriority(
1726 IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
1727 CategoryEndOffsets[Category] = NextLineOffset;
1728 if (FirstIncludeOffset < 0)
1729 FirstIncludeOffset = Offset;
1730 }
Eric Liuc0d3a802016-09-23 15:10:56 +00001731 if (isDeletedHeader(IncludeName, HeadersToDelete)) {
1732 // If this is the last line without trailing newline, we need to make
1733 // sure we don't delete across the file boundary.
1734 unsigned Length = std::min(Line.size() + 1, Code.size() - Offset);
1735 llvm::Error Err =
1736 Result.add(tooling::Replacement(FileName, Offset, Length, ""));
1737 if (Err) {
1738 // Ignore the deletion on conflict.
1739 llvm::errs() << "Failed to add header deletion replacement for "
1740 << IncludeName << ": " << llvm::toString(std::move(Err))
1741 << "\n";
1742 }
1743 }
Eric Liu659afd52016-05-31 13:34:20 +00001744 }
Eric Liu35288322016-06-06 11:00:13 +00001745 Offset = NextLineOffset;
Eric Liu659afd52016-05-31 13:34:20 +00001746 }
1747
1748 // Populate CategoryEndOfssets:
1749 // - Ensure that CategoryEndOffset[Highest] is always populated.
1750 // - If CategoryEndOffset[Priority] isn't set, use the next higher value that
1751 // is set, up to CategoryEndOffset[Highest].
Eric Liu659afd52016-05-31 13:34:20 +00001752 auto Highest = Priorities.begin();
1753 if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
1754 if (FirstIncludeOffset >= 0)
1755 CategoryEndOffsets[*Highest] = FirstIncludeOffset;
1756 else
Eric Liu303baf52016-06-03 12:52:59 +00001757 CategoryEndOffsets[*Highest] = MinInsertOffset;
Eric Liu659afd52016-05-31 13:34:20 +00001758 }
1759 // By this point, CategoryEndOffset[Highest] is always set appropriately:
1760 // - to an appropriate location before/after existing #includes, or
1761 // - to right after the header guard, or
1762 // - to the beginning of the file.
1763 for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
1764 if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
1765 CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
1766
Eric Liu11a42372016-10-05 15:42:19 +00001767 bool NeedNewLineAtEnd = !Code.empty() && Code.back() != '\n';
Eric Liu659afd52016-05-31 13:34:20 +00001768 for (const auto &R : HeaderInsertions) {
1769 auto IncludeDirective = R.getReplacementText();
1770 bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
1771 assert(Matched && "Header insertion replacement must have replacement text "
1772 "'#include ...'");
Benjamin Kramer1cb7ee12016-05-31 14:14:42 +00001773 (void)Matched;
Eric Liu659afd52016-05-31 13:34:20 +00001774 auto IncludeName = Matches[2];
Eric Liu3753f912016-06-14 14:09:21 +00001775 if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) {
1776 DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName
1777 << "\n");
1778 continue;
1779 }
Eric Liu659afd52016-05-31 13:34:20 +00001780 int Category =
1781 Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true);
1782 Offset = CategoryEndOffsets[Category];
1783 std::string NewInclude = !IncludeDirective.endswith("\n")
1784 ? (IncludeDirective + "\n").str()
1785 : IncludeDirective.str();
Eric Liu11a42372016-10-05 15:42:19 +00001786 // When inserting headers at end of the code, also append '\n' to the code
1787 // if it does not end with '\n'.
1788 if (NeedNewLineAtEnd && Offset == Code.size()) {
1789 NewInclude = "\n" + NewInclude;
1790 NeedNewLineAtEnd = false;
1791 }
Eric Liu40ef2fb2016-08-01 10:16:37 +00001792 auto NewReplace = tooling::Replacement(FileName, Offset, 0, NewInclude);
1793 auto Err = Result.add(NewReplace);
1794 if (Err) {
1795 llvm::consumeError(std::move(Err));
Eric Liu11a42372016-10-05 15:42:19 +00001796 unsigned NewOffset = Result.getShiftedCodePosition(Offset);
1797 NewReplace = tooling::Replacement(FileName, NewOffset, 0, NewInclude);
Eric Liu40ef2fb2016-08-01 10:16:37 +00001798 Result = Result.merge(tooling::Replacements(NewReplace));
1799 }
Eric Liu659afd52016-05-31 13:34:20 +00001800 }
1801 return Result;
1802}
1803
1804} // anonymous namespace
1805
Eric Liu4f8d9942016-07-11 13:53:12 +00001806llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001807cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1808 const FormatStyle &Style) {
1809 // We need to use lambda function here since there are two versions of
1810 // `cleanup`.
1811 auto Cleanup = [](const FormatStyle &Style, StringRef Code,
1812 std::vector<tooling::Range> Ranges,
1813 StringRef FileName) -> tooling::Replacements {
1814 return cleanup(Style, Code, Ranges, FileName);
1815 };
Eric Liu659afd52016-05-31 13:34:20 +00001816 // Make header insertion replacements insert new headers into correct blocks.
1817 tooling::Replacements NewReplaces =
1818 fixCppIncludeInsertions(Code, Replaces, Style);
1819 return processReplacements(Cleanup, Code, NewReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001820}
1821
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001822tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001823 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001824 StringRef FileName, bool *IncompleteFormat) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001825 FormatStyle Expanded = expandPresets(Style);
1826 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001827 return tooling::Replacements();
Martin Probstfa37b182017-01-27 09:09:11 +00001828 if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
1829 return tooling::Replacements();
Daniel Jasper496c1992016-09-07 22:48:53 +00001830 auto Env = Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1831
1832 if (Style.Language == FormatStyle::LK_JavaScript &&
1833 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
1834 JavaScriptRequoter Requoter(*Env, Expanded);
1835 tooling::Replacements Requotes = Requoter.process();
1836 if (!Requotes.empty()) {
1837 auto NewCode = applyAllReplacements(Code, Requotes);
1838 if (NewCode) {
1839 auto NewEnv = Environment::CreateVirtualEnvironment(
1840 *NewCode, FileName,
1841 tooling::calculateRangesAfterReplacements(Requotes, Ranges));
1842 Formatter Format(*NewEnv, Expanded, IncompleteFormat);
1843 return Requotes.merge(Format.process());
1844 }
1845 }
1846 }
1847
Eric Liu635423e2016-04-28 07:52:03 +00001848 Formatter Format(*Env, Expanded, IncompleteFormat);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001849 return Format.process();
1850}
1851
Eric Liu4cfb88a2016-04-25 15:09:22 +00001852tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1853 ArrayRef<tooling::Range> Ranges,
1854 StringRef FileName) {
1855 std::unique_ptr<Environment> Env =
Eric Liu635423e2016-04-28 07:52:03 +00001856 Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1857 Cleaner Clean(*Env, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001858 return Clean.process();
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001859}
1860
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00001861tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1862 StringRef Code,
1863 ArrayRef<tooling::Range> Ranges,
1864 StringRef FileName) {
1865 std::unique_ptr<Environment> Env =
1866 Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
1867 NamespaceEndCommentsFixer Fix(*Env, Style);
1868 return Fix.process();
1869}
1870
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001871LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001872 LangOptions LangOpts;
1873 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001874 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1875 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001876 LangOpts.LineComment = 1;
Nico Weberd96ae862017-02-24 19:10:12 +00001877 bool AlternativeOperators = Style.IsCpp();
Daniel Jasper30a24062014-11-14 09:02:28 +00001878 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001879 LangOpts.Bool = 1;
1880 LangOpts.ObjC1 = 1;
1881 LangOpts.ObjC2 = 1;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001882 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001883 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001884 return LangOpts;
1885}
1886
Edwin Vaned544aa72013-09-30 13:31:48 +00001887const char *StyleOptionHelpDescription =
1888 "Coding style, currently supports:\n"
1889 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1890 "Use -style=file to load style configuration from\n"
1891 ".clang-format file located in one of the parent\n"
1892 "directories of the source file (or current\n"
1893 "directory for stdin).\n"
1894 "Use -style=\"{key: value, ...}\" to set specific\n"
1895 "parameters, e.g.:\n"
1896 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1897
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001898static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasper498f5582015-12-25 08:53:31 +00001899 if (FileName.endswith(".java"))
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001900 return FormatStyle::LK_Java;
Daniel Jasper498f5582015-12-25 08:53:31 +00001901 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
1902 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
Daniel Jasper03a04fe2016-12-12 12:42:29 +00001903 if (FileName.endswith(".m") || FileName.endswith(".mm"))
1904 return FormatStyle::LK_ObjC;
Daniel Jasper498f5582015-12-25 08:53:31 +00001905 if (FileName.endswith_lower(".proto") ||
1906 FileName.endswith_lower(".protodevel"))
Daniel Jasper7052ce62014-01-19 09:04:08 +00001907 return FormatStyle::LK_Proto;
Daniel Jasper498f5582015-12-25 08:53:31 +00001908 if (FileName.endswith_lower(".td"))
1909 return FormatStyle::LK_TableGen;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001910 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001911}
1912
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001913llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
Antonio Maiorano7eb75072017-01-20 01:22:42 +00001914 StringRef FallbackStyleName,
1915 StringRef Code, vfs::FileSystem *FS) {
Eric Liu547d8792016-03-24 13:22:42 +00001916 if (!FS) {
1917 FS = vfs::getRealFileSystem().get();
1918 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001919 FormatStyle Style = getLLVMStyle();
1920 Style.Language = getLanguageByFileName(FileName);
Daniel Jasper03a04fe2016-12-12 12:42:29 +00001921
1922 // This is a very crude detection of whether a header contains ObjC code that
1923 // should be improved over time and probably be done on tokens, not one the
1924 // bare content of the file.
1925 if (Style.Language == FormatStyle::LK_Cpp && FileName.endswith(".h") &&
1926 (Code.contains("\n- (") || Code.contains("\n+ (")))
1927 Style.Language = FormatStyle::LK_ObjC;
1928
Antonio Maiorano7eb75072017-01-20 01:22:42 +00001929 FormatStyle FallbackStyle = getNoStyle();
1930 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
1931 return make_string_error("Invalid fallback style \"" + FallbackStyleName);
Edwin Vaned544aa72013-09-30 13:31:48 +00001932
1933 if (StyleName.startswith("{")) {
1934 // Parse YAML/JSON style from the command line.
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001935 if (std::error_code ec = parseConfiguration(StyleName, &Style))
1936 return make_string_error("Error parsing -style: " + ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00001937 return Style;
1938 }
1939
1940 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001941 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001942 return make_string_error("Invalid value for -style");
Edwin Vaned544aa72013-09-30 13:31:48 +00001943 return Style;
1944 }
1945
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001946 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001947 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001948 SmallString<128> Path(FileName);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001949 if (std::error_code EC = FS->makeAbsolute(Path))
1950 return make_string_error(EC.message());
Antonio Maiorano34c03762016-12-22 05:10:07 +00001951
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001952 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001953 Directory = llvm::sys::path::parent_path(Directory)) {
Eric Liu547d8792016-03-24 13:22:42 +00001954
1955 auto Status = FS->status(Directory);
1956 if (!Status ||
1957 Status->getType() != llvm::sys::fs::file_type::directory_file) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001958 continue;
Eric Liu547d8792016-03-24 13:22:42 +00001959 }
1960
Edwin Vaned544aa72013-09-30 13:31:48 +00001961 SmallString<128> ConfigFile(Directory);
1962
1963 llvm::sys::path::append(ConfigFile, ".clang-format");
1964 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liud4758322016-03-24 13:22:37 +00001965
Eric Liu547d8792016-03-24 13:22:42 +00001966 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001967 bool FoundConfigFile =
Eric Liu547d8792016-03-24 13:22:42 +00001968 Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001969 if (!FoundConfigFile) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001970 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1971 ConfigFile = Directory;
1972 llvm::sys::path::append(ConfigFile, "_clang-format");
1973 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liu547d8792016-03-24 13:22:42 +00001974 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001975 FoundConfigFile = Status && (Status->getType() ==
1976 llvm::sys::fs::file_type::regular_file);
Edwin Vaned544aa72013-09-30 13:31:48 +00001977 }
1978
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001979 if (FoundConfigFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001980 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
Eric Liu547d8792016-03-24 13:22:42 +00001981 FS->getBufferForFile(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001982 if (std::error_code EC = Text.getError())
1983 return make_string_error(EC.message());
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001984 if (std::error_code ec =
1985 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001986 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001987 if (!UnsuitableConfigFiles.empty())
1988 UnsuitableConfigFiles.append(", ");
1989 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001990 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001991 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001992 return make_string_error("Error reading " + ConfigFile + ": " +
1993 ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00001994 }
1995 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1996 return Style;
1997 }
1998 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00001999 if (!UnsuitableConfigFiles.empty())
2000 return make_string_error("Configuration file(s) do(es) not support " +
2001 getLanguageName(Style.Language) + ": " +
2002 UnsuitableConfigFiles);
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002003 return FallbackStyle;
Edwin Vaned544aa72013-09-30 13:31:48 +00002004}
2005
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002006} // namespace format
2007} // namespace clang