blob: 4b998c764befd66313cc22d89e248c005f30f305 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasper85c472d2015-09-29 07:53:08 +000016#include "clang/Format/Format.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000017#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000019#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000030#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Chandler Carruth10346662014-04-22 03:17:02 +000035#define DEBUG_TYPE "format-formatter"
36
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000037using clang::format::FormatStyle;
38
Daniel Jaspere1e43192014-04-01 12:55:11 +000039LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +000040LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
Daniel Jaspere1e43192014-04-01 12:55:11 +000041
Alexander Kornienkod6538332013-05-07 15:32:14 +000042namespace llvm {
43namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000044template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
45 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
46 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000047 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000048 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000049 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000050 }
51};
52
53template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
54 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
55 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
56 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
57 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
58 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
59 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
60 }
61};
62
63template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
64 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
65 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
66 IO.enumCase(Value, "false", FormatStyle::UT_Never);
67 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
68 IO.enumCase(Value, "true", FormatStyle::UT_Always);
69 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
70 }
71};
72
Daniel Jasperd74cf402014-04-08 12:46:38 +000073template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
74 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
75 IO.enumCase(Value, "None", FormatStyle::SFS_None);
76 IO.enumCase(Value, "false", FormatStyle::SFS_None);
77 IO.enumCase(Value, "All", FormatStyle::SFS_All);
78 IO.enumCase(Value, "true", FormatStyle::SFS_All);
79 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000080 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000081 }
82};
83
Daniel Jasperac043c92014-09-15 11:11:00 +000084template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
85 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
86 IO.enumCase(Value, "All", FormatStyle::BOS_All);
87 IO.enumCase(Value, "true", FormatStyle::BOS_All);
88 IO.enumCase(Value, "None", FormatStyle::BOS_None);
89 IO.enumCase(Value, "false", FormatStyle::BOS_None);
90 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
91 }
92};
93
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000094template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
95 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
96 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
97 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000098 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
100 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000101 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000102 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000103 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 }
105};
106
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000107template <>
108struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
109 static void
110 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000111 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
112 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
113 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
114
115 // For backward compatibility.
116 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
117 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
118 }
119};
120
Alexander Kornienkod6538332013-05-07 15:32:14 +0000121template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000122struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000123 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000124 FormatStyle::NamespaceIndentationKind &Value) {
125 IO.enumCase(Value, "None", FormatStyle::NI_None);
126 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
127 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000128 }
129};
130
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000131template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
132 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
133 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
134 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
135 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
136
137 // For backward compatibility.
138 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
139 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
140 }
141};
142
Jacques Pienaarfc275112015-02-18 23:48:37 +0000143template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
144 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000145 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
146 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
147 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
148
Alp Toker958027b2014-07-14 19:42:55 +0000149 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000150 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
151 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
152 }
153};
154
155template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000156struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000157 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000158 FormatStyle::SpaceBeforeParensOptions &Value) {
159 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000160 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000161 FormatStyle::SBPO_ControlStatements);
162 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000163
164 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000165 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
166 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000167 }
168};
169
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000170template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000171 static void mapping(IO &IO, FormatStyle &Style) {
172 // When reading, read the language first, we need it for getPredefinedStyle.
173 IO.mapOptional("Language", Style.Language);
174
Alexander Kornienko49149672013-05-10 11:56:10 +0000175 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000176 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
177 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000178 ArrayRef<StringRef> Styles(StylesArray);
179 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
180 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000181 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000182 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000183 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000184 IO.mapOptional("# BasedOnStyle", StyleName);
185 break;
186 }
187 }
188 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000189 StringRef BasedOnStyle;
190 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000191 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000192 FormatStyle::LanguageKind OldLanguage = Style.Language;
193 FormatStyle::LanguageKind Language =
194 ((FormatStyle *)IO.getContext())->Language;
195 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000196 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
197 return;
198 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000199 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000200 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 }
202
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000203 // For backward compatibility.
204 if (!IO.outputting()) {
205 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
206 IO.mapOptional("IndentFunctionDeclarationAfterType",
207 Style.IndentWrappedFunctionNames);
208 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
209 IO.mapOptional("SpaceAfterControlStatementKeyword",
210 Style.SpaceBeforeParens);
211 }
212
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000214 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000215 IO.mapOptional("AlignConsecutiveAssignments",
216 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000217 IO.mapOptional("AlignConsecutiveDeclarations",
218 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000219 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000220 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000221 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000222 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
223 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000224 IO.mapOptional("AllowShortBlocksOnASingleLine",
225 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000226 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
227 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000228 IO.mapOptional("AllowShortFunctionsOnASingleLine",
229 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000230 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
231 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000232 IO.mapOptional("AllowShortLoopsOnASingleLine",
233 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000234 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
235 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000236 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
237 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000238 IO.mapOptional("AlwaysBreakTemplateDeclarations",
239 Style.AlwaysBreakTemplateDeclarations);
240 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
241 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000242 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000243 IO.mapOptional("BreakBeforeBinaryOperators",
244 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000245 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000246 IO.mapOptional("BreakBeforeTernaryOperators",
247 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000248 IO.mapOptional("BreakConstructorInitializersBeforeComma",
249 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000250 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000251 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000252 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
253 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000254 IO.mapOptional("ConstructorInitializerIndentWidth",
255 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000256 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
257 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000258 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000259 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000260 IO.mapOptional("ExperimentalAutoDetectBinPacking",
261 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000262 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000263 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000264 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000265 IO.mapOptional("IndentWidth", Style.IndentWidth);
266 IO.mapOptional("IndentWrappedFunctionNames",
267 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000268 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
269 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000270 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
271 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000272 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000273 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000274 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000275 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000276 IO.mapOptional("ObjCSpaceBeforeProtocolList",
277 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000278 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
279 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000280 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000281 IO.mapOptional("PenaltyBreakFirstLessLess",
282 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000283 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000284 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
285 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
286 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000287 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000288 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000289 IO.mapOptional("SpaceBeforeAssignmentOperators",
290 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000291 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
292 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
293 IO.mapOptional("SpacesBeforeTrailingComments",
294 Style.SpacesBeforeTrailingComments);
295 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
296 IO.mapOptional("SpacesInContainerLiterals",
297 Style.SpacesInContainerLiterals);
298 IO.mapOptional("SpacesInCStyleCastParentheses",
299 Style.SpacesInCStyleCastParentheses);
300 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
301 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
302 IO.mapOptional("Standard", Style.Standard);
303 IO.mapOptional("TabWidth", Style.TabWidth);
304 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000305 }
306};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000307
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000308template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
309 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
310 IO.mapOptional("AfterClass", Wrapping.AfterClass);
311 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
312 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
313 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
314 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
315 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
316 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
317 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
318 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
319 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
320 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
321 }
322};
323
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000324template <> struct MappingTraits<FormatStyle::IncludeCategory> {
325 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
326 IO.mapOptional("Regex", Category.Regex);
327 IO.mapOptional("Priority", Category.Priority);
328 }
329};
330
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000331// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000332// IO.getContext() should contain a pointer to the FormatStyle structure, that
333// will be used to get default values for missing keys.
334// If the first element has no Language specified, it will be treated as the
335// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000336template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000337 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
338 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000339 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000340 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000341 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000342 if (Index >= Seq.size()) {
343 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000344 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000345 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000346 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000347 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000348 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000349 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000350 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000351 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000352 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000353 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000354 }
355};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000356} // namespace yaml
357} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000358
Daniel Jasperf7935112012-12-03 18:12:45 +0000359namespace clang {
360namespace format {
361
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000362const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000363 static ParseErrorCategory C;
364 return C;
365}
366std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000367 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000368}
369
370const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
371 return "clang-format.parse_error";
372}
373
374std::string ParseErrorCategory::message(int EV) const {
375 switch (static_cast<ParseError>(EV)) {
376 case ParseError::Success:
377 return "Success";
378 case ParseError::Error:
379 return "Invalid argument";
380 case ParseError::Unsuitable:
381 return "Unsuitable";
382 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000383 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000384}
385
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000386static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000387 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
388 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000389 FormatStyle Expanded = Style;
390 Expanded.BraceWrapping = {false, false, false, false, false, false,
391 false, false, false, false, false};
392 switch (Style.BreakBeforeBraces) {
393 case FormatStyle::BS_Linux:
394 Expanded.BraceWrapping.AfterClass = true;
395 Expanded.BraceWrapping.AfterFunction = true;
396 Expanded.BraceWrapping.AfterNamespace = true;
397 Expanded.BraceWrapping.BeforeElse = true;
398 break;
399 case FormatStyle::BS_Mozilla:
400 Expanded.BraceWrapping.AfterClass = true;
401 Expanded.BraceWrapping.AfterEnum = true;
402 Expanded.BraceWrapping.AfterFunction = true;
403 Expanded.BraceWrapping.AfterStruct = true;
404 Expanded.BraceWrapping.AfterUnion = true;
405 break;
406 case FormatStyle::BS_Stroustrup:
407 Expanded.BraceWrapping.AfterFunction = true;
408 Expanded.BraceWrapping.BeforeCatch = true;
409 Expanded.BraceWrapping.BeforeElse = true;
410 break;
411 case FormatStyle::BS_Allman:
412 Expanded.BraceWrapping.AfterClass = true;
413 Expanded.BraceWrapping.AfterControlStatement = true;
414 Expanded.BraceWrapping.AfterEnum = true;
415 Expanded.BraceWrapping.AfterFunction = true;
416 Expanded.BraceWrapping.AfterNamespace = true;
417 Expanded.BraceWrapping.AfterObjCDeclaration = true;
418 Expanded.BraceWrapping.AfterStruct = true;
419 Expanded.BraceWrapping.BeforeCatch = true;
420 Expanded.BraceWrapping.BeforeElse = true;
421 break;
422 case FormatStyle::BS_GNU:
423 Expanded.BraceWrapping = {true, true, true, true, true, true,
424 true, true, true, true, true};
425 break;
426 case FormatStyle::BS_WebKit:
427 Expanded.BraceWrapping.AfterFunction = true;
428 break;
429 default:
430 break;
431 }
432 return Expanded;
433}
434
Daniel Jasperf7935112012-12-03 18:12:45 +0000435FormatStyle getLLVMStyle() {
436 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000437 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000438 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000439 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000440 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000441 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000442 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000443 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000444 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000445 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000446 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000447 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000448 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000449 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000450 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000451 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000452 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000453 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000454 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000455 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000456 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000457 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000458 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000459 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
460 false, false, false, false, false};
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000461 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Nico Weber2cd92f12015-10-15 16:03:01 +0000462 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000463 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000464 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000465 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000466 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000467 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000468 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000469 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000470 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000471 LLVMStyle.ForEachMacros.push_back("foreach");
472 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
473 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000474 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
475 {"^(<|\"(gtest|isl|json)/)", 3},
476 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000477 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000478 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000479 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000480 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000481 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000482 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000483 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000484 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000485 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000486 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000487 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000488 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000489 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000490 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000491 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000492 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000493 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000494 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000495 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000496 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000497 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000498 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000499 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000500
Daniel Jasper19a541e2013-12-19 16:45:34 +0000501 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000502 LLVMStyle.PenaltyBreakFirstLessLess = 120;
503 LLVMStyle.PenaltyBreakString = 1000;
504 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000505 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000506 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000507
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000508 LLVMStyle.DisableFormat = false;
509
Daniel Jasperf7935112012-12-03 18:12:45 +0000510 return LLVMStyle;
511}
512
Nico Weber514ecc82014-02-02 20:50:45 +0000513FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000514 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000515 GoogleStyle.Language = Language;
516
Daniel Jasperf7935112012-12-03 18:12:45 +0000517 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000518 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000519 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000520 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000521 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000522 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000523 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000524 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000525 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000526 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000527 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000528 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000529 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000530 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000531 GoogleStyle.SpacesBeforeTrailingComments = 2;
532 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000533
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000534 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000535 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000536
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000537 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000538 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000539 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000540 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000541 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000542 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000543 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000544 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
545 GoogleStyle.ColumnLimit = 100;
546 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000547 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000548 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000549 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
550 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
551 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000552 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000553 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000554 GoogleStyle.SpacesInContainerLiterals = false;
555 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000556 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000557 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000558 }
559
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 return GoogleStyle;
561}
562
Nico Weber514ecc82014-02-02 20:50:45 +0000563FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
564 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000565 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000566 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000567 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000568 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000569 ChromiumStyle.IndentWidth = 4;
Nico Weber450425c2014-11-26 16:43:18 +0000570 } else {
571 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
572 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
573 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
574 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
575 ChromiumStyle.BinPackParameters = false;
576 ChromiumStyle.DerivePointerAlignment = false;
577 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000578 return ChromiumStyle;
579}
580
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000581FormatStyle getMozillaStyle() {
582 FormatStyle MozillaStyle = getLLVMStyle();
583 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000584 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000585 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
586 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000587 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000588 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000589 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
590 MozillaStyle.ConstructorInitializerIndentWidth = 2;
591 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000592 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000593 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000594 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000595 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
596 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000597 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000598 return MozillaStyle;
599}
600
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000601FormatStyle getWebKitStyle() {
602 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000603 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000604 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000605 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000606 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000607 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000608 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000609 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000610 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000611 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000612 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000613 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000614 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000615 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000616 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000617 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000618 return Style;
619}
620
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000621FormatStyle getGNUStyle() {
622 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000623 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000624 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000625 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000626 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000627 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000628 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000629 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000630 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000631 return Style;
632}
633
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000634FormatStyle getNoStyle() {
635 FormatStyle NoStyle = getLLVMStyle();
636 NoStyle.DisableFormat = true;
637 return NoStyle;
638}
639
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000640bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
641 FormatStyle *Style) {
642 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000643 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000644 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000645 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000646 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000647 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000648 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000649 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000650 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000651 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000652 } else if (Name.equals_lower("gnu")) {
653 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000654 } else if (Name.equals_lower("none")) {
655 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000656 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000657 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000658 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000659
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000660 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000661 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000662}
663
Rafael Espindolac0809172014-06-12 14:02:15 +0000664std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000665 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000666 FormatStyle::LanguageKind Language = Style->Language;
667 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000668 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000669 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000670
671 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000672 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000673 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
674 // values for the fields, keys for which are missing from the configuration.
675 // Mapping also uses the context to get the language to find the correct
676 // base style.
677 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000678 Input >> Styles;
679 if (Input.error())
680 return Input.error();
681
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000682 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000683 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000684 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000685 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000686 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000687 for (unsigned j = 0; j < i; ++j) {
688 if (Styles[i].Language == Styles[j].Language) {
689 DEBUG(llvm::dbgs()
690 << "Duplicate languages in the config file on positions " << j
691 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000692 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000693 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000694 }
695 }
696 // Look for a suitable configuration starting from the end, so we can
697 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000698 // configuration (which can only be at slot 0) after it.
699 for (int i = Styles.size() - 1; i >= 0; --i) {
700 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000701 Styles[i].Language == FormatStyle::LK_None) {
702 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000703 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000704 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000705 }
706 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000707 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000708}
709
710std::string configurationAsText(const FormatStyle &Style) {
711 std::string Text;
712 llvm::raw_string_ostream Stream(Text);
713 llvm::yaml::Output Output(Stream);
714 // We use the same mapping method for input and output, so we need a non-const
715 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000716 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000717 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000718 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000719}
720
Craig Topperaf35e852013-06-30 22:29:28 +0000721namespace {
722
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000723class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000724public:
Daniel Jasper23376252014-09-09 14:37:39 +0000725 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000726 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000727 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000728 LessStashed(false), Column(0), TrailingWhitespace(0),
729 SourceMgr(SourceMgr), ID(ID), Style(Style),
730 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000731 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
732 MacroBlockBeginRegex(Style.MacroBlockBegin),
733 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000734 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
735 getFormattingLangOpts(Style)));
736 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000737
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000738 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000739 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
740 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000741 }
742
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000743 ArrayRef<FormatToken *> lex() {
744 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000745 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000746 do {
747 Tokens.push_back(getNextToken());
Daniel Jasper265309e2015-10-18 07:02:28 +0000748 if (Style.Language == FormatStyle::LK_JavaScript)
749 tryParseJSRegexLiteral();
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000750 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000751 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000752 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000753 } while (Tokens.back()->Tok.isNot(tok::eof));
754 return Tokens;
755 }
756
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000757 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000758
759private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000760 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000761 if (tryMerge_TMacro())
762 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000763 if (tryMergeConflictMarkers())
764 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000765 if (tryMergeLessLess())
766 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000767
768 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000769 if (tryMergeTemplateString())
770 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000771
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000772 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
773 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
774 tok::equal};
775 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
776 tok::greaterequal};
777 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000778 // FIXME: Investigate what token type gives the correct operator priority.
779 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000780 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000781 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000782 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000783 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000784 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000785 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000786 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000787 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000788 }
789
Jacques Pienaarfc275112015-02-18 23:48:37 +0000790 bool tryMergeLessLess() {
791 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000792 if (Tokens.size() < 3)
793 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000794
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000795 bool FourthTokenIsLess = false;
796 if (Tokens.size() > 3)
797 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000798
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000799 auto First = Tokens.end() - 3;
800 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
801 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000802 return false;
803
804 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000805 if (First[1]->WhitespaceRange.getBegin() !=
806 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000807 return false;
808
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000809 First[0]->Tok.setKind(tok::lessless);
810 First[0]->TokenText = "<<";
811 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000812 Tokens.erase(Tokens.end() - 2);
813 return true;
814 }
815
Manuel Klimek79e06082015-05-21 12:23:34 +0000816 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000817 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000818 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000819
820 SmallVectorImpl<FormatToken *>::const_iterator First =
821 Tokens.end() - Kinds.size();
822 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000823 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000824 unsigned AddLength = 0;
825 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000826 if (!First[i]->is(Kinds[i]) ||
827 First[i]->WhitespaceRange.getBegin() !=
828 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000829 return false;
830 AddLength += First[i]->TokenText.size();
831 }
832 Tokens.resize(Tokens.size() - Kinds.size() + 1);
833 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
834 First[0]->TokenText.size() + AddLength);
835 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000836 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000837 return true;
838 }
839
Daniel Jasper265309e2015-10-18 07:02:28 +0000840 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
841 bool precedesOperand(FormatToken *Tok) {
842 // NB: This is not entirely correct, as an r_paren can introduce an operand
843 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
844 // corner case to not matter in practice, though.
845 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
846 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
847 tok::colon, tok::question, tok::tilde) ||
848 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
849 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
850 tok::kw_typeof, Keywords.kw_instanceof,
851 Keywords.kw_in) ||
852 Tok->isBinaryOperator();
853 }
854
855 bool canPrecedeRegexLiteral(FormatToken *Prev) {
856 if (!Prev)
857 return true;
858
859 // Regex literals can only follow after prefix unary operators, not after
860 // postfix unary operators. If the '++' is followed by a non-operand
861 // introducing token, the slash here is the operand and not the start of a
862 // regex.
863 if (Prev->isOneOf(tok::plusplus, tok::minusminus))
864 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
865
866 // The previous token must introduce an operand location where regex
867 // literals can occur.
868 if (!precedesOperand(Prev))
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000869 return false;
Daniel Jasper265309e2015-10-18 07:02:28 +0000870
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000871 return true;
872 }
873
Daniel Jasper265309e2015-10-18 07:02:28 +0000874 // Tries to parse a JavaScript Regex literal starting at the current token,
875 // if that begins with a slash and is in a location where JavaScript allows
876 // regex literals. Changes the current token to a regex literal and updates
877 // its text if successful.
878 void tryParseJSRegexLiteral() {
879 FormatToken *RegexToken = Tokens.back();
880 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
881 return;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000882
Daniel Jasper265309e2015-10-18 07:02:28 +0000883 FormatToken *Prev = nullptr;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000884 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
Daniel Jasper265309e2015-10-18 07:02:28 +0000885 // NB: Because previous pointers are not initialized yet, this cannot use
886 // Token.getPreviousNonComment.
887 if ((*I)->isNot(tok::comment)) {
888 Prev = *I;
889 break;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000890 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000891 }
Daniel Jasper265309e2015-10-18 07:02:28 +0000892
893 if (!canPrecedeRegexLiteral(Prev))
894 return;
895
896 // 'Manually' lex ahead in the current file buffer.
897 const char *Offset = Lex->getBufferLocation();
898 const char *RegexBegin = Offset - RegexToken->TokenText.size();
899 StringRef Buffer = Lex->getBuffer();
900 bool InCharacterClass = false;
901 bool HaveClosingSlash = false;
902 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
903 // Regular expressions are terminated with a '/', which can only be
904 // escaped using '\' or a character class between '[' and ']'.
905 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
906 switch (*Offset) {
907 case '\\':
908 // Skip the escaped character.
909 ++Offset;
910 break;
911 case '[':
912 InCharacterClass = true;
913 break;
914 case ']':
915 InCharacterClass = false;
916 break;
917 case '/':
918 if (!InCharacterClass)
919 HaveClosingSlash = true;
920 break;
921 }
922 }
923
924 RegexToken->Type = TT_RegexLiteral;
925 // Treat regex literals like other string_literals.
926 RegexToken->Tok.setKind(tok::string_literal);
927 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
928 RegexToken->ColumnWidth = RegexToken->TokenText.size();
929
930 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000931 }
932
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000933 bool tryMergeTemplateString() {
934 if (Tokens.size() < 2)
935 return false;
936
937 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000938 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000939 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
940 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000941 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
942 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000943 return false;
944 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
945 // Unknown token that's not actually a backtick, or a comment that doesn't
946 // contain a backtick.
947 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000948 return false;
949
950 unsigned TokenCount = 0;
951 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000952 unsigned EndColumnInFirstLine =
953 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000954 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
955 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000956 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000957 IsMultiline = true;
958
959 // If there was a preceding template string, this must be the start of a
960 // template string, not the end.
961 if (I[0]->is(TT_TemplateString))
962 return false;
963
964 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
965 // Keep track of the rhs offset of the last token to wrap across lines -
966 // its the rhs offset of the first line of the template string, used to
967 // determine its width.
968 if (I[0]->IsMultiline)
969 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
970 // If the token has newlines, the token before it (if it exists) is the
971 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000972 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000973 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000974 IsMultiline = true;
975 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000976 continue;
977 }
978
979 Tokens.resize(Tokens.size() - TokenCount);
980 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000981 const char *EndOffset =
982 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
983 if (CommentBacktickPos != 0) {
984 // If the backtick was not the first character (e.g. in a comment),
985 // re-lex after the backtick position.
986 SourceLocation Loc = EndBacktick->Tok.getLocation();
987 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
988 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000989 Tokens.back()->TokenText =
990 StringRef(Tokens.back()->TokenText.data(),
991 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000992
993 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
994 if (EndOriginalColumn == 0) {
995 SourceLocation Loc = EndBacktick->Tok.getLocation();
996 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
997 }
998 // If the ` is further down within the token (e.g. in a comment).
999 EndOriginalColumn += CommentBacktickPos;
1000
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001001 if (IsMultiline) {
1002 // ColumnWidth is from backtick to last token in line.
1003 // LastLineColumnWidth is 0 to backtick.
1004 // x = `some content
1005 // until here`;
1006 Tokens.back()->ColumnWidth =
1007 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001008 // +1 for the ` itself.
1009 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001010 Tokens.back()->IsMultiline = true;
1011 } else {
1012 // Token simply spans from start to end, +1 for the ` itself.
1013 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001014 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001015 }
1016 return true;
1017 }
1018 return false;
1019 }
1020
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001021 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001022 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001023 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001024 FormatToken *Last = Tokens.back();
1025 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001026 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001027
1028 FormatToken *String = Tokens[Tokens.size() - 2];
1029 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001030 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001031
1032 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001033 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001034
1035 FormatToken *Macro = Tokens[Tokens.size() - 4];
1036 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001037 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001038
1039 const char *Start = Macro->TokenText.data();
1040 const char *End = Last->TokenText.data() + Last->TokenText.size();
1041 String->TokenText = StringRef(Start, End - Start);
1042 String->IsFirst = Macro->IsFirst;
1043 String->LastNewlineOffset = Macro->LastNewlineOffset;
1044 String->WhitespaceRange = Macro->WhitespaceRange;
1045 String->OriginalColumn = Macro->OriginalColumn;
1046 String->ColumnWidth = encoding::columnWidthWithTabs(
1047 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001048 String->NewlinesBefore = Macro->NewlinesBefore;
1049 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001050
1051 Tokens.pop_back();
1052 Tokens.pop_back();
1053 Tokens.pop_back();
1054 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001055 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001056 }
1057
Manuel Klimek68b03042014-04-14 09:14:11 +00001058 bool tryMergeConflictMarkers() {
1059 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1060 return false;
1061
1062 // Conflict lines look like:
1063 // <marker> <text from the vcs>
1064 // For example:
1065 // >>>>>>> /file/in/file/system at revision 1234
1066 //
1067 // We merge all tokens in a line that starts with a conflict marker
1068 // into a single token with a special token type that the unwrapped line
1069 // parser will use to correctly rebuild the underlying code.
1070
1071 FileID ID;
1072 // Get the position of the first token in the line.
1073 unsigned FirstInLineOffset;
1074 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1075 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1076 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1077 // Calculate the offset of the start of the current line.
1078 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1079 if (LineOffset == StringRef::npos) {
1080 LineOffset = 0;
1081 } else {
1082 ++LineOffset;
1083 }
1084
1085 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1086 StringRef LineStart;
1087 if (FirstSpace == StringRef::npos) {
1088 LineStart = Buffer.substr(LineOffset);
1089 } else {
1090 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1091 }
1092
1093 TokenType Type = TT_Unknown;
1094 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1095 Type = TT_ConflictStart;
1096 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1097 LineStart == "====") {
1098 Type = TT_ConflictAlternative;
1099 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1100 Type = TT_ConflictEnd;
1101 }
1102
1103 if (Type != TT_Unknown) {
1104 FormatToken *Next = Tokens.back();
1105
1106 Tokens.resize(FirstInLineIndex + 1);
1107 // We do not need to build a complete token here, as we will skip it
1108 // during parsing anyway (as we must not touch whitespace around conflict
1109 // markers).
1110 Tokens.back()->Type = Type;
1111 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1112
1113 Tokens.push_back(Next);
1114 return true;
1115 }
1116
1117 return false;
1118 }
1119
Jacques Pienaarfc275112015-02-18 23:48:37 +00001120 FormatToken *getStashedToken() {
1121 // Create a synthesized second '>' or '<' token.
1122 Token Tok = FormatTok->Tok;
1123 StringRef TokenText = FormatTok->TokenText;
1124
1125 unsigned OriginalColumn = FormatTok->OriginalColumn;
1126 FormatTok = new (Allocator.Allocate()) FormatToken;
1127 FormatTok->Tok = Tok;
1128 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001129 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1130 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001131 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1132 FormatTok->TokenText = TokenText;
1133 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001134 FormatTok->OriginalColumn = OriginalColumn + 1;
1135
Jacques Pienaarfc275112015-02-18 23:48:37 +00001136 return FormatTok;
1137 }
1138
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001139 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001140 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001141 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001142 return getStashedToken();
1143 }
1144 if (LessStashed) {
1145 LessStashed = false;
1146 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001147 }
1148
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001149 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001150 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001151 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001152 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001153 FormatTok->IsFirst = IsFirstToken;
1154 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001155
1156 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001157 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001158 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001159 StringRef Text = FormatTok->TokenText;
1160 auto EscapesNewline = [&](int pos) {
1161 // A '\r' here is just part of '\r\n'. Skip it.
1162 if (pos >= 0 && Text[pos] == '\r')
1163 --pos;
1164 // See whether there is an odd number of '\' before this.
1165 unsigned count = 0;
1166 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001167 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001168 break;
1169 return count & 1;
1170 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001171 // FIXME: This miscounts tok:unknown tokens that are not just
1172 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001173 for (int i = 0, e = Text.size(); i != e; ++i) {
1174 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001175 case '\n':
1176 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001177 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001178 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1179 Column = 0;
1180 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001181 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001182 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1183 Column = 0;
1184 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001185 case '\f':
1186 case '\v':
1187 Column = 0;
1188 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001189 case ' ':
1190 ++Column;
1191 break;
1192 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001193 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001194 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001195 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001196 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001197 FormatTok->Type = TT_ImplicitStringLiteral;
1198 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001199 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001200 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001201 break;
1202 }
1203 }
1204
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001205 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001206 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001207 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001208
Daniel Jasper8369aa52013-07-16 20:28:33 +00001209 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001210 }
Manuel Klimekef920692013-01-07 07:56:50 +00001211
Manuel Klimek1abf7892013-01-04 23:34:14 +00001212 // In case the token starts with escaped newlines, we want to
1213 // take them into account as whitespace - this pattern is quite frequent
1214 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001215 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001216 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1217 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001218 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001219 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001220 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001221 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001222 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001223 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001224
1225 FormatTok->WhitespaceRange = SourceRange(
1226 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1227
Manuel Klimek31c85922013-08-29 15:21:40 +00001228 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001229
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001230 TrailingWhitespace = 0;
1231 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001232 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001233 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001234 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001235 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001236 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001237 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001238 FormatTok->Tok.setIdentifierInfo(&Info);
1239 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001240 if (Style.Language == FormatStyle::LK_Java &&
1241 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1242 FormatTok->Tok.setKind(tok::identifier);
1243 FormatTok->Tok.setIdentifierInfo(nullptr);
1244 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001245 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001246 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001247 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001248 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001249 } else if (FormatTok->Tok.is(tok::lessless)) {
1250 FormatTok->Tok.setKind(tok::less);
1251 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1252 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001253 }
1254
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001255 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001256
Alexander Kornienko39856b72013-09-10 09:38:25 +00001257 StringRef Text = FormatTok->TokenText;
1258 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001259 if (FirstNewlinePos == StringRef::npos) {
1260 // FIXME: ColumnWidth actually depends on the start column, we need to
1261 // take this into account when the token is moved.
1262 FormatTok->ColumnWidth =
1263 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1264 Column += FormatTok->ColumnWidth;
1265 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001266 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001267 // FIXME: ColumnWidth actually depends on the start column, we need to
1268 // take this into account when the token is moved.
1269 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1270 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1271
Alexander Kornienko39856b72013-09-10 09:38:25 +00001272 // The last line of the token always starts in column 0.
1273 // Thus, the length can be precomputed even in the presence of tabs.
1274 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1275 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1276 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001277 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001278 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001279
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001280 if (Style.Language == FormatStyle::LK_Cpp) {
1281 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1282 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1283 tok::pp_define) &&
1284 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1285 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1286 FormatTok->Type = TT_ForEachMacro;
1287 } else if (FormatTok->is(tok::identifier)) {
1288 if (MacroBlockBeginRegex.match(Text)) {
1289 FormatTok->Type = TT_MacroBlockBegin;
1290 } else if (MacroBlockEndRegex.match(Text)) {
1291 FormatTok->Type = TT_MacroBlockEnd;
1292 }
1293 }
1294 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001295
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001296 return FormatTok;
1297 }
1298
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001299 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001300 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001301 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001302 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001303 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001304 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001305 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001306 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001307 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001308 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001309 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001310 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001311 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001312 // Index (in 'Tokens') of the last token that starts a new line.
1313 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001314 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001315 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001316
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001317 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001318
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001319 llvm::Regex MacroBlockBeginRegex;
1320 llvm::Regex MacroBlockEndRegex;
1321
Daniel Jasper8369aa52013-07-16 20:28:33 +00001322 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001323 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001324 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1325 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001326 // For formatting, treat unterminated string literals like normal string
1327 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001328 if (Tok.is(tok::unknown)) {
1329 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1330 Tok.Tok.setKind(tok::string_literal);
1331 Tok.IsUnterminatedLiteral = true;
1332 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1333 Tok.TokenText == "''") {
1334 Tok.Tok.setKind(tok::char_constant);
1335 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001336 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001337
1338 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1339 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001340 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001341 }
1342
Daniel Jasper471894432014-08-06 13:40:26 +00001343 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001344
1345 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1346 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001347 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001348 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001350
1351 void resetLexer(unsigned Offset) {
1352 StringRef Buffer = SourceMgr.getBufferData(ID);
1353 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1354 getFormattingLangOpts(Style), Buffer.begin(),
1355 Buffer.begin() + Offset, Buffer.end()));
1356 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001357 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001358 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001359};
1360
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001361static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1362 switch (Language) {
1363 case FormatStyle::LK_Cpp:
1364 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001365 case FormatStyle::LK_Java:
1366 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001367 case FormatStyle::LK_JavaScript:
1368 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001369 case FormatStyle::LK_Proto:
1370 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001371 default:
1372 return "Unknown";
1373 }
1374}
1375
Daniel Jasperf7935112012-12-03 18:12:45 +00001376class Formatter : public UnwrappedLineConsumer {
1377public:
Daniel Jasper23376252014-09-09 14:37:39 +00001378 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001379 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001380 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1381 Whitespaces(SourceMgr, Style,
1382 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001383 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001384 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001385 DEBUG(llvm::dbgs() << "File encoding: "
1386 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1387 : "unknown")
1388 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001389 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1390 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001391 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001392
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001393 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001394 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001395 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001396
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001397 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1398 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001399 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001400 assert(UnwrappedLines.rbegin()->empty());
1401 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1402 ++Run) {
1403 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1404 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1405 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1406 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1407 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001408 tooling::Replacements RunResult =
1409 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001410 DEBUG({
1411 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1412 for (tooling::Replacements::iterator I = RunResult.begin(),
1413 E = RunResult.end();
1414 I != E; ++I) {
1415 llvm::dbgs() << I->toString() << "\n";
1416 }
1417 });
1418 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1419 delete AnnotatedLines[i];
1420 }
1421 Result.insert(RunResult.begin(), RunResult.end());
1422 Whitespaces.reset();
1423 }
1424 return Result;
1425 }
1426
1427 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001428 FormatTokenLexer &Tokens,
1429 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001430 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001431 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001432 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001433 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001434 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001435 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001436 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001437 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001438 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001439
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001440 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001441 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1442 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001443 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001444 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1445 IncompleteFormat)
1446 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001447 return Whitespaces.generateReplacements();
1448 }
1449
1450private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001451 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001452 // Returns \c true if at least one line between I and E or one of their
1453 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001454 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1455 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1456 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001457 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001458 while (I != E) {
1459 AnnotatedLine *Line = *I;
1460 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1461
1462 // If a line is part of a preprocessor directive, it needs to be formatted
1463 // if any token within the directive is affected.
1464 if (Line->InPPDirective) {
1465 FormatToken *Last = Line->Last;
1466 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1467 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1468 Last = (*PPEnd)->Last;
1469 ++PPEnd;
1470 }
1471
1472 if (affectsTokenRange(*Line->First, *Last,
1473 /*IncludeLeadingNewlines=*/false)) {
1474 SomeLineAffected = true;
1475 markAllAsAffected(I, PPEnd);
1476 }
1477 I = PPEnd;
1478 continue;
1479 }
1480
Daniel Jasper38c82402013-11-29 09:27:43 +00001481 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001482 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001483
Daniel Jasper38c82402013-11-29 09:27:43 +00001484 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001485 ++I;
1486 }
1487 return SomeLineAffected;
1488 }
1489
Daniel Jasper9c199562013-11-28 15:58:55 +00001490 // Determines whether 'Line' is affected by the SourceRanges given as input.
1491 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001492 bool nonPPLineAffected(AnnotatedLine *Line,
1493 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001494 bool SomeLineAffected = false;
1495 Line->ChildrenAffected =
1496 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1497 if (Line->ChildrenAffected)
1498 SomeLineAffected = true;
1499
1500 // Stores whether one of the line's tokens is directly affected.
1501 bool SomeTokenAffected = false;
1502 // Stores whether we need to look at the leading newlines of the next token
1503 // in order to determine whether it was affected.
1504 bool IncludeLeadingNewlines = false;
1505
1506 // Stores whether the first child line of any of this line's tokens is
1507 // affected.
1508 bool SomeFirstChildAffected = false;
1509
1510 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1511 // Determine whether 'Tok' was affected.
1512 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1513 SomeTokenAffected = true;
1514
1515 // Determine whether the first child of 'Tok' was affected.
1516 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1517 SomeFirstChildAffected = true;
1518
1519 IncludeLeadingNewlines = Tok->Children.empty();
1520 }
1521
1522 // Was this line moved, i.e. has it previously been on the same line as an
1523 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001524 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1525 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001526
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001527 bool IsContinuedComment =
1528 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1529 Line->First->NewlinesBefore < 2 && PreviousLine &&
1530 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001531
1532 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1533 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001534 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001535 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001536 }
1537 return SomeLineAffected;
1538 }
1539
Daniel Jasper5500f612013-11-25 11:08:59 +00001540 // Marks all lines between I and E as well as all their children as affected.
1541 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1542 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1543 while (I != E) {
1544 (*I)->Affected = true;
1545 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1546 ++I;
1547 }
1548 }
1549
1550 // Returns true if the range from 'First' to 'Last' intersects with one of the
1551 // input ranges.
1552 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1553 bool IncludeLeadingNewlines) {
1554 SourceLocation Start = First.WhitespaceRange.getBegin();
1555 if (!IncludeLeadingNewlines)
1556 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001557 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001558 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001559 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1560 return affectsCharSourceRange(Range);
1561 }
1562
1563 // Returns true if one of the input ranges intersect the leading empty lines
1564 // before 'Tok'.
1565 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1566 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1567 Tok.WhitespaceRange.getBegin(),
1568 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1569 return affectsCharSourceRange(EmptyLineRange);
1570 }
1571
1572 // Returns true if 'Range' intersects with one of the input ranges.
1573 bool affectsCharSourceRange(const CharSourceRange &Range) {
1574 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1575 E = Ranges.end();
1576 I != E; ++I) {
1577 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1578 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1579 return true;
1580 }
1581 return false;
1582 }
1583
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001584 static bool inputUsesCRLF(StringRef Text) {
1585 return Text.count('\r') * 2 > Text.count('\n');
1586 }
1587
Daniel Jasper352f0df2015-07-18 16:35:30 +00001588 bool
1589 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1590 for (const AnnotatedLine* Line : Lines) {
1591 if (hasCpp03IncompatibleFormat(Line->Children))
1592 return true;
1593 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1594 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1595 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1596 return true;
1597 if (Tok->is(TT_TemplateCloser) &&
1598 Tok->Previous->is(TT_TemplateCloser))
1599 return true;
1600 }
1601 }
1602 }
1603 return false;
1604 }
1605
1606 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1607 int AlignmentDiff = 0;
1608 for (const AnnotatedLine* Line : Lines) {
1609 AlignmentDiff += countVariableAlignments(Line->Children);
1610 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1611 if (!Tok->is(TT_PointerOrReference))
1612 continue;
1613 bool SpaceBefore =
1614 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1615 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1616 Tok->Next->WhitespaceRange.getEnd();
1617 if (SpaceBefore && !SpaceAfter)
1618 ++AlignmentDiff;
1619 if (!SpaceBefore && SpaceAfter)
1620 --AlignmentDiff;
1621 }
1622 }
1623 return AlignmentDiff;
1624 }
1625
Manuel Klimek71814b42013-10-11 21:25:45 +00001626 void
1627 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001628 bool HasBinPackedFunction = false;
1629 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001630 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001631 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001632 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001633 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001634 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001635 if (Tok->PackingKind == PPK_BinPacked)
1636 HasBinPackedFunction = true;
1637 if (Tok->PackingKind == PPK_OnePerLine)
1638 HasOnePerLineFunction = true;
1639
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001640 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001641 }
1642 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001643 if (Style.DerivePointerAlignment)
1644 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1645 ? FormatStyle::PAS_Left
1646 : FormatStyle::PAS_Right;
1647 if (Style.Standard == FormatStyle::LS_Auto)
1648 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1649 ? FormatStyle::LS_Cpp11
1650 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001651 BinPackInconclusiveFunctions =
1652 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001653 }
1654
Craig Topperfb6b25b2014-03-15 04:29:04 +00001655 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001656 assert(!UnwrappedLines.empty());
1657 UnwrappedLines.back().push_back(TheLine);
1658 }
1659
Craig Topperfb6b25b2014-03-15 04:29:04 +00001660 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001661 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001662 }
1663
1664 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001665 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001666 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001667 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001668 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001669 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001670
1671 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001672 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001673};
1674
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001675struct IncludeDirective {
1676 StringRef Filename;
1677 StringRef Text;
1678 unsigned Offset;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001679 unsigned Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001680};
1681
Craig Topperaf35e852013-06-30 22:29:28 +00001682} // end anonymous namespace
1683
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001684// Determines whether 'Ranges' intersects with ('Start', 'End').
1685static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1686 unsigned End) {
1687 for (auto Range : Ranges) {
1688 if (Range.getOffset() < End &&
1689 Range.getOffset() + Range.getLength() > Start)
1690 return true;
1691 }
1692 return false;
1693}
1694
1695// Sorts a block of includes given by 'Includes' alphabetically adding the
1696// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1697// order.
1698static void sortIncludes(const FormatStyle &Style,
1699 const SmallVectorImpl<IncludeDirective> &Includes,
1700 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1701 tooling::Replacements &Replaces) {
1702 if (!affectsRange(Ranges, Includes.front().Offset,
1703 Includes.back().Offset + Includes.back().Text.size()))
1704 return;
1705 SmallVector<unsigned, 16> Indices;
1706 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1707 Indices.push_back(i);
1708 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001709 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1710 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001711 });
1712
1713 // If the #includes are out of order, we generate a single replacement fixing
1714 // the entire block. Otherwise, no replacement is generated.
1715 bool OutOfOrder = false;
1716 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1717 if (Indices[i] != i) {
1718 OutOfOrder = true;
1719 break;
1720 }
1721 }
1722 if (!OutOfOrder)
1723 return;
1724
1725 std::string result = Includes[Indices[0]].Text;
1726 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1727 result += "\n";
1728 result += Includes[Indices[i]].Text;
1729 }
1730
1731 // Sorting #includes shouldn't change their total number of characters.
1732 // This would otherwise mess up 'Ranges'.
1733 assert(result.size() ==
1734 Includes.back().Offset + Includes.back().Text.size() -
1735 Includes.front().Offset);
1736
1737 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1738 result.size(), result));
1739}
1740
1741tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1742 ArrayRef<tooling::Range> Ranges,
1743 StringRef FileName) {
1744 tooling::Replacements Replaces;
1745 unsigned Prev = 0;
1746 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001747 llvm::Regex IncludeRegex(
Nico Weberff063702015-10-21 17:13:45 +00001748 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001749 SmallVector<StringRef, 4> Matches;
1750 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001751
1752 // In compiled files, consider the first #include to be the main #include of
1753 // the file if it is not a system #include. This ensures that the header
1754 // doesn't have hidden dependencies
1755 // (http://llvm.org/docs/CodingStandards.html#include-style).
1756 //
1757 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1758 // cases where the first #include is unlikely to be the main header.
1759 bool LookForMainHeader = FileName.endswith(".c") ||
1760 FileName.endswith(".cc") ||
1761 FileName.endswith(".cpp")||
1762 FileName.endswith(".c++")||
Nico Weberafa62fa2015-10-19 01:36:09 +00001763 FileName.endswith(".cxx") ||
1764 FileName.endswith(".m")||
1765 FileName.endswith(".mm");
Daniel Jasper85c472d2015-09-29 07:53:08 +00001766
1767 // Create pre-compiled regular expressions for the #include categories.
1768 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001769 for (const auto &Category : Style.IncludeCategories)
1770 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001771
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001772 for (;;) {
1773 auto Pos = Code.find('\n', SearchFrom);
1774 StringRef Line =
1775 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1776 if (!Line.endswith("\\")) {
1777 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001778 StringRef IncludeName = Matches[2];
Daniel Jasper85c472d2015-09-29 07:53:08 +00001779 unsigned Category;
Nico Weberff063702015-10-21 17:13:45 +00001780 if (LookForMainHeader && !IncludeName.startswith("<")) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001781 Category = 0;
1782 } else {
1783 Category = UINT_MAX;
1784 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
Nico Weberff063702015-10-21 17:13:45 +00001785 if (CategoryRegexs[i].match(IncludeName)) {
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001786 Category = Style.IncludeCategories[i].Priority;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001787 break;
1788 }
1789 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001790 }
Daniel Jasper85c472d2015-09-29 07:53:08 +00001791 LookForMainHeader = false;
Nico Weberff063702015-10-21 17:13:45 +00001792 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001793 } else if (!IncludesInBlock.empty()) {
1794 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1795 IncludesInBlock.clear();
1796 }
1797 Prev = Pos + 1;
1798 }
1799 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1800 break;
1801 SearchFrom = Pos + 1;
1802 }
1803 if (!IncludesInBlock.empty())
1804 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1805 return Replaces;
1806}
1807
Daniel Jasper23376252014-09-09 14:37:39 +00001808tooling::Replacements reformat(const FormatStyle &Style,
1809 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001810 ArrayRef<CharSourceRange> Ranges,
1811 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001812 FormatStyle Expanded = expandPresets(Style);
1813 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001814 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001815 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001816 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001817}
1818
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001819tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001820 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001821 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001822 if (Style.DisableFormat)
1823 return tooling::Replacements();
1824
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001825 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1826 new vfs::InMemoryFileSystem);
1827 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001828 DiagnosticsEngine Diagnostics(
1829 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1830 new DiagnosticOptions);
1831 SourceManager SourceMgr(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001832 InMemoryFileSystem->addFile(FileName, 0,
1833 llvm::MemoryBuffer::getMemBuffer(Code, FileName));
1834 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1835 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001836 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1837 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001838 for (const tooling::Range &Range : Ranges) {
1839 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1840 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001841 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1842 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001843 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001844}
1845
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001846LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001847 LangOptions LangOpts;
1848 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001849 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1850 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001851 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001852 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001853 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001854 LangOpts.Bool = 1;
1855 LangOpts.ObjC1 = 1;
1856 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001857 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001858 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001859 return LangOpts;
1860}
1861
Edwin Vaned544aa72013-09-30 13:31:48 +00001862const char *StyleOptionHelpDescription =
1863 "Coding style, currently supports:\n"
1864 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1865 "Use -style=file to load style configuration from\n"
1866 ".clang-format file located in one of the parent\n"
1867 "directories of the source file (or current\n"
1868 "directory for stdin).\n"
1869 "Use -style=\"{key: value, ...}\" to set specific\n"
1870 "parameters, e.g.:\n"
1871 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1872
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001873static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001874 if (FileName.endswith(".java")) {
1875 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001876 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1877 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001878 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001879 } else if (FileName.endswith_lower(".proto") ||
1880 FileName.endswith_lower(".protodevel")) {
1881 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001882 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001883 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001884}
1885
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001886FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1887 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001888 FormatStyle Style = getLLVMStyle();
1889 Style.Language = getLanguageByFileName(FileName);
1890 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001891 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1892 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001893 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001894 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001895
1896 if (StyleName.startswith("{")) {
1897 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001898 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001899 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1900 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001901 }
1902 return Style;
1903 }
1904
1905 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001906 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001907 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1908 << " style\n";
1909 return Style;
1910 }
1911
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001912 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001913 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001914 SmallString<128> Path(FileName);
1915 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001916 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001917 Directory = llvm::sys::path::parent_path(Directory)) {
1918 if (!llvm::sys::fs::is_directory(Directory))
1919 continue;
1920 SmallString<128> ConfigFile(Directory);
1921
1922 llvm::sys::path::append(ConfigFile, ".clang-format");
1923 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1924 bool IsFile = false;
1925 // Ignore errors from is_regular_file: we only need to know if we can read
1926 // the file or not.
1927 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1928
1929 if (!IsFile) {
1930 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1931 ConfigFile = Directory;
1932 llvm::sys::path::append(ConfigFile, "_clang-format");
1933 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1934 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1935 }
1936
1937 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001938 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1939 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1940 if (std::error_code EC = Text.getError()) {
1941 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001942 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001943 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001944 if (std::error_code ec =
1945 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001946 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001947 if (!UnsuitableConfigFiles.empty())
1948 UnsuitableConfigFiles.append(", ");
1949 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001950 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001951 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001952 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1953 << "\n";
1954 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001955 }
1956 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1957 return Style;
1958 }
1959 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001960 if (!UnsuitableConfigFiles.empty()) {
1961 llvm::errs() << "Configuration file(s) do(es) not support "
1962 << getLanguageName(Style.Language) << ": "
1963 << UnsuitableConfigFiles << "\n";
1964 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001965 return Style;
1966}
1967
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001968} // namespace format
1969} // namespace clang