blob: cc11d3df400c04a27741a5c2af77db2ce9a2d061 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasper85c472d2015-09-29 07:53:08 +000016#include "clang/Format/Format.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000017#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000019#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Marianne Mailhot-Sarrasin4988fa12016-04-14 14:47:37 +000025#include "clang/Basic/VirtualFileSystem.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000030#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000031#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000032#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000033#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000034#include <string>
35
Chandler Carruth10346662014-04-22 03:17:02 +000036#define DEBUG_TYPE "format-formatter"
37
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000038using clang::format::FormatStyle;
39
Daniel Jaspere1e43192014-04-01 12:55:11 +000040LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +000041LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
Daniel Jaspere1e43192014-04-01 12:55:11 +000042
Alexander Kornienkod6538332013-05-07 15:32:14 +000043namespace llvm {
44namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
46 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
47 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000048 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000049 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000050 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Daniel Jasper498f5582015-12-25 08:53:31 +000051 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000052 }
53};
54
55template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
56 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
57 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
58 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
59 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
60 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
61 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
62 }
63};
64
65template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
66 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
67 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
68 IO.enumCase(Value, "false", FormatStyle::UT_Never);
69 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
70 IO.enumCase(Value, "true", FormatStyle::UT_Always);
71 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
72 }
73};
74
Daniel Jasperabd1f572016-03-02 22:44:03 +000075template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
76 static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
77 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
78 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
79 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
80 }
81};
82
Daniel Jasperd74cf402014-04-08 12:46:38 +000083template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
84 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
85 IO.enumCase(Value, "None", FormatStyle::SFS_None);
86 IO.enumCase(Value, "false", FormatStyle::SFS_None);
87 IO.enumCase(Value, "All", FormatStyle::SFS_All);
88 IO.enumCase(Value, "true", FormatStyle::SFS_All);
89 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000090 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000091 }
92};
93
Daniel Jasperac043c92014-09-15 11:11:00 +000094template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
95 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
96 IO.enumCase(Value, "All", FormatStyle::BOS_All);
97 IO.enumCase(Value, "true", FormatStyle::BOS_All);
98 IO.enumCase(Value, "None", FormatStyle::BOS_None);
99 IO.enumCase(Value, "false", FormatStyle::BOS_None);
100 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
101 }
102};
103
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
105 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
106 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
107 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000108 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000109 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
110 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000111 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000112 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000113 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114 }
115};
116
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000117template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000118struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
119 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
120 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
121 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
122 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
123 IO.enumCase(Value, "TopLevelDefinitions",
124 FormatStyle::RTBS_TopLevelDefinitions);
125 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
126 }
127};
128
129template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000130struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
131 static void
132 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000133 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
134 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
135 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
136
137 // For backward compatibility.
138 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
139 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
140 }
141};
142
Alexander Kornienkod6538332013-05-07 15:32:14 +0000143template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000144struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000145 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000146 FormatStyle::NamespaceIndentationKind &Value) {
147 IO.enumCase(Value, "None", FormatStyle::NI_None);
148 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
149 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000150 }
151};
152
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000153template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
154 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
155 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
156 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
157 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
158
159 // For backward compatibility.
160 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
161 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
162 }
163};
164
Jacques Pienaarfc275112015-02-18 23:48:37 +0000165template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
166 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000167 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
168 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
169 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
170
Alp Toker958027b2014-07-14 19:42:55 +0000171 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000172 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
173 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
174 }
175};
176
177template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000178struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000179 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000180 FormatStyle::SpaceBeforeParensOptions &Value) {
181 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000182 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000183 FormatStyle::SBPO_ControlStatements);
184 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000185
186 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000187 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
188 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000189 }
190};
191
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000192template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000193 static void mapping(IO &IO, FormatStyle &Style) {
194 // When reading, read the language first, we need it for getPredefinedStyle.
195 IO.mapOptional("Language", Style.Language);
196
Alexander Kornienko49149672013-05-10 11:56:10 +0000197 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000198 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
199 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000200 ArrayRef<StringRef> Styles(StylesArray);
201 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
202 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000203 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000204 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000205 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000206 IO.mapOptional("# BasedOnStyle", StyleName);
207 break;
208 }
209 }
210 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000211 StringRef BasedOnStyle;
212 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000213 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000214 FormatStyle::LanguageKind OldLanguage = Style.Language;
215 FormatStyle::LanguageKind Language =
216 ((FormatStyle *)IO.getContext())->Language;
217 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000218 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
219 return;
220 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000221 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000222 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000223 }
224
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000225 // For backward compatibility.
226 if (!IO.outputting()) {
227 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
228 IO.mapOptional("IndentFunctionDeclarationAfterType",
229 Style.IndentWrappedFunctionNames);
230 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
231 IO.mapOptional("SpaceAfterControlStatementKeyword",
232 Style.SpaceBeforeParens);
233 }
234
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000236 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000237 IO.mapOptional("AlignConsecutiveAssignments",
238 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000239 IO.mapOptional("AlignConsecutiveDeclarations",
240 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000241 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000242 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000243 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000244 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
245 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000246 IO.mapOptional("AllowShortBlocksOnASingleLine",
247 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000248 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
249 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000250 IO.mapOptional("AllowShortFunctionsOnASingleLine",
251 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000252 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
253 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000254 IO.mapOptional("AllowShortLoopsOnASingleLine",
255 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000256 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
257 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000258 IO.mapOptional("AlwaysBreakAfterReturnType",
259 Style.AlwaysBreakAfterReturnType);
260 // If AlwaysBreakAfterDefinitionReturnType was specified but
261 // AlwaysBreakAfterReturnType was not, initialize the latter from the
262 // former for backwards compatibility.
263 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
264 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
265 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
266 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
267 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
268 FormatStyle::DRTBS_TopLevel)
269 Style.AlwaysBreakAfterReturnType =
270 FormatStyle::RTBS_TopLevelDefinitions;
271 }
272
Alexander Kornienko58611712013-07-04 12:02:44 +0000273 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
274 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000275 IO.mapOptional("AlwaysBreakTemplateDeclarations",
276 Style.AlwaysBreakTemplateDeclarations);
277 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
278 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000279 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000280 IO.mapOptional("BreakBeforeBinaryOperators",
281 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000282 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000283 IO.mapOptional("BreakBeforeTernaryOperators",
284 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000285 IO.mapOptional("BreakConstructorInitializersBeforeComma",
286 Style.BreakConstructorInitializersBeforeComma);
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000287 IO.mapOptional("BreakAfterJavaFieldAnnotations",
288 Style.BreakAfterJavaFieldAnnotations);
289 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000290 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000291 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000292 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
293 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000294 IO.mapOptional("ConstructorInitializerIndentWidth",
295 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000296 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
297 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000298 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000299 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000300 IO.mapOptional("ExperimentalAutoDetectBinPacking",
301 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000302 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000303 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000304 IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000305 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000306 IO.mapOptional("IndentWidth", Style.IndentWidth);
307 IO.mapOptional("IndentWrappedFunctionNames",
308 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000309 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
310 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000311 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
312 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000313 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000314 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000315 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000316 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000317 IO.mapOptional("ObjCSpaceBeforeProtocolList",
318 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000319 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
320 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000321 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000322 IO.mapOptional("PenaltyBreakFirstLessLess",
323 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000324 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000325 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
326 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
327 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000328 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000329 IO.mapOptional("ReflowComments", Style.ReflowComments);
330 IO.mapOptional("SortIncludes", Style.SortIncludes);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000331 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000332 IO.mapOptional("SpaceBeforeAssignmentOperators",
333 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000334 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
335 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
336 IO.mapOptional("SpacesBeforeTrailingComments",
337 Style.SpacesBeforeTrailingComments);
338 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
339 IO.mapOptional("SpacesInContainerLiterals",
340 Style.SpacesInContainerLiterals);
341 IO.mapOptional("SpacesInCStyleCastParentheses",
342 Style.SpacesInCStyleCastParentheses);
343 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
344 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
345 IO.mapOptional("Standard", Style.Standard);
346 IO.mapOptional("TabWidth", Style.TabWidth);
347 IO.mapOptional("UseTab", Style.UseTab);
Daniel Jasperabd1f572016-03-02 22:44:03 +0000348 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000349 }
350};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000351
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000352template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
353 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
354 IO.mapOptional("AfterClass", Wrapping.AfterClass);
355 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
356 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
357 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
358 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
359 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
360 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
361 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
362 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
363 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
364 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
365 }
366};
367
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000368template <> struct MappingTraits<FormatStyle::IncludeCategory> {
369 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
370 IO.mapOptional("Regex", Category.Regex);
371 IO.mapOptional("Priority", Category.Priority);
372 }
373};
374
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000375// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000376// IO.getContext() should contain a pointer to the FormatStyle structure, that
377// will be used to get default values for missing keys.
378// If the first element has no Language specified, it will be treated as the
379// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000380template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000381 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
382 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000383 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000384 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000385 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000386 if (Index >= Seq.size()) {
387 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000388 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000389 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000390 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000391 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000392 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000393 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000394 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000395 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000396 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000397 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000398 }
399};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000400} // namespace yaml
401} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000402
Daniel Jasperf7935112012-12-03 18:12:45 +0000403namespace clang {
404namespace format {
405
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000406const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000407 static ParseErrorCategory C;
408 return C;
409}
410std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000411 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000412}
413
414const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
415 return "clang-format.parse_error";
416}
417
418std::string ParseErrorCategory::message(int EV) const {
419 switch (static_cast<ParseError>(EV)) {
420 case ParseError::Success:
421 return "Success";
422 case ParseError::Error:
423 return "Invalid argument";
424 case ParseError::Unsuitable:
425 return "Unsuitable";
426 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000427 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000428}
429
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000430static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000431 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
432 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000433 FormatStyle Expanded = Style;
434 Expanded.BraceWrapping = {false, false, false, false, false, false,
435 false, false, false, false, false};
436 switch (Style.BreakBeforeBraces) {
437 case FormatStyle::BS_Linux:
438 Expanded.BraceWrapping.AfterClass = true;
439 Expanded.BraceWrapping.AfterFunction = true;
440 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000441 break;
442 case FormatStyle::BS_Mozilla:
443 Expanded.BraceWrapping.AfterClass = true;
444 Expanded.BraceWrapping.AfterEnum = true;
445 Expanded.BraceWrapping.AfterFunction = true;
446 Expanded.BraceWrapping.AfterStruct = true;
447 Expanded.BraceWrapping.AfterUnion = true;
448 break;
449 case FormatStyle::BS_Stroustrup:
450 Expanded.BraceWrapping.AfterFunction = true;
451 Expanded.BraceWrapping.BeforeCatch = true;
452 Expanded.BraceWrapping.BeforeElse = true;
453 break;
454 case FormatStyle::BS_Allman:
455 Expanded.BraceWrapping.AfterClass = true;
456 Expanded.BraceWrapping.AfterControlStatement = true;
457 Expanded.BraceWrapping.AfterEnum = true;
458 Expanded.BraceWrapping.AfterFunction = true;
459 Expanded.BraceWrapping.AfterNamespace = true;
460 Expanded.BraceWrapping.AfterObjCDeclaration = true;
461 Expanded.BraceWrapping.AfterStruct = true;
462 Expanded.BraceWrapping.BeforeCatch = true;
463 Expanded.BraceWrapping.BeforeElse = true;
464 break;
465 case FormatStyle::BS_GNU:
466 Expanded.BraceWrapping = {true, true, true, true, true, true,
467 true, true, true, true, true};
468 break;
469 case FormatStyle::BS_WebKit:
470 Expanded.BraceWrapping.AfterFunction = true;
471 break;
472 default:
473 break;
474 }
475 return Expanded;
476}
477
Daniel Jasperf7935112012-12-03 18:12:45 +0000478FormatStyle getLLVMStyle() {
479 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000480 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000481 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000482 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000483 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000484 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000485 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000486 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000487 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000488 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000489 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000490 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000491 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000492 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000493 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000494 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000495 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000496 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000497 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000498 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000499 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000500 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000501 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000502 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000503 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
504 false, false, false, false, false};
Nico Weber2cd92f12015-10-15 16:03:01 +0000505 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000506 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
507 LLVMStyle.BreakStringLiterals = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000508 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000509 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000510 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000511 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000512 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000513 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000514 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000515 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000516 LLVMStyle.ForEachMacros.push_back("foreach");
517 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
518 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000519 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
520 {"^(<|\"(gtest|isl|json)/)", 3},
521 {".*", 1}};
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000522 LLVMStyle.IncludeIsMainRegex = "$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000523 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000524 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000525 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000526 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000527 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000528 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000529 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000530 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000531 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000532 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000533 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000534 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000535 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000536 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000537 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000538 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000539 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000540 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000541 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000542 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000543 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000544 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000545 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000546 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000547 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000548
Daniel Jasper19a541e2013-12-19 16:45:34 +0000549 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000550 LLVMStyle.PenaltyBreakFirstLessLess = 120;
551 LLVMStyle.PenaltyBreakString = 1000;
552 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000553 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000554 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000555
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000556 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000557 LLVMStyle.SortIncludes = true;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000558
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 return LLVMStyle;
560}
561
Nico Weber514ecc82014-02-02 20:50:45 +0000562FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000563 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000564 GoogleStyle.Language = Language;
565
Daniel Jasperf7935112012-12-03 18:12:45 +0000566 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000567 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000568 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000569 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000570 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000571 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000572 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000573 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000574 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000575 GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000576 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000577 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000578 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000579 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000580 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000581 GoogleStyle.SpacesBeforeTrailingComments = 2;
582 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000583
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000584 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000585 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000586
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000587 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000588 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000589 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000590 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000591 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000592 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000593 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000594 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
595 GoogleStyle.ColumnLimit = 100;
596 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000597 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000598 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000599 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000600 GoogleStyle.AlignOperands = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000601 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
602 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000603 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper2bc38702016-02-22 20:24:11 +0000604 GoogleStyle.CommentPragmas = "@(export|return|see|visibility) ";
Daniel Jasper8f83a902014-05-09 10:28:58 +0000605 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000606 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000607 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
Nico Weber514ecc82014-02-02 20:50:45 +0000608 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000609 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000610 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000611 }
612
Daniel Jasperf7935112012-12-03 18:12:45 +0000613 return GoogleStyle;
614}
615
Nico Weber514ecc82014-02-02 20:50:45 +0000616FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
617 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000618 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000619 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000620 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000621 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000622 ChromiumStyle.IndentWidth = 4;
Nico Weber450425c2014-11-26 16:43:18 +0000623 } else {
624 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
625 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
626 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
627 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
628 ChromiumStyle.BinPackParameters = false;
629 ChromiumStyle.DerivePointerAlignment = false;
630 }
Nico Weberb10423a2015-12-22 22:42:56 +0000631 ChromiumStyle.SortIncludes = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000632 return ChromiumStyle;
633}
634
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000635FormatStyle getMozillaStyle() {
636 FormatStyle MozillaStyle = getLLVMStyle();
637 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000638 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Zachary Turner448592e2015-12-18 22:20:15 +0000639 MozillaStyle.AlwaysBreakAfterReturnType =
640 FormatStyle::RTBS_TopLevelDefinitions;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000641 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
642 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000643 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000644 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000645 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
646 MozillaStyle.ConstructorInitializerIndentWidth = 2;
647 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000648 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000649 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000650 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000651 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
652 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000653 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000654 return MozillaStyle;
655}
656
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000657FormatStyle getWebKitStyle() {
658 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000659 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000660 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000661 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000662 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000663 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000664 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000665 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000666 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000667 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000668 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000669 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000670 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000671 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000672 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000673 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000674 return Style;
675}
676
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000677FormatStyle getGNUStyle() {
678 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000679 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000680 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000681 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000682 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000683 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000684 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000685 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000686 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000687 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000688 return Style;
689}
690
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000691FormatStyle getNoStyle() {
692 FormatStyle NoStyle = getLLVMStyle();
693 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000694 NoStyle.SortIncludes = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000695 return NoStyle;
696}
697
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000698bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
699 FormatStyle *Style) {
700 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000701 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000702 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000703 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000704 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000705 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000706 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000707 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000708 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000709 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000710 } else if (Name.equals_lower("gnu")) {
711 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000712 } else if (Name.equals_lower("none")) {
713 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000714 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000715 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000716 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000717
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000718 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000719 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000720}
721
Rafael Espindolac0809172014-06-12 14:02:15 +0000722std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000723 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000724 FormatStyle::LanguageKind Language = Style->Language;
725 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000726 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000727 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000728
729 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000730 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000731 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
732 // values for the fields, keys for which are missing from the configuration.
733 // Mapping also uses the context to get the language to find the correct
734 // base style.
735 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000736 Input >> Styles;
737 if (Input.error())
738 return Input.error();
739
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000740 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000741 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000742 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000743 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000744 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000745 for (unsigned j = 0; j < i; ++j) {
746 if (Styles[i].Language == Styles[j].Language) {
747 DEBUG(llvm::dbgs()
748 << "Duplicate languages in the config file on positions " << j
749 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000750 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000751 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000752 }
753 }
754 // Look for a suitable configuration starting from the end, so we can
755 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000756 // configuration (which can only be at slot 0) after it.
757 for (int i = Styles.size() - 1; i >= 0; --i) {
758 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000759 Styles[i].Language == FormatStyle::LK_None) {
760 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000761 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000762 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000763 }
764 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000765 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000766}
767
768std::string configurationAsText(const FormatStyle &Style) {
769 std::string Text;
770 llvm::raw_string_ostream Stream(Text);
771 llvm::yaml::Output Output(Stream);
772 // We use the same mapping method for input and output, so we need a non-const
773 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000774 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000775 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000776 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000777}
778
Craig Topperaf35e852013-06-30 22:29:28 +0000779namespace {
780
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000781class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000782public:
Daniel Jasper23376252014-09-09 14:37:39 +0000783 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Daniel Jasper97439922016-03-17 13:03:41 +0000784 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000785 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000786 LessStashed(false), Column(0), TrailingWhitespace(0),
787 SourceMgr(SourceMgr), ID(ID), Style(Style),
788 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Daniel Jasper97439922016-03-17 13:03:41 +0000789 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
790 MacroBlockBeginRegex(Style.MacroBlockBegin),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000791 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000792 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
793 getFormattingLangOpts(Style)));
794 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000795
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000796 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000797 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
798 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000799 }
800
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000801 ArrayRef<FormatToken *> lex() {
802 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000803 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000804 do {
805 Tokens.push_back(getNextToken());
Daniel Jasper265309e2015-10-18 07:02:28 +0000806 if (Style.Language == FormatStyle::LK_JavaScript)
807 tryParseJSRegexLiteral();
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000808 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000809 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000810 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000811 } while (Tokens.back()->Tok.isNot(tok::eof));
812 return Tokens;
813 }
814
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000815 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000816
817private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000818 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000819 if (tryMerge_TMacro())
820 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000821 if (tryMergeConflictMarkers())
822 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000823 if (tryMergeLessLess())
824 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000825
826 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000827 if (tryMergeTemplateString())
828 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000829
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000830 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
831 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
832 tok::equal};
833 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
834 tok::greaterequal};
835 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000836 // FIXME: Investigate what token type gives the correct operator priority.
837 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000838 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000839 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000840 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000841 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000842 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000843 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000844 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000845 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000846 }
847
Jacques Pienaarfc275112015-02-18 23:48:37 +0000848 bool tryMergeLessLess() {
849 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000850 if (Tokens.size() < 3)
851 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000852
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000853 bool FourthTokenIsLess = false;
854 if (Tokens.size() > 3)
855 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000856
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000857 auto First = Tokens.end() - 3;
858 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
859 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000860 return false;
861
862 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000863 if (First[1]->WhitespaceRange.getBegin() !=
864 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000865 return false;
866
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000867 First[0]->Tok.setKind(tok::lessless);
868 First[0]->TokenText = "<<";
869 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000870 Tokens.erase(Tokens.end() - 2);
871 return true;
872 }
873
Manuel Klimek79e06082015-05-21 12:23:34 +0000874 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000875 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000876 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000877
878 SmallVectorImpl<FormatToken *>::const_iterator First =
879 Tokens.end() - Kinds.size();
880 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000881 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000882 unsigned AddLength = 0;
883 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000884 if (!First[i]->is(Kinds[i]) ||
885 First[i]->WhitespaceRange.getBegin() !=
886 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000887 return false;
888 AddLength += First[i]->TokenText.size();
889 }
890 Tokens.resize(Tokens.size() - Kinds.size() + 1);
891 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
892 First[0]->TokenText.size() + AddLength);
893 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000894 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000895 return true;
896 }
897
Daniel Jasper265309e2015-10-18 07:02:28 +0000898 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
899 bool precedesOperand(FormatToken *Tok) {
900 // NB: This is not entirely correct, as an r_paren can introduce an operand
901 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
902 // corner case to not matter in practice, though.
903 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
904 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
905 tok::colon, tok::question, tok::tilde) ||
906 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
907 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
908 tok::kw_typeof, Keywords.kw_instanceof,
909 Keywords.kw_in) ||
910 Tok->isBinaryOperator();
911 }
912
913 bool canPrecedeRegexLiteral(FormatToken *Prev) {
914 if (!Prev)
915 return true;
916
917 // Regex literals can only follow after prefix unary operators, not after
918 // postfix unary operators. If the '++' is followed by a non-operand
919 // introducing token, the slash here is the operand and not the start of a
920 // regex.
921 if (Prev->isOneOf(tok::plusplus, tok::minusminus))
922 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
923
924 // The previous token must introduce an operand location where regex
925 // literals can occur.
926 if (!precedesOperand(Prev))
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000927 return false;
Daniel Jasper265309e2015-10-18 07:02:28 +0000928
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000929 return true;
930 }
931
Daniel Jasper265309e2015-10-18 07:02:28 +0000932 // Tries to parse a JavaScript Regex literal starting at the current token,
933 // if that begins with a slash and is in a location where JavaScript allows
934 // regex literals. Changes the current token to a regex literal and updates
935 // its text if successful.
936 void tryParseJSRegexLiteral() {
937 FormatToken *RegexToken = Tokens.back();
938 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
939 return;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000940
Daniel Jasper265309e2015-10-18 07:02:28 +0000941 FormatToken *Prev = nullptr;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000942 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
Daniel Jasper265309e2015-10-18 07:02:28 +0000943 // NB: Because previous pointers are not initialized yet, this cannot use
944 // Token.getPreviousNonComment.
945 if ((*I)->isNot(tok::comment)) {
946 Prev = *I;
947 break;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000948 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000949 }
Daniel Jasper265309e2015-10-18 07:02:28 +0000950
951 if (!canPrecedeRegexLiteral(Prev))
952 return;
953
954 // 'Manually' lex ahead in the current file buffer.
955 const char *Offset = Lex->getBufferLocation();
956 const char *RegexBegin = Offset - RegexToken->TokenText.size();
957 StringRef Buffer = Lex->getBuffer();
958 bool InCharacterClass = false;
959 bool HaveClosingSlash = false;
960 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
961 // Regular expressions are terminated with a '/', which can only be
962 // escaped using '\' or a character class between '[' and ']'.
963 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
964 switch (*Offset) {
965 case '\\':
966 // Skip the escaped character.
967 ++Offset;
968 break;
969 case '[':
970 InCharacterClass = true;
971 break;
972 case ']':
973 InCharacterClass = false;
974 break;
975 case '/':
976 if (!InCharacterClass)
977 HaveClosingSlash = true;
978 break;
979 }
980 }
981
982 RegexToken->Type = TT_RegexLiteral;
983 // Treat regex literals like other string_literals.
984 RegexToken->Tok.setKind(tok::string_literal);
985 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
986 RegexToken->ColumnWidth = RegexToken->TokenText.size();
987
988 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000989 }
990
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000991 bool tryMergeTemplateString() {
992 if (Tokens.size() < 2)
993 return false;
994
995 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000996 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000997 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
998 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000999 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
1000 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +00001001 return false;
1002 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
1003 // Unknown token that's not actually a backtick, or a comment that doesn't
1004 // contain a backtick.
1005 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001006 return false;
1007
1008 unsigned TokenCount = 0;
1009 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +00001010 unsigned EndColumnInFirstLine =
1011 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001012 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
1013 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001014 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001015 IsMultiline = true;
1016
1017 // If there was a preceding template string, this must be the start of a
1018 // template string, not the end.
1019 if (I[0]->is(TT_TemplateString))
1020 return false;
1021
1022 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
1023 // Keep track of the rhs offset of the last token to wrap across lines -
1024 // its the rhs offset of the first line of the template string, used to
1025 // determine its width.
1026 if (I[0]->IsMultiline)
1027 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
1028 // If the token has newlines, the token before it (if it exists) is the
1029 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +00001030 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001031 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001032 IsMultiline = true;
1033 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001034 continue;
1035 }
1036
1037 Tokens.resize(Tokens.size() - TokenCount);
1038 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +00001039 const char *EndOffset =
1040 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
1041 if (CommentBacktickPos != 0) {
1042 // If the backtick was not the first character (e.g. in a comment),
1043 // re-lex after the backtick position.
1044 SourceLocation Loc = EndBacktick->Tok.getLocation();
1045 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
1046 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001047 Tokens.back()->TokenText =
1048 StringRef(Tokens.back()->TokenText.data(),
1049 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +00001050
1051 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
1052 if (EndOriginalColumn == 0) {
1053 SourceLocation Loc = EndBacktick->Tok.getLocation();
1054 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
1055 }
1056 // If the ` is further down within the token (e.g. in a comment).
1057 EndOriginalColumn += CommentBacktickPos;
1058
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001059 if (IsMultiline) {
1060 // ColumnWidth is from backtick to last token in line.
1061 // LastLineColumnWidth is 0 to backtick.
1062 // x = `some content
1063 // until here`;
1064 Tokens.back()->ColumnWidth =
1065 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001066 // +1 for the ` itself.
1067 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001068 Tokens.back()->IsMultiline = true;
1069 } else {
1070 // Token simply spans from start to end, +1 for the ` itself.
1071 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001072 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001073 }
1074 return true;
1075 }
1076 return false;
1077 }
1078
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001079 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001080 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001081 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001082 FormatToken *Last = Tokens.back();
1083 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001084 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001085
1086 FormatToken *String = Tokens[Tokens.size() - 2];
1087 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001088 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001089
1090 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001091 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001092
1093 FormatToken *Macro = Tokens[Tokens.size() - 4];
1094 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001095 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001096
1097 const char *Start = Macro->TokenText.data();
1098 const char *End = Last->TokenText.data() + Last->TokenText.size();
1099 String->TokenText = StringRef(Start, End - Start);
1100 String->IsFirst = Macro->IsFirst;
1101 String->LastNewlineOffset = Macro->LastNewlineOffset;
1102 String->WhitespaceRange = Macro->WhitespaceRange;
1103 String->OriginalColumn = Macro->OriginalColumn;
1104 String->ColumnWidth = encoding::columnWidthWithTabs(
1105 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001106 String->NewlinesBefore = Macro->NewlinesBefore;
1107 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001108
1109 Tokens.pop_back();
1110 Tokens.pop_back();
1111 Tokens.pop_back();
1112 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001113 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001114 }
1115
Manuel Klimek68b03042014-04-14 09:14:11 +00001116 bool tryMergeConflictMarkers() {
1117 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1118 return false;
1119
1120 // Conflict lines look like:
1121 // <marker> <text from the vcs>
1122 // For example:
1123 // >>>>>>> /file/in/file/system at revision 1234
1124 //
1125 // We merge all tokens in a line that starts with a conflict marker
1126 // into a single token with a special token type that the unwrapped line
1127 // parser will use to correctly rebuild the underlying code.
1128
1129 FileID ID;
1130 // Get the position of the first token in the line.
1131 unsigned FirstInLineOffset;
1132 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1133 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1134 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1135 // Calculate the offset of the start of the current line.
1136 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1137 if (LineOffset == StringRef::npos) {
1138 LineOffset = 0;
1139 } else {
1140 ++LineOffset;
1141 }
1142
1143 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1144 StringRef LineStart;
1145 if (FirstSpace == StringRef::npos) {
1146 LineStart = Buffer.substr(LineOffset);
1147 } else {
1148 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1149 }
1150
1151 TokenType Type = TT_Unknown;
1152 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1153 Type = TT_ConflictStart;
1154 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1155 LineStart == "====") {
1156 Type = TT_ConflictAlternative;
1157 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1158 Type = TT_ConflictEnd;
1159 }
1160
1161 if (Type != TT_Unknown) {
1162 FormatToken *Next = Tokens.back();
1163
1164 Tokens.resize(FirstInLineIndex + 1);
1165 // We do not need to build a complete token here, as we will skip it
1166 // during parsing anyway (as we must not touch whitespace around conflict
1167 // markers).
1168 Tokens.back()->Type = Type;
1169 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1170
1171 Tokens.push_back(Next);
1172 return true;
1173 }
1174
1175 return false;
1176 }
1177
Jacques Pienaarfc275112015-02-18 23:48:37 +00001178 FormatToken *getStashedToken() {
1179 // Create a synthesized second '>' or '<' token.
1180 Token Tok = FormatTok->Tok;
1181 StringRef TokenText = FormatTok->TokenText;
1182
1183 unsigned OriginalColumn = FormatTok->OriginalColumn;
1184 FormatTok = new (Allocator.Allocate()) FormatToken;
1185 FormatTok->Tok = Tok;
1186 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001187 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1188 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001189 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1190 FormatTok->TokenText = TokenText;
1191 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001192 FormatTok->OriginalColumn = OriginalColumn + 1;
1193
Jacques Pienaarfc275112015-02-18 23:48:37 +00001194 return FormatTok;
1195 }
1196
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001197 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001198 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001199 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001200 return getStashedToken();
1201 }
1202 if (LessStashed) {
1203 LessStashed = false;
1204 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001205 }
1206
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001207 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001208 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001209 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001210 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001211 FormatTok->IsFirst = IsFirstToken;
1212 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001213
1214 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001215 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001216 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001217 StringRef Text = FormatTok->TokenText;
1218 auto EscapesNewline = [&](int pos) {
1219 // A '\r' here is just part of '\r\n'. Skip it.
1220 if (pos >= 0 && Text[pos] == '\r')
1221 --pos;
1222 // See whether there is an odd number of '\' before this.
1223 unsigned count = 0;
1224 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001225 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001226 break;
1227 return count & 1;
1228 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001229 // FIXME: This miscounts tok:unknown tokens that are not just
1230 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001231 for (int i = 0, e = Text.size(); i != e; ++i) {
1232 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001233 case '\n':
1234 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001235 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001236 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1237 Column = 0;
1238 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001239 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001240 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1241 Column = 0;
1242 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001243 case '\f':
1244 case '\v':
1245 Column = 0;
1246 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001247 case ' ':
1248 ++Column;
1249 break;
1250 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001251 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001252 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001253 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001254 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001255 FormatTok->Type = TT_ImplicitStringLiteral;
1256 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001257 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001258 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001259 break;
1260 }
Daniel Jaspere1f72a62016-01-09 21:12:45 +00001261 if (FormatTok->Type == TT_ImplicitStringLiteral)
1262 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001263 }
1264
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001265 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001266 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001267 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001268
Daniel Jasper8369aa52013-07-16 20:28:33 +00001269 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001270 }
Manuel Klimekef920692013-01-07 07:56:50 +00001271
Manuel Klimek1abf7892013-01-04 23:34:14 +00001272 // In case the token starts with escaped newlines, we want to
1273 // take them into account as whitespace - this pattern is quite frequent
1274 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001275 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001276 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1277 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001278 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001279 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001280 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001281 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001282 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001283 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001284
1285 FormatTok->WhitespaceRange = SourceRange(
1286 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1287
Manuel Klimek31c85922013-08-29 15:21:40 +00001288 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001289
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001290 TrailingWhitespace = 0;
1291 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001292 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001293 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001294 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001295 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001296 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001297 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001298 FormatTok->Tok.setIdentifierInfo(&Info);
1299 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001300 if (Style.Language == FormatStyle::LK_Java &&
Daniel Jasper72a1b6a2015-12-22 15:47:56 +00001301 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1302 tok::kw_operator)) {
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001303 FormatTok->Tok.setKind(tok::identifier);
1304 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasper09840ef2015-11-20 15:58:50 +00001305 } else if (Style.Language == FormatStyle::LK_JavaScript &&
Daniel Jasper72a1b6a2015-12-22 15:47:56 +00001306 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1307 tok::kw_operator)) {
Daniel Jasper09840ef2015-11-20 15:58:50 +00001308 FormatTok->Tok.setKind(tok::identifier);
1309 FormatTok->Tok.setIdentifierInfo(nullptr);
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001310 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001311 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001312 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001313 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001314 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001315 } else if (FormatTok->Tok.is(tok::lessless)) {
1316 FormatTok->Tok.setKind(tok::less);
1317 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1318 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001319 }
1320
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001321 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001322
Alexander Kornienko39856b72013-09-10 09:38:25 +00001323 StringRef Text = FormatTok->TokenText;
1324 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001325 if (FirstNewlinePos == StringRef::npos) {
1326 // FIXME: ColumnWidth actually depends on the start column, we need to
1327 // take this into account when the token is moved.
1328 FormatTok->ColumnWidth =
1329 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1330 Column += FormatTok->ColumnWidth;
1331 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001332 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001333 // FIXME: ColumnWidth actually depends on the start column, we need to
1334 // take this into account when the token is moved.
1335 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1336 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1337
Alexander Kornienko39856b72013-09-10 09:38:25 +00001338 // The last line of the token always starts in column 0.
1339 // Thus, the length can be precomputed even in the presence of tabs.
1340 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1341 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1342 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001343 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001344 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001345
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001346 if (Style.Language == FormatStyle::LK_Cpp) {
1347 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1348 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1349 tok::pp_define) &&
1350 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1351 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1352 FormatTok->Type = TT_ForEachMacro;
1353 } else if (FormatTok->is(tok::identifier)) {
1354 if (MacroBlockBeginRegex.match(Text)) {
1355 FormatTok->Type = TT_MacroBlockBegin;
1356 } else if (MacroBlockEndRegex.match(Text)) {
1357 FormatTok->Type = TT_MacroBlockEnd;
1358 }
1359 }
1360 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001361
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001362 return FormatTok;
1363 }
1364
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001365 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001366 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001367 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001368 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001369 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001370 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001371 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001372 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001373 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001374 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001375 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001376 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001377 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001378 // Index (in 'Tokens') of the last token that starts a new line.
1379 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001380 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001381 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001382
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001383 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001384
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001385 llvm::Regex MacroBlockBeginRegex;
1386 llvm::Regex MacroBlockEndRegex;
1387
Daniel Jasper8369aa52013-07-16 20:28:33 +00001388 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001389 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001390 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1391 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001392 // For formatting, treat unterminated string literals like normal string
1393 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001394 if (Tok.is(tok::unknown)) {
1395 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1396 Tok.Tok.setKind(tok::string_literal);
1397 Tok.IsUnterminatedLiteral = true;
1398 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1399 Tok.TokenText == "''") {
Daniel Jasperabd1f572016-03-02 22:44:03 +00001400 Tok.Tok.setKind(tok::string_literal);
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001401 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001402 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001403
Daniel Jasperabd1f572016-03-02 22:44:03 +00001404 if (Style.Language == FormatStyle::LK_JavaScript &&
1405 Tok.is(tok::char_constant)) {
1406 Tok.Tok.setKind(tok::string_literal);
1407 }
1408
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001409 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1410 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001411 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001412 }
1413
Daniel Jasper471894432014-08-06 13:40:26 +00001414 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001415
1416 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1417 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001418 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001419 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001420 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001421
1422 void resetLexer(unsigned Offset) {
1423 StringRef Buffer = SourceMgr.getBufferData(ID);
1424 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1425 getFormattingLangOpts(Style), Buffer.begin(),
1426 Buffer.begin() + Offset, Buffer.end()));
1427 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001428 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001429 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001430};
1431
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001432static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1433 switch (Language) {
1434 case FormatStyle::LK_Cpp:
1435 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001436 case FormatStyle::LK_Java:
1437 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001438 case FormatStyle::LK_JavaScript:
1439 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001440 case FormatStyle::LK_Proto:
1441 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001442 default:
1443 return "Unknown";
1444 }
1445}
1446
Daniel Jasperf7935112012-12-03 18:12:45 +00001447class Formatter : public UnwrappedLineConsumer {
1448public:
Daniel Jasper23376252014-09-09 14:37:39 +00001449 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001450 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001451 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1452 Whitespaces(SourceMgr, Style,
1453 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001454 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001455 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001456 DEBUG(llvm::dbgs() << "File encoding: "
1457 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1458 : "unknown")
1459 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001460 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1461 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001462 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001463
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001464 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001465 tooling::Replacements Result;
Daniel Jasper97439922016-03-17 13:03:41 +00001466 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001467
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001468 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1469 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001470 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001471 assert(UnwrappedLines.rbegin()->empty());
1472 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1473 ++Run) {
1474 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1475 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1476 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1477 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1478 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001479 tooling::Replacements RunResult =
Daniel Jasper97439922016-03-17 13:03:41 +00001480 format(AnnotatedLines, Tokens, Result, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001481 DEBUG({
1482 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1483 for (tooling::Replacements::iterator I = RunResult.begin(),
1484 E = RunResult.end();
1485 I != E; ++I) {
1486 llvm::dbgs() << I->toString() << "\n";
1487 }
1488 });
1489 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1490 delete AnnotatedLines[i];
1491 }
1492 Result.insert(RunResult.begin(), RunResult.end());
1493 Whitespaces.reset();
1494 }
1495 return Result;
1496 }
1497
1498 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001499 FormatTokenLexer &Tokens,
Daniel Jasper97439922016-03-17 13:03:41 +00001500 tooling::Replacements &Result,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001501 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001502 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001503 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001504 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001505 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001506 deriveLocalStyle(AnnotatedLines);
Daniel Jasper97439922016-03-17 13:03:41 +00001507 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1508 if (Style.Language == FormatStyle::LK_JavaScript &&
1509 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
1510 requoteJSStringLiteral(AnnotatedLines, Result);
1511
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001512 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001513 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001514 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001515
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001516 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001517 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1518 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001519 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001520 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1521 IncompleteFormat)
1522 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001523 return Whitespaces.generateReplacements();
1524 }
1525
1526private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001527 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001528 // Returns \c true if at least one line between I and E or one of their
1529 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001530 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1531 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1532 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001533 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001534 while (I != E) {
1535 AnnotatedLine *Line = *I;
1536 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1537
1538 // If a line is part of a preprocessor directive, it needs to be formatted
1539 // if any token within the directive is affected.
1540 if (Line->InPPDirective) {
1541 FormatToken *Last = Line->Last;
1542 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1543 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1544 Last = (*PPEnd)->Last;
1545 ++PPEnd;
1546 }
1547
1548 if (affectsTokenRange(*Line->First, *Last,
1549 /*IncludeLeadingNewlines=*/false)) {
1550 SomeLineAffected = true;
1551 markAllAsAffected(I, PPEnd);
1552 }
1553 I = PPEnd;
1554 continue;
1555 }
1556
Daniel Jasper38c82402013-11-29 09:27:43 +00001557 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001558 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001559
Daniel Jasper38c82402013-11-29 09:27:43 +00001560 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001561 ++I;
1562 }
1563 return SomeLineAffected;
1564 }
Daniel Jasper97439922016-03-17 13:03:41 +00001565
1566 // If the last token is a double/single-quoted string literal, generates a
1567 // replacement with a single/double quoted string literal, re-escaping the
1568 // contents in the process.
1569 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
1570 tooling::Replacements &Result) {
1571 for (AnnotatedLine *Line : Lines) {
1572 requoteJSStringLiteral(Line->Children, Result);
1573 if (!Line->Affected)
1574 continue;
1575 for (FormatToken *FormatTok = Line->First; FormatTok;
1576 FormatTok = FormatTok->Next) {
1577 StringRef Input = FormatTok->TokenText;
1578 if (!FormatTok->isStringLiteral() ||
1579 // NB: testing for not starting with a double quote to avoid
1580 // breaking
1581 // `template strings`.
1582 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
1583 !Input.startswith("\"")) ||
1584 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
1585 !Input.startswith("\'")))
1586 continue;
1587
1588 // Change start and end quote.
1589 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
1590 SourceLocation Start = FormatTok->Tok.getLocation();
1591 auto Replace = [&](SourceLocation Start, unsigned Length,
1592 StringRef ReplacementText) {
1593 Result.insert(
1594 tooling::Replacement(SourceMgr, Start, Length, ReplacementText));
1595 };
1596 Replace(Start, 1, IsSingle ? "'" : "\"");
1597 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1598 IsSingle ? "'" : "\"");
1599
1600 // Escape internal quotes.
1601 size_t ColumnWidth = FormatTok->TokenText.size();
1602 bool Escaped = false;
1603 for (size_t i = 1; i < Input.size() - 1; i++) {
1604 switch (Input[i]) {
1605 case '\\':
1606 if (!Escaped && i + 1 < Input.size() &&
1607 ((IsSingle && Input[i + 1] == '"') ||
1608 (!IsSingle && Input[i + 1] == '\''))) {
1609 // Remove this \, it's escaping a " or ' that no longer needs
1610 // escaping
1611 ColumnWidth--;
1612 Replace(Start.getLocWithOffset(i), 1, "");
1613 continue;
1614 }
1615 Escaped = !Escaped;
1616 break;
1617 case '\"':
1618 case '\'':
1619 if (!Escaped && IsSingle == (Input[i] == '\'')) {
1620 // Escape the quote.
1621 Replace(Start.getLocWithOffset(i), 0, "\\");
1622 ColumnWidth++;
1623 }
1624 Escaped = false;
1625 break;
1626 default:
1627 Escaped = false;
1628 break;
1629 }
1630 }
1631
1632 // For formatting, count the number of non-escaped single quotes in them
1633 // and adjust ColumnWidth to take the added escapes into account.
1634 // FIXME(martinprobst): this might conflict with code breaking a long string
1635 // literal (which clang-format doesn't do, yet). For that to work, this code
1636 // would have to modify TokenText directly.
1637 FormatTok->ColumnWidth = ColumnWidth;
1638 }
1639 }
1640 }
1641
Daniel Jasper5500f612013-11-25 11:08:59 +00001642
Daniel Jasper9c199562013-11-28 15:58:55 +00001643 // Determines whether 'Line' is affected by the SourceRanges given as input.
1644 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001645 bool nonPPLineAffected(AnnotatedLine *Line,
1646 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001647 bool SomeLineAffected = false;
1648 Line->ChildrenAffected =
1649 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1650 if (Line->ChildrenAffected)
1651 SomeLineAffected = true;
1652
1653 // Stores whether one of the line's tokens is directly affected.
1654 bool SomeTokenAffected = false;
1655 // Stores whether we need to look at the leading newlines of the next token
1656 // in order to determine whether it was affected.
1657 bool IncludeLeadingNewlines = false;
1658
1659 // Stores whether the first child line of any of this line's tokens is
1660 // affected.
1661 bool SomeFirstChildAffected = false;
1662
1663 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1664 // Determine whether 'Tok' was affected.
1665 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1666 SomeTokenAffected = true;
1667
1668 // Determine whether the first child of 'Tok' was affected.
1669 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1670 SomeFirstChildAffected = true;
1671
1672 IncludeLeadingNewlines = Tok->Children.empty();
1673 }
1674
1675 // Was this line moved, i.e. has it previously been on the same line as an
1676 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001677 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1678 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001679
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001680 bool IsContinuedComment =
1681 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1682 Line->First->NewlinesBefore < 2 && PreviousLine &&
1683 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001684
1685 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1686 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001687 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001688 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001689 }
1690 return SomeLineAffected;
1691 }
1692
Daniel Jasper5500f612013-11-25 11:08:59 +00001693 // Marks all lines between I and E as well as all their children as affected.
1694 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1695 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1696 while (I != E) {
1697 (*I)->Affected = true;
1698 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1699 ++I;
1700 }
1701 }
1702
1703 // Returns true if the range from 'First' to 'Last' intersects with one of the
1704 // input ranges.
1705 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1706 bool IncludeLeadingNewlines) {
1707 SourceLocation Start = First.WhitespaceRange.getBegin();
1708 if (!IncludeLeadingNewlines)
1709 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001710 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001711 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001712 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1713 return affectsCharSourceRange(Range);
1714 }
1715
1716 // Returns true if one of the input ranges intersect the leading empty lines
1717 // before 'Tok'.
1718 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1719 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1720 Tok.WhitespaceRange.getBegin(),
1721 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1722 return affectsCharSourceRange(EmptyLineRange);
1723 }
1724
1725 // Returns true if 'Range' intersects with one of the input ranges.
1726 bool affectsCharSourceRange(const CharSourceRange &Range) {
1727 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1728 E = Ranges.end();
1729 I != E; ++I) {
1730 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1731 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1732 return true;
1733 }
1734 return false;
1735 }
1736
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001737 static bool inputUsesCRLF(StringRef Text) {
1738 return Text.count('\r') * 2 > Text.count('\n');
1739 }
1740
Daniel Jasper352f0df2015-07-18 16:35:30 +00001741 bool
1742 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1743 for (const AnnotatedLine* Line : Lines) {
1744 if (hasCpp03IncompatibleFormat(Line->Children))
1745 return true;
1746 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1747 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1748 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1749 return true;
1750 if (Tok->is(TT_TemplateCloser) &&
1751 Tok->Previous->is(TT_TemplateCloser))
1752 return true;
1753 }
1754 }
1755 }
1756 return false;
1757 }
1758
1759 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1760 int AlignmentDiff = 0;
1761 for (const AnnotatedLine* Line : Lines) {
1762 AlignmentDiff += countVariableAlignments(Line->Children);
1763 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1764 if (!Tok->is(TT_PointerOrReference))
1765 continue;
1766 bool SpaceBefore =
1767 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1768 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1769 Tok->Next->WhitespaceRange.getEnd();
1770 if (SpaceBefore && !SpaceAfter)
1771 ++AlignmentDiff;
1772 if (!SpaceBefore && SpaceAfter)
1773 --AlignmentDiff;
1774 }
1775 }
1776 return AlignmentDiff;
1777 }
1778
Manuel Klimek71814b42013-10-11 21:25:45 +00001779 void
1780 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001781 bool HasBinPackedFunction = false;
1782 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001783 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001784 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001785 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001786 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001787 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001788 if (Tok->PackingKind == PPK_BinPacked)
1789 HasBinPackedFunction = true;
1790 if (Tok->PackingKind == PPK_OnePerLine)
1791 HasOnePerLineFunction = true;
1792
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001793 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001794 }
1795 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001796 if (Style.DerivePointerAlignment)
1797 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1798 ? FormatStyle::PAS_Left
1799 : FormatStyle::PAS_Right;
1800 if (Style.Standard == FormatStyle::LS_Auto)
1801 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1802 ? FormatStyle::LS_Cpp11
1803 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001804 BinPackInconclusiveFunctions =
1805 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001806 }
1807
Craig Topperfb6b25b2014-03-15 04:29:04 +00001808 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001809 assert(!UnwrappedLines.empty());
1810 UnwrappedLines.back().push_back(TheLine);
1811 }
1812
Craig Topperfb6b25b2014-03-15 04:29:04 +00001813 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001814 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001815 }
1816
1817 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001818 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001819 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001820 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001821 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001822 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001823
1824 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001825 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001826};
1827
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001828struct IncludeDirective {
1829 StringRef Filename;
1830 StringRef Text;
1831 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001832 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001833};
1834
Craig Topperaf35e852013-06-30 22:29:28 +00001835} // end anonymous namespace
1836
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001837// Determines whether 'Ranges' intersects with ('Start', 'End').
1838static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1839 unsigned End) {
1840 for (auto Range : Ranges) {
1841 if (Range.getOffset() < End &&
1842 Range.getOffset() + Range.getLength() > Start)
1843 return true;
1844 }
1845 return false;
1846}
1847
1848// Sorts a block of includes given by 'Includes' alphabetically adding the
1849// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1850// order.
1851static void sortIncludes(const FormatStyle &Style,
1852 const SmallVectorImpl<IncludeDirective> &Includes,
1853 ArrayRef<tooling::Range> Ranges, StringRef FileName,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001854 tooling::Replacements &Replaces, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001855 if (!affectsRange(Ranges, Includes.front().Offset,
1856 Includes.back().Offset + Includes.back().Text.size()))
1857 return;
1858 SmallVector<unsigned, 16> Indices;
1859 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1860 Indices.push_back(i);
Daniel Jasper94a96fc2016-03-03 17:34:14 +00001861 std::stable_sort(
1862 Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1863 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1864 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1865 });
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001866
1867 // If the #includes are out of order, we generate a single replacement fixing
1868 // the entire block. Otherwise, no replacement is generated.
1869 bool OutOfOrder = false;
1870 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1871 if (Indices[i] != i) {
1872 OutOfOrder = true;
1873 break;
1874 }
1875 }
1876 if (!OutOfOrder)
1877 return;
1878
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001879 std::string result;
1880 bool CursorMoved = false;
1881 for (unsigned Index : Indices) {
1882 if (!result.empty())
1883 result += "\n";
1884 result += Includes[Index].Text;
1885
1886 if (Cursor && !CursorMoved) {
1887 unsigned Start = Includes[Index].Offset;
1888 unsigned End = Start + Includes[Index].Text.size();
1889 if (*Cursor >= Start && *Cursor < End) {
1890 *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
1891 CursorMoved = true;
1892 }
1893 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001894 }
1895
1896 // Sorting #includes shouldn't change their total number of characters.
1897 // This would otherwise mess up 'Ranges'.
1898 assert(result.size() ==
1899 Includes.back().Offset + Includes.back().Text.size() -
1900 Includes.front().Offset);
1901
1902 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1903 result.size(), result));
1904}
1905
1906tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1907 ArrayRef<tooling::Range> Ranges,
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001908 StringRef FileName, unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001909 tooling::Replacements Replaces;
Daniel Jasperda446772015-11-16 12:38:56 +00001910 if (!Style.SortIncludes)
1911 return Replaces;
1912
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001913 unsigned Prev = 0;
1914 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001915 llvm::Regex IncludeRegex(
Nico Weberff063702015-10-21 17:13:45 +00001916 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001917 SmallVector<StringRef, 4> Matches;
1918 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001919
1920 // In compiled files, consider the first #include to be the main #include of
1921 // the file if it is not a system #include. This ensures that the header
1922 // doesn't have hidden dependencies
1923 // (http://llvm.org/docs/CodingStandards.html#include-style).
1924 //
1925 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1926 // cases where the first #include is unlikely to be the main header.
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001927 bool IsSource = FileName.endswith(".c") || FileName.endswith(".cc") ||
1928 FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1929 FileName.endswith(".cxx") || FileName.endswith(".m") ||
1930 FileName.endswith(".mm");
1931 StringRef FileStem = llvm::sys::path::stem(FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001932 bool FirstIncludeBlock = true;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001933 bool MainIncludeFound = false;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001934
1935 // Create pre-compiled regular expressions for the #include categories.
1936 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001937 for (const auto &Category : Style.IncludeCategories)
1938 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001939
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001940 bool FormattingOff = false;
1941
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001942 for (;;) {
1943 auto Pos = Code.find('\n', SearchFrom);
1944 StringRef Line =
1945 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001946
1947 StringRef Trimmed = Line.trim();
1948 if (Trimmed == "// clang-format off")
1949 FormattingOff = true;
1950 else if (Trimmed == "// clang-format on")
1951 FormattingOff = false;
1952
1953 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001954 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001955 StringRef IncludeName = Matches[2];
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001956 int Category = INT_MAX;
1957 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1958 if (CategoryRegexs[i].match(IncludeName)) {
1959 Category = Style.IncludeCategories[i].Priority;
1960 break;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001961 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001962 }
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001963 if (IsSource && !MainIncludeFound && Category > 0 &&
1964 FirstIncludeBlock && IncludeName.startswith("\"")) {
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001965 StringRef HeaderStem =
1966 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001967 if (FileStem.startswith(HeaderStem)) {
Daniel Jasper9c8ff352016-03-21 14:11:27 +00001968 llvm::Regex MainIncludeRegex(
1969 (HeaderStem + Style.IncludeIsMainRegex).str());
1970 if (MainIncludeRegex.match(FileStem)) {
1971 Category = 0;
1972 MainIncludeFound = true;
1973 }
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001974 }
Daniel Jasper0bfdeb42015-12-21 12:14:17 +00001975 }
Nico Weberff063702015-10-21 17:13:45 +00001976 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001977 } else if (!IncludesInBlock.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001978 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1979 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001980 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001981 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001982 }
1983 Prev = Pos + 1;
1984 }
1985 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1986 break;
1987 SearchFrom = Pos + 1;
1988 }
1989 if (!IncludesInBlock.empty())
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001990 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001991 return Replaces;
1992}
1993
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001994tooling::Replacements formatReplacements(StringRef Code,
1995 const tooling::Replacements &Replaces,
1996 const FormatStyle &Style) {
1997 if (Replaces.empty())
1998 return tooling::Replacements();
1999
2000 std::string NewCode = applyAllReplacements(Code, Replaces);
2001 std::vector<tooling::Range> ChangedRanges =
Eric Liu4c1ef97a2016-03-29 16:31:53 +00002002 tooling::calculateChangedRanges(Replaces);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002003 StringRef FileName = Replaces.begin()->getFilePath();
2004 tooling::Replacements FormatReplaces =
2005 reformat(Style, NewCode, ChangedRanges, FileName);
2006
2007 tooling::Replacements MergedReplacements =
2008 mergeReplacements(Replaces, FormatReplaces);
Eric Liu8c6f72f2016-03-24 10:21:00 +00002009
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002010 return MergedReplacements;
2011}
2012
Daniel Jasper23376252014-09-09 14:37:39 +00002013tooling::Replacements reformat(const FormatStyle &Style,
2014 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00002015 ArrayRef<CharSourceRange> Ranges,
2016 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002017 FormatStyle Expanded = expandPresets(Style);
2018 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00002019 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002020 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00002021 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00002022}
2023
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002024tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002025 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00002026 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00002027 if (Style.DisableFormat)
2028 return tooling::Replacements();
2029
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00002030 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
2031 new vfs::InMemoryFileSystem);
2032 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002033 DiagnosticsEngine Diagnostics(
2034 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2035 new DiagnosticOptions);
2036 SourceManager SourceMgr(Diagnostics, Files);
Daniel Jasper88c16342016-01-09 15:56:57 +00002037 InMemoryFileSystem->addFile(
2038 FileName, 0, llvm::MemoryBuffer::getMemBuffer(
2039 Code, FileName, /*RequiresNullTerminator=*/false));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00002040 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
2041 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002042 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2043 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002044 for (const tooling::Range &Range : Ranges) {
2045 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2046 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002047 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2048 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00002049 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002050}
2051
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002052LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002053 LangOptions LangOpts;
2054 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002055 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2056 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002057 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00002058 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00002059 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002060 LangOpts.Bool = 1;
2061 LangOpts.ObjC1 = 1;
2062 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00002063 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002064 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002065 return LangOpts;
2066}
2067
Edwin Vaned544aa72013-09-30 13:31:48 +00002068const char *StyleOptionHelpDescription =
2069 "Coding style, currently supports:\n"
2070 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2071 "Use -style=file to load style configuration from\n"
2072 ".clang-format file located in one of the parent\n"
2073 "directories of the source file (or current\n"
2074 "directory for stdin).\n"
2075 "Use -style=\"{key: value, ...}\" to set specific\n"
2076 "parameters, e.g.:\n"
2077 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2078
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002079static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasper498f5582015-12-25 08:53:31 +00002080 if (FileName.endswith(".java"))
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002081 return FormatStyle::LK_Java;
Daniel Jasper498f5582015-12-25 08:53:31 +00002082 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
2083 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
2084 if (FileName.endswith_lower(".proto") ||
2085 FileName.endswith_lower(".protodevel"))
Daniel Jasper7052ce62014-01-19 09:04:08 +00002086 return FormatStyle::LK_Proto;
Daniel Jasper498f5582015-12-25 08:53:31 +00002087 if (FileName.endswith_lower(".td"))
2088 return FormatStyle::LK_TableGen;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002089 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002090}
2091
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002092FormatStyle getStyle(StringRef StyleName, StringRef FileName,
Eric Liu547d8792016-03-24 13:22:42 +00002093 StringRef FallbackStyle, vfs::FileSystem *FS) {
2094 if (!FS) {
2095 FS = vfs::getRealFileSystem().get();
2096 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002097 FormatStyle Style = getLLVMStyle();
2098 Style.Language = getLanguageByFileName(FileName);
2099 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002100 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2101 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002102 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002103 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002104
2105 if (StyleName.startswith("{")) {
2106 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002107 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002108 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2109 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002110 }
2111 return Style;
2112 }
2113
2114 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002115 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002116 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2117 << " style\n";
2118 return Style;
2119 }
2120
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002121 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002122 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002123 SmallString<128> Path(FileName);
2124 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002125 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002126 Directory = llvm::sys::path::parent_path(Directory)) {
Eric Liu547d8792016-03-24 13:22:42 +00002127
2128 auto Status = FS->status(Directory);
2129 if (!Status ||
2130 Status->getType() != llvm::sys::fs::file_type::directory_file) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002131 continue;
Eric Liu547d8792016-03-24 13:22:42 +00002132 }
2133
Edwin Vaned544aa72013-09-30 13:31:48 +00002134 SmallString<128> ConfigFile(Directory);
2135
2136 llvm::sys::path::append(ConfigFile, ".clang-format");
2137 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liud4758322016-03-24 13:22:37 +00002138
Eric Liu547d8792016-03-24 13:22:42 +00002139 Status = FS->status(ConfigFile.str());
2140 bool IsFile =
2141 Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
Edwin Vaned544aa72013-09-30 13:31:48 +00002142 if (!IsFile) {
2143 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2144 ConfigFile = Directory;
2145 llvm::sys::path::append(ConfigFile, "_clang-format");
2146 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liu547d8792016-03-24 13:22:42 +00002147 Status = FS->status(ConfigFile.str());
2148 IsFile = Status &&
2149 (Status->getType() == llvm::sys::fs::file_type::regular_file);
Edwin Vaned544aa72013-09-30 13:31:48 +00002150 }
2151
2152 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002153 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
Eric Liu547d8792016-03-24 13:22:42 +00002154 FS->getBufferForFile(ConfigFile.str());
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002155 if (std::error_code EC = Text.getError()) {
2156 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002157 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002158 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002159 if (std::error_code ec =
2160 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002161 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002162 if (!UnsuitableConfigFiles.empty())
2163 UnsuitableConfigFiles.append(", ");
2164 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002165 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002166 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002167 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2168 << "\n";
2169 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002170 }
2171 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2172 return Style;
2173 }
2174 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002175 if (!UnsuitableConfigFiles.empty()) {
2176 llvm::errs() << "Configuration file(s) do(es) not support "
2177 << getLanguageName(Style.Language) << ": "
2178 << UnsuitableConfigFiles << "\n";
2179 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002180 return Style;
2181}
2182
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002183} // namespace format
2184} // namespace clang