blob: aa227a1f00a82ca14b075809e14a6f7ccd168fc5 [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)
40
Alexander Kornienkod6538332013-05-07 15:32:14 +000041namespace llvm {
42namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000043template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
44 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
45 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000046 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000048 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000049 }
50};
51
52template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
53 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
54 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
55 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
56 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
57 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
58 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
59 }
60};
61
62template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
63 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
64 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
65 IO.enumCase(Value, "false", FormatStyle::UT_Never);
66 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
67 IO.enumCase(Value, "true", FormatStyle::UT_Always);
68 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
69 }
70};
71
Daniel Jasperd74cf402014-04-08 12:46:38 +000072template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
73 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
74 IO.enumCase(Value, "None", FormatStyle::SFS_None);
75 IO.enumCase(Value, "false", FormatStyle::SFS_None);
76 IO.enumCase(Value, "All", FormatStyle::SFS_All);
77 IO.enumCase(Value, "true", FormatStyle::SFS_All);
78 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000079 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000080 }
81};
82
Daniel Jasperac043c92014-09-15 11:11:00 +000083template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
84 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
85 IO.enumCase(Value, "All", FormatStyle::BOS_All);
86 IO.enumCase(Value, "true", FormatStyle::BOS_All);
87 IO.enumCase(Value, "None", FormatStyle::BOS_None);
88 IO.enumCase(Value, "false", FormatStyle::BOS_None);
89 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
90 }
91};
92
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000093template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
94 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
95 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
96 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000097 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000098 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
99 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000100 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000101 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000102 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103 }
104};
105
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000106template <>
107struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
108 static void
109 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000110 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
111 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
112 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
113
114 // For backward compatibility.
115 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
116 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
117 }
118};
119
Alexander Kornienkod6538332013-05-07 15:32:14 +0000120template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000121struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000122 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000123 FormatStyle::NamespaceIndentationKind &Value) {
124 IO.enumCase(Value, "None", FormatStyle::NI_None);
125 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
126 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000127 }
128};
129
Jacques Pienaarfc275112015-02-18 23:48:37 +0000130template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
131 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000132 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
133 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
134 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
135
Alp Toker958027b2014-07-14 19:42:55 +0000136 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000137 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
138 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
139 }
140};
141
142template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000143struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000144 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000145 FormatStyle::SpaceBeforeParensOptions &Value) {
146 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000147 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000148 FormatStyle::SBPO_ControlStatements);
149 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000150
151 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000152 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
153 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000154 }
155};
156
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000157template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000158 static void mapping(IO &IO, FormatStyle &Style) {
159 // When reading, read the language first, we need it for getPredefinedStyle.
160 IO.mapOptional("Language", Style.Language);
161
Alexander Kornienko49149672013-05-10 11:56:10 +0000162 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000163 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
164 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000165 ArrayRef<StringRef> Styles(StylesArray);
166 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
167 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000168 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000169 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000170 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000171 IO.mapOptional("# BasedOnStyle", StyleName);
172 break;
173 }
174 }
175 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000176 StringRef BasedOnStyle;
177 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000178 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000179 FormatStyle::LanguageKind OldLanguage = Style.Language;
180 FormatStyle::LanguageKind Language =
181 ((FormatStyle *)IO.getContext())->Language;
182 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000183 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
184 return;
185 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000186 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000187 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000188 }
189
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000190 // For backward compatibility.
191 if (!IO.outputting()) {
192 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
193 IO.mapOptional("IndentFunctionDeclarationAfterType",
194 Style.IndentWrappedFunctionNames);
195 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
196 IO.mapOptional("SpaceAfterControlStatementKeyword",
197 Style.SpaceBeforeParens);
198 }
199
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000201 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000202 IO.mapOptional("AlignConsecutiveAssignments",
203 Style.AlignConsecutiveAssignments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000204 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000205 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000206 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000207 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
208 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000209 IO.mapOptional("AllowShortBlocksOnASingleLine",
210 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000211 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
212 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000213 IO.mapOptional("AllowShortFunctionsOnASingleLine",
214 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000215 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
216 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000217 IO.mapOptional("AllowShortLoopsOnASingleLine",
218 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000219 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
220 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000221 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
222 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000223 IO.mapOptional("AlwaysBreakTemplateDeclarations",
224 Style.AlwaysBreakTemplateDeclarations);
225 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
226 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000227 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000228 IO.mapOptional("BreakBeforeBinaryOperators",
229 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000230 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000231 IO.mapOptional("BreakBeforeTernaryOperators",
232 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000233 IO.mapOptional("BreakConstructorInitializersBeforeComma",
234 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000236 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000237 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
238 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000239 IO.mapOptional("ConstructorInitializerIndentWidth",
240 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000241 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
242 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000243 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000244 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000245 IO.mapOptional("ExperimentalAutoDetectBinPacking",
246 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000247 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000248 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000249 IO.mapOptional("IndentWidth", Style.IndentWidth);
250 IO.mapOptional("IndentWrappedFunctionNames",
251 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000252 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
253 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000254 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
255 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000256 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000257 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000258 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000259 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000260 IO.mapOptional("ObjCSpaceBeforeProtocolList",
261 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000262 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
263 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000264 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000265 IO.mapOptional("PenaltyBreakFirstLessLess",
266 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000267 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000268 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
269 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
270 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000271 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000272 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000273 IO.mapOptional("SpaceBeforeAssignmentOperators",
274 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000275 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
276 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
277 IO.mapOptional("SpacesBeforeTrailingComments",
278 Style.SpacesBeforeTrailingComments);
279 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
280 IO.mapOptional("SpacesInContainerLiterals",
281 Style.SpacesInContainerLiterals);
282 IO.mapOptional("SpacesInCStyleCastParentheses",
283 Style.SpacesInCStyleCastParentheses);
284 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
285 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
286 IO.mapOptional("Standard", Style.Standard);
287 IO.mapOptional("TabWidth", Style.TabWidth);
288 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000289 }
290};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000291
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000292template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
293 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
294 IO.mapOptional("AfterClass", Wrapping.AfterClass);
295 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
296 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
297 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
298 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
299 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
300 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
301 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
302 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
303 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
304 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
305 }
306};
307
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000308// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000309// IO.getContext() should contain a pointer to the FormatStyle structure, that
310// will be used to get default values for missing keys.
311// If the first element has no Language specified, it will be treated as the
312// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000313template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000314 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
315 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000316 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000317 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000318 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000319 if (Index >= Seq.size()) {
320 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000321 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000322 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000323 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000324 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000325 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000326 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000327 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000328 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000329 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000330 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000331 }
332};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000333} // namespace yaml
334} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000335
Daniel Jasperf7935112012-12-03 18:12:45 +0000336namespace clang {
337namespace format {
338
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000339const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000340 static ParseErrorCategory C;
341 return C;
342}
343std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000344 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000345}
346
347const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
348 return "clang-format.parse_error";
349}
350
351std::string ParseErrorCategory::message(int EV) const {
352 switch (static_cast<ParseError>(EV)) {
353 case ParseError::Success:
354 return "Success";
355 case ParseError::Error:
356 return "Invalid argument";
357 case ParseError::Unsuitable:
358 return "Unsuitable";
359 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000360 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000361}
362
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000363static FormatStyle expandPresets(const FormatStyle &Style) {
364 FormatStyle Expanded = Style;
365 Expanded.BraceWrapping = {false, false, false, false, false, false,
366 false, false, false, false, false};
367 switch (Style.BreakBeforeBraces) {
368 case FormatStyle::BS_Linux:
369 Expanded.BraceWrapping.AfterClass = true;
370 Expanded.BraceWrapping.AfterFunction = true;
371 Expanded.BraceWrapping.AfterNamespace = true;
372 Expanded.BraceWrapping.BeforeElse = true;
373 break;
374 case FormatStyle::BS_Mozilla:
375 Expanded.BraceWrapping.AfterClass = true;
376 Expanded.BraceWrapping.AfterEnum = true;
377 Expanded.BraceWrapping.AfterFunction = true;
378 Expanded.BraceWrapping.AfterStruct = true;
379 Expanded.BraceWrapping.AfterUnion = true;
380 break;
381 case FormatStyle::BS_Stroustrup:
382 Expanded.BraceWrapping.AfterFunction = true;
383 Expanded.BraceWrapping.BeforeCatch = true;
384 Expanded.BraceWrapping.BeforeElse = true;
385 break;
386 case FormatStyle::BS_Allman:
387 Expanded.BraceWrapping.AfterClass = true;
388 Expanded.BraceWrapping.AfterControlStatement = true;
389 Expanded.BraceWrapping.AfterEnum = true;
390 Expanded.BraceWrapping.AfterFunction = true;
391 Expanded.BraceWrapping.AfterNamespace = true;
392 Expanded.BraceWrapping.AfterObjCDeclaration = true;
393 Expanded.BraceWrapping.AfterStruct = true;
394 Expanded.BraceWrapping.BeforeCatch = true;
395 Expanded.BraceWrapping.BeforeElse = true;
396 break;
397 case FormatStyle::BS_GNU:
398 Expanded.BraceWrapping = {true, true, true, true, true, true,
399 true, true, true, true, true};
400 break;
401 case FormatStyle::BS_WebKit:
402 Expanded.BraceWrapping.AfterFunction = true;
403 break;
404 default:
405 break;
406 }
407 return Expanded;
408}
409
Daniel Jasperf7935112012-12-03 18:12:45 +0000410FormatStyle getLLVMStyle() {
411 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000412 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000413 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000414 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000415 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000416 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000417 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000418 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000419 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000420 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000421 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000422 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000423 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000424 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000425 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000426 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000427 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000428 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000429 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000430 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000431 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000432 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
433 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000434 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000435 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000436 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000437 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000438 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000439 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000440 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000441 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000442 LLVMStyle.ForEachMacros.push_back("foreach");
443 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
444 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000445 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
446 {"^(<|\"(gtest|isl|json)/)", 3},
447 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000448 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000449 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000450 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000451 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000452 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000453 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000454 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000455 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000456 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000457 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000458 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000459 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000460 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000461 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000462 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000463 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000464 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000465 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000466 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000467 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000468 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000469 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000470 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000471
Daniel Jasper19a541e2013-12-19 16:45:34 +0000472 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000473 LLVMStyle.PenaltyBreakFirstLessLess = 120;
474 LLVMStyle.PenaltyBreakString = 1000;
475 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000476 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000477 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000478
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000479 LLVMStyle.DisableFormat = false;
480
Daniel Jasperf7935112012-12-03 18:12:45 +0000481 return LLVMStyle;
482}
483
Nico Weber514ecc82014-02-02 20:50:45 +0000484FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000485 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000486 GoogleStyle.Language = Language;
487
Daniel Jasperf7935112012-12-03 18:12:45 +0000488 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000489 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000490 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000491 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000492 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000493 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000494 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000495 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000496 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000497 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000498 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000499 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000500 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000501 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000502 GoogleStyle.SpacesBeforeTrailingComments = 2;
503 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000504
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000505 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000506 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000507
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000508 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000509 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000510 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000511 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000512 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000513 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000514 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000515 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
516 GoogleStyle.ColumnLimit = 100;
517 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000518 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000519 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000520 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000521 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000522 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000523 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000524 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000525 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000526 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000527 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000528 }
529
Daniel Jasperf7935112012-12-03 18:12:45 +0000530 return GoogleStyle;
531}
532
Nico Weber514ecc82014-02-02 20:50:45 +0000533FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
534 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000535 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000536 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000537 ChromiumStyle.IndentWidth = 4;
538 ChromiumStyle.ContinuationIndentWidth = 8;
539 } else {
540 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
541 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
542 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
543 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
544 ChromiumStyle.BinPackParameters = false;
545 ChromiumStyle.DerivePointerAlignment = false;
546 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000547 return ChromiumStyle;
548}
549
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000550FormatStyle getMozillaStyle() {
551 FormatStyle MozillaStyle = getLLVMStyle();
552 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000553 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000554 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
555 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000556 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000557 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000558 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
559 MozillaStyle.ConstructorInitializerIndentWidth = 2;
560 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000561 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000562 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000563 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000564 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
565 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000566 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000567 return MozillaStyle;
568}
569
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000570FormatStyle getWebKitStyle() {
571 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000572 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000573 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000574 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000575 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000576 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000577 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000578 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000579 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000580 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000581 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000582 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000583 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000584 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000585 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000586 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000587 return Style;
588}
589
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000590FormatStyle getGNUStyle() {
591 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000592 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000593 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000594 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000595 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000596 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000597 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000598 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000599 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000600 return Style;
601}
602
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000603FormatStyle getNoStyle() {
604 FormatStyle NoStyle = getLLVMStyle();
605 NoStyle.DisableFormat = true;
606 return NoStyle;
607}
608
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000609bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
610 FormatStyle *Style) {
611 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000612 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000613 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000614 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000615 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000616 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000617 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000618 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000619 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000620 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000621 } else if (Name.equals_lower("gnu")) {
622 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000623 } else if (Name.equals_lower("none")) {
624 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000625 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000626 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000627 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000628
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000629 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000630 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000631}
632
Rafael Espindolac0809172014-06-12 14:02:15 +0000633std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000634 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000635 FormatStyle::LanguageKind Language = Style->Language;
636 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000637 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000638 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000639
640 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000641 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000642 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
643 // values for the fields, keys for which are missing from the configuration.
644 // Mapping also uses the context to get the language to find the correct
645 // base style.
646 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000647 Input >> Styles;
648 if (Input.error())
649 return Input.error();
650
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000651 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000652 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000653 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000654 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000655 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000656 for (unsigned j = 0; j < i; ++j) {
657 if (Styles[i].Language == Styles[j].Language) {
658 DEBUG(llvm::dbgs()
659 << "Duplicate languages in the config file on positions " << j
660 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000661 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000662 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000663 }
664 }
665 // Look for a suitable configuration starting from the end, so we can
666 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000667 // configuration (which can only be at slot 0) after it.
668 for (int i = Styles.size() - 1; i >= 0; --i) {
669 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000670 Styles[i].Language == FormatStyle::LK_None) {
671 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000672 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000673 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000674 }
675 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000676 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000677}
678
679std::string configurationAsText(const FormatStyle &Style) {
680 std::string Text;
681 llvm::raw_string_ostream Stream(Text);
682 llvm::yaml::Output Output(Stream);
683 // We use the same mapping method for input and output, so we need a non-const
684 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000685 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000686 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000687 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000688}
689
Craig Topperaf35e852013-06-30 22:29:28 +0000690namespace {
691
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000692class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000693public:
Daniel Jasper23376252014-09-09 14:37:39 +0000694 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000695 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000696 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000697 LessStashed(false), Column(0), TrailingWhitespace(0),
698 SourceMgr(SourceMgr), ID(ID), Style(Style),
699 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000700 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
701 MacroBlockBeginRegex(Style.MacroBlockBegin),
702 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000703 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
704 getFormattingLangOpts(Style)));
705 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000706
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000707 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000708 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
709 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000710 }
711
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000712 ArrayRef<FormatToken *> lex() {
713 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000714 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000715 do {
716 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000717 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000718 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000719 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000720 } while (Tokens.back()->Tok.isNot(tok::eof));
721 return Tokens;
722 }
723
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000724 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000725
726private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000727 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000728 if (tryMerge_TMacro())
729 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000730 if (tryMergeConflictMarkers())
731 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000732 if (tryMergeLessLess())
733 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000734
735 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000736 if (tryMergeJSRegexLiteral())
737 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000738 if (tryMergeEscapeSequence())
739 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000740 if (tryMergeTemplateString())
741 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000742
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000743 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
744 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
745 tok::equal};
746 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
747 tok::greaterequal};
748 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000749 // FIXME: Investigate what token type gives the correct operator priority.
750 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000751 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000752 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000753 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000754 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000755 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000756 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000757 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000758 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000759 }
760
Jacques Pienaarfc275112015-02-18 23:48:37 +0000761 bool tryMergeLessLess() {
762 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000763 if (Tokens.size() < 3)
764 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000765
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000766 bool FourthTokenIsLess = false;
767 if (Tokens.size() > 3)
768 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000769
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000770 auto First = Tokens.end() - 3;
771 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
772 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000773 return false;
774
775 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000776 if (First[1]->WhitespaceRange.getBegin() !=
777 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000778 return false;
779
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000780 First[0]->Tok.setKind(tok::lessless);
781 First[0]->TokenText = "<<";
782 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000783 Tokens.erase(Tokens.end() - 2);
784 return true;
785 }
786
Manuel Klimek79e06082015-05-21 12:23:34 +0000787 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000788 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000789 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000790
791 SmallVectorImpl<FormatToken *>::const_iterator First =
792 Tokens.end() - Kinds.size();
793 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000794 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000795 unsigned AddLength = 0;
796 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000797 if (!First[i]->is(Kinds[i]) ||
798 First[i]->WhitespaceRange.getBegin() !=
799 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000800 return false;
801 AddLength += First[i]->TokenText.size();
802 }
803 Tokens.resize(Tokens.size() - Kinds.size() + 1);
804 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
805 First[0]->TokenText.size() + AddLength);
806 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000807 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000808 return true;
809 }
810
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000811 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000812 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000813 bool tryMergeEscapeSequence() {
814 if (Tokens.size() < 2)
815 return false;
816 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000817 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000818 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000819 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000820 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000821 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
822 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000823 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000824 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000825 return true;
826 }
827
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000828 // Try to determine whether the current token ends a JavaScript regex literal.
829 // We heuristically assume that this is a regex literal if we find two
830 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000831 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
832 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000833 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000834 if (Tokens.size() < 2)
835 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000836
837 // If this is a string literal with a slash inside, compute the slash's
838 // offset and try to find the beginning of the regex literal.
839 // Also look at tok::unknown, as it can be an unterminated char literal.
840 size_t SlashInStringPos = StringRef::npos;
841 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
842 tok::unknown)) {
843 // Start search from position 1 as otherwise, this is an unknown token
844 // for an unterminated /*-comment which is handled elsewhere.
845 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
846 if (SlashInStringPos == StringRef::npos)
847 return false;
848 }
849
Daniel Jasper23376252014-09-09 14:37:39 +0000850 // If a regex literal ends in "\//", this gets represented by an unknown
851 // token "\" and a comment.
852 bool MightEndWithEscapedSlash =
853 Tokens.back()->is(tok::comment) &&
854 Tokens.back()->TokenText.startswith("//") &&
855 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000856 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000857 (Tokens.back()->isNot(tok::slash) ||
858 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
859 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000860 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000861
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000862 unsigned TokenCount = 0;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000863 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
864 ++TokenCount;
Daniel Jasperf7372152015-07-02 14:14:04 +0000865 auto Prev = I + 1;
866 while (Prev != E && Prev[0]->is(tok::comment))
867 ++Prev;
Daniel Jasperc553ae12015-07-02 13:20:45 +0000868 if (I[0]->isOneOf(tok::slash, tok::slashequal) &&
Daniel Jasperf7372152015-07-02 14:14:04 +0000869 (Prev == E ||
870 ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
871 tok::r_brace, tok::exclaim, tok::l_square,
872 tok::colon, tok::comma, tok::question,
873 tok::kw_return) ||
874 Prev[0]->isBinaryOperator())))) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000875 unsigned LastColumn = Tokens.back()->OriginalColumn;
876 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000877 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000878 // This regex literal ends in '\//'. Skip past the '//' of the last
879 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000880 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000881 } else if (SlashInStringPos != StringRef::npos) {
882 // This regex literal ends in a string_literal with a slash inside.
883 // Calculate end column and reset lexer appropriately.
884 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
885 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000886 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000887 Tokens.resize(Tokens.size() - TokenCount);
888 Tokens.back()->Tok.setKind(tok::unknown);
889 Tokens.back()->Type = TT_RegexLiteral;
Daniel Jasperf1446202015-07-02 15:00:44 +0000890 // Treat regex literals like other string_literals.
891 Tokens.back()->Tok.setKind(tok::string_literal);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000892 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
893 return true;
894 }
895
896 // There can't be a newline inside a regex literal.
897 if (I[0]->NewlinesBefore > 0)
898 return false;
899 }
900 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000901 }
902
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000903 bool tryMergeTemplateString() {
904 if (Tokens.size() < 2)
905 return false;
906
907 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000908 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000909 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
910 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000911 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
912 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000913 return false;
914 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
915 // Unknown token that's not actually a backtick, or a comment that doesn't
916 // contain a backtick.
917 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000918 return false;
919
920 unsigned TokenCount = 0;
921 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000922 unsigned EndColumnInFirstLine =
923 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000924 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
925 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000926 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000927 IsMultiline = true;
928
929 // If there was a preceding template string, this must be the start of a
930 // template string, not the end.
931 if (I[0]->is(TT_TemplateString))
932 return false;
933
934 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
935 // Keep track of the rhs offset of the last token to wrap across lines -
936 // its the rhs offset of the first line of the template string, used to
937 // determine its width.
938 if (I[0]->IsMultiline)
939 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
940 // If the token has newlines, the token before it (if it exists) is the
941 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000942 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000943 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000944 IsMultiline = true;
945 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000946 continue;
947 }
948
949 Tokens.resize(Tokens.size() - TokenCount);
950 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000951 const char *EndOffset =
952 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
953 if (CommentBacktickPos != 0) {
954 // If the backtick was not the first character (e.g. in a comment),
955 // re-lex after the backtick position.
956 SourceLocation Loc = EndBacktick->Tok.getLocation();
957 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
958 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000959 Tokens.back()->TokenText =
960 StringRef(Tokens.back()->TokenText.data(),
961 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000962
963 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
964 if (EndOriginalColumn == 0) {
965 SourceLocation Loc = EndBacktick->Tok.getLocation();
966 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
967 }
968 // If the ` is further down within the token (e.g. in a comment).
969 EndOriginalColumn += CommentBacktickPos;
970
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000971 if (IsMultiline) {
972 // ColumnWidth is from backtick to last token in line.
973 // LastLineColumnWidth is 0 to backtick.
974 // x = `some content
975 // until here`;
976 Tokens.back()->ColumnWidth =
977 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000978 // +1 for the ` itself.
979 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000980 Tokens.back()->IsMultiline = true;
981 } else {
982 // Token simply spans from start to end, +1 for the ` itself.
983 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000984 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000985 }
986 return true;
987 }
988 return false;
989 }
990
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000991 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000992 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000993 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000994 FormatToken *Last = Tokens.back();
995 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000996 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000997
998 FormatToken *String = Tokens[Tokens.size() - 2];
999 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001000 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001001
1002 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001003 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001004
1005 FormatToken *Macro = Tokens[Tokens.size() - 4];
1006 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001007 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001008
1009 const char *Start = Macro->TokenText.data();
1010 const char *End = Last->TokenText.data() + Last->TokenText.size();
1011 String->TokenText = StringRef(Start, End - Start);
1012 String->IsFirst = Macro->IsFirst;
1013 String->LastNewlineOffset = Macro->LastNewlineOffset;
1014 String->WhitespaceRange = Macro->WhitespaceRange;
1015 String->OriginalColumn = Macro->OriginalColumn;
1016 String->ColumnWidth = encoding::columnWidthWithTabs(
1017 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001018 String->NewlinesBefore = Macro->NewlinesBefore;
1019 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001020
1021 Tokens.pop_back();
1022 Tokens.pop_back();
1023 Tokens.pop_back();
1024 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001025 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001026 }
1027
Manuel Klimek68b03042014-04-14 09:14:11 +00001028 bool tryMergeConflictMarkers() {
1029 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1030 return false;
1031
1032 // Conflict lines look like:
1033 // <marker> <text from the vcs>
1034 // For example:
1035 // >>>>>>> /file/in/file/system at revision 1234
1036 //
1037 // We merge all tokens in a line that starts with a conflict marker
1038 // into a single token with a special token type that the unwrapped line
1039 // parser will use to correctly rebuild the underlying code.
1040
1041 FileID ID;
1042 // Get the position of the first token in the line.
1043 unsigned FirstInLineOffset;
1044 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1045 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1046 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1047 // Calculate the offset of the start of the current line.
1048 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1049 if (LineOffset == StringRef::npos) {
1050 LineOffset = 0;
1051 } else {
1052 ++LineOffset;
1053 }
1054
1055 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1056 StringRef LineStart;
1057 if (FirstSpace == StringRef::npos) {
1058 LineStart = Buffer.substr(LineOffset);
1059 } else {
1060 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1061 }
1062
1063 TokenType Type = TT_Unknown;
1064 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1065 Type = TT_ConflictStart;
1066 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1067 LineStart == "====") {
1068 Type = TT_ConflictAlternative;
1069 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1070 Type = TT_ConflictEnd;
1071 }
1072
1073 if (Type != TT_Unknown) {
1074 FormatToken *Next = Tokens.back();
1075
1076 Tokens.resize(FirstInLineIndex + 1);
1077 // We do not need to build a complete token here, as we will skip it
1078 // during parsing anyway (as we must not touch whitespace around conflict
1079 // markers).
1080 Tokens.back()->Type = Type;
1081 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1082
1083 Tokens.push_back(Next);
1084 return true;
1085 }
1086
1087 return false;
1088 }
1089
Jacques Pienaarfc275112015-02-18 23:48:37 +00001090 FormatToken *getStashedToken() {
1091 // Create a synthesized second '>' or '<' token.
1092 Token Tok = FormatTok->Tok;
1093 StringRef TokenText = FormatTok->TokenText;
1094
1095 unsigned OriginalColumn = FormatTok->OriginalColumn;
1096 FormatTok = new (Allocator.Allocate()) FormatToken;
1097 FormatTok->Tok = Tok;
1098 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001099 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1100 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001101 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1102 FormatTok->TokenText = TokenText;
1103 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001104 FormatTok->OriginalColumn = OriginalColumn + 1;
1105
Jacques Pienaarfc275112015-02-18 23:48:37 +00001106 return FormatTok;
1107 }
1108
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001109 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001110 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001111 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001112 return getStashedToken();
1113 }
1114 if (LessStashed) {
1115 LessStashed = false;
1116 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001117 }
1118
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001119 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001120 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001121 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001122 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001123 FormatTok->IsFirst = IsFirstToken;
1124 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001125
1126 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001127 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001128 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001129 StringRef Text = FormatTok->TokenText;
1130 auto EscapesNewline = [&](int pos) {
1131 // A '\r' here is just part of '\r\n'. Skip it.
1132 if (pos >= 0 && Text[pos] == '\r')
1133 --pos;
1134 // See whether there is an odd number of '\' before this.
1135 unsigned count = 0;
1136 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001137 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001138 break;
1139 return count & 1;
1140 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001141 // FIXME: This miscounts tok:unknown tokens that are not just
1142 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001143 for (int i = 0, e = Text.size(); i != e; ++i) {
1144 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001145 case '\n':
1146 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001147 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001148 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1149 Column = 0;
1150 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001151 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001152 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1153 Column = 0;
1154 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001155 case '\f':
1156 case '\v':
1157 Column = 0;
1158 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001159 case ' ':
1160 ++Column;
1161 break;
1162 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001163 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001164 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001165 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001166 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001167 FormatTok->Type = TT_ImplicitStringLiteral;
1168 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001169 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001170 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001171 break;
1172 }
1173 }
1174
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001175 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001176 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001177 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001178
Daniel Jasper8369aa52013-07-16 20:28:33 +00001179 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001180 }
Manuel Klimekef920692013-01-07 07:56:50 +00001181
Manuel Klimek1abf7892013-01-04 23:34:14 +00001182 // In case the token starts with escaped newlines, we want to
1183 // take them into account as whitespace - this pattern is quite frequent
1184 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001185 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001186 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1187 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001188 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001189 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001190 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001191 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001192 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001193 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001194
1195 FormatTok->WhitespaceRange = SourceRange(
1196 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1197
Manuel Klimek31c85922013-08-29 15:21:40 +00001198 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001199
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001200 TrailingWhitespace = 0;
1201 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001202 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001203 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001204 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001205 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001206 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001207 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001208 FormatTok->Tok.setIdentifierInfo(&Info);
1209 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001210 if (Style.Language == FormatStyle::LK_Java &&
1211 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1212 FormatTok->Tok.setKind(tok::identifier);
1213 FormatTok->Tok.setIdentifierInfo(nullptr);
1214 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001215 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001216 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001217 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001218 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001219 } else if (FormatTok->Tok.is(tok::lessless)) {
1220 FormatTok->Tok.setKind(tok::less);
1221 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1222 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001223 }
1224
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001225 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001226
Alexander Kornienko39856b72013-09-10 09:38:25 +00001227 StringRef Text = FormatTok->TokenText;
1228 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001229 if (FirstNewlinePos == StringRef::npos) {
1230 // FIXME: ColumnWidth actually depends on the start column, we need to
1231 // take this into account when the token is moved.
1232 FormatTok->ColumnWidth =
1233 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1234 Column += FormatTok->ColumnWidth;
1235 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001236 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001237 // FIXME: ColumnWidth actually depends on the start column, we need to
1238 // take this into account when the token is moved.
1239 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1240 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1241
Alexander Kornienko39856b72013-09-10 09:38:25 +00001242 // The last line of the token always starts in column 0.
1243 // Thus, the length can be precomputed even in the presence of tabs.
1244 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1245 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1246 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001247 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001248 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001249
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001250 if (Style.Language == FormatStyle::LK_Cpp) {
1251 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1252 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1253 tok::pp_define) &&
1254 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1255 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1256 FormatTok->Type = TT_ForEachMacro;
1257 } else if (FormatTok->is(tok::identifier)) {
1258 if (MacroBlockBeginRegex.match(Text)) {
1259 FormatTok->Type = TT_MacroBlockBegin;
1260 } else if (MacroBlockEndRegex.match(Text)) {
1261 FormatTok->Type = TT_MacroBlockEnd;
1262 }
1263 }
1264 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001265
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001266 return FormatTok;
1267 }
1268
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001269 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001270 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001271 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001272 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001273 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001274 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001276 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001277 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001278 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001279 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001280 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001281 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001282 // Index (in 'Tokens') of the last token that starts a new line.
1283 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001284 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001285 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001286
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001287 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001288
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001289 llvm::Regex MacroBlockBeginRegex;
1290 llvm::Regex MacroBlockEndRegex;
1291
Daniel Jasper8369aa52013-07-16 20:28:33 +00001292 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001293 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001294 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1295 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001296 // For formatting, treat unterminated string literals like normal string
1297 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001298 if (Tok.is(tok::unknown)) {
1299 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1300 Tok.Tok.setKind(tok::string_literal);
1301 Tok.IsUnterminatedLiteral = true;
1302 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1303 Tok.TokenText == "''") {
1304 Tok.Tok.setKind(tok::char_constant);
1305 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001306 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001307
1308 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1309 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001310 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001311 }
1312
Daniel Jasper471894432014-08-06 13:40:26 +00001313 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001314
1315 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1316 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001317 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001318 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001319 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001320
1321 void resetLexer(unsigned Offset) {
1322 StringRef Buffer = SourceMgr.getBufferData(ID);
1323 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1324 getFormattingLangOpts(Style), Buffer.begin(),
1325 Buffer.begin() + Offset, Buffer.end()));
1326 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001327 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001328 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001329};
1330
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001331static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1332 switch (Language) {
1333 case FormatStyle::LK_Cpp:
1334 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001335 case FormatStyle::LK_Java:
1336 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001337 case FormatStyle::LK_JavaScript:
1338 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001339 case FormatStyle::LK_Proto:
1340 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001341 default:
1342 return "Unknown";
1343 }
1344}
1345
Daniel Jasperf7935112012-12-03 18:12:45 +00001346class Formatter : public UnwrappedLineConsumer {
1347public:
Daniel Jasper23376252014-09-09 14:37:39 +00001348 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001349 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001350 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1351 Whitespaces(SourceMgr, Style,
1352 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001353 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001354 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001355 DEBUG(llvm::dbgs() << "File encoding: "
1356 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1357 : "unknown")
1358 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001359 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1360 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001361 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001362
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001363 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001364 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001365 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001366
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001367 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1368 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001369 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001370 assert(UnwrappedLines.rbegin()->empty());
1371 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1372 ++Run) {
1373 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1374 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1375 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1376 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1377 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001378 tooling::Replacements RunResult =
1379 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001380 DEBUG({
1381 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1382 for (tooling::Replacements::iterator I = RunResult.begin(),
1383 E = RunResult.end();
1384 I != E; ++I) {
1385 llvm::dbgs() << I->toString() << "\n";
1386 }
1387 });
1388 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1389 delete AnnotatedLines[i];
1390 }
1391 Result.insert(RunResult.begin(), RunResult.end());
1392 Whitespaces.reset();
1393 }
1394 return Result;
1395 }
1396
1397 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001398 FormatTokenLexer &Tokens,
1399 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001400 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001401 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001402 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001403 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001404 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001405 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001406 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001407 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001408 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001409
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001410 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001411 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1412 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001413 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001414 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1415 IncompleteFormat)
1416 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001417 return Whitespaces.generateReplacements();
1418 }
1419
1420private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001421 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001422 // Returns \c true if at least one line between I and E or one of their
1423 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001424 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1425 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1426 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001427 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001428 while (I != E) {
1429 AnnotatedLine *Line = *I;
1430 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1431
1432 // If a line is part of a preprocessor directive, it needs to be formatted
1433 // if any token within the directive is affected.
1434 if (Line->InPPDirective) {
1435 FormatToken *Last = Line->Last;
1436 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1437 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1438 Last = (*PPEnd)->Last;
1439 ++PPEnd;
1440 }
1441
1442 if (affectsTokenRange(*Line->First, *Last,
1443 /*IncludeLeadingNewlines=*/false)) {
1444 SomeLineAffected = true;
1445 markAllAsAffected(I, PPEnd);
1446 }
1447 I = PPEnd;
1448 continue;
1449 }
1450
Daniel Jasper38c82402013-11-29 09:27:43 +00001451 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001452 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001453
Daniel Jasper38c82402013-11-29 09:27:43 +00001454 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001455 ++I;
1456 }
1457 return SomeLineAffected;
1458 }
1459
Daniel Jasper9c199562013-11-28 15:58:55 +00001460 // Determines whether 'Line' is affected by the SourceRanges given as input.
1461 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001462 bool nonPPLineAffected(AnnotatedLine *Line,
1463 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001464 bool SomeLineAffected = false;
1465 Line->ChildrenAffected =
1466 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1467 if (Line->ChildrenAffected)
1468 SomeLineAffected = true;
1469
1470 // Stores whether one of the line's tokens is directly affected.
1471 bool SomeTokenAffected = false;
1472 // Stores whether we need to look at the leading newlines of the next token
1473 // in order to determine whether it was affected.
1474 bool IncludeLeadingNewlines = false;
1475
1476 // Stores whether the first child line of any of this line's tokens is
1477 // affected.
1478 bool SomeFirstChildAffected = false;
1479
1480 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1481 // Determine whether 'Tok' was affected.
1482 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1483 SomeTokenAffected = true;
1484
1485 // Determine whether the first child of 'Tok' was affected.
1486 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1487 SomeFirstChildAffected = true;
1488
1489 IncludeLeadingNewlines = Tok->Children.empty();
1490 }
1491
1492 // Was this line moved, i.e. has it previously been on the same line as an
1493 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001494 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1495 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001496
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001497 bool IsContinuedComment =
1498 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1499 Line->First->NewlinesBefore < 2 && PreviousLine &&
1500 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001501
1502 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1503 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001504 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001505 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001506 }
1507 return SomeLineAffected;
1508 }
1509
Daniel Jasper5500f612013-11-25 11:08:59 +00001510 // Marks all lines between I and E as well as all their children as affected.
1511 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1512 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1513 while (I != E) {
1514 (*I)->Affected = true;
1515 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1516 ++I;
1517 }
1518 }
1519
1520 // Returns true if the range from 'First' to 'Last' intersects with one of the
1521 // input ranges.
1522 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1523 bool IncludeLeadingNewlines) {
1524 SourceLocation Start = First.WhitespaceRange.getBegin();
1525 if (!IncludeLeadingNewlines)
1526 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001527 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001528 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001529 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1530 return affectsCharSourceRange(Range);
1531 }
1532
1533 // Returns true if one of the input ranges intersect the leading empty lines
1534 // before 'Tok'.
1535 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1536 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1537 Tok.WhitespaceRange.getBegin(),
1538 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1539 return affectsCharSourceRange(EmptyLineRange);
1540 }
1541
1542 // Returns true if 'Range' intersects with one of the input ranges.
1543 bool affectsCharSourceRange(const CharSourceRange &Range) {
1544 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1545 E = Ranges.end();
1546 I != E; ++I) {
1547 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1548 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1549 return true;
1550 }
1551 return false;
1552 }
1553
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001554 static bool inputUsesCRLF(StringRef Text) {
1555 return Text.count('\r') * 2 > Text.count('\n');
1556 }
1557
Daniel Jasper352f0df2015-07-18 16:35:30 +00001558 bool
1559 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1560 for (const AnnotatedLine* Line : Lines) {
1561 if (hasCpp03IncompatibleFormat(Line->Children))
1562 return true;
1563 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1564 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1565 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1566 return true;
1567 if (Tok->is(TT_TemplateCloser) &&
1568 Tok->Previous->is(TT_TemplateCloser))
1569 return true;
1570 }
1571 }
1572 }
1573 return false;
1574 }
1575
1576 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1577 int AlignmentDiff = 0;
1578 for (const AnnotatedLine* Line : Lines) {
1579 AlignmentDiff += countVariableAlignments(Line->Children);
1580 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1581 if (!Tok->is(TT_PointerOrReference))
1582 continue;
1583 bool SpaceBefore =
1584 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1585 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1586 Tok->Next->WhitespaceRange.getEnd();
1587 if (SpaceBefore && !SpaceAfter)
1588 ++AlignmentDiff;
1589 if (!SpaceBefore && SpaceAfter)
1590 --AlignmentDiff;
1591 }
1592 }
1593 return AlignmentDiff;
1594 }
1595
Manuel Klimek71814b42013-10-11 21:25:45 +00001596 void
1597 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001598 bool HasBinPackedFunction = false;
1599 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001600 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001601 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001602 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001603 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001604 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001605 if (Tok->PackingKind == PPK_BinPacked)
1606 HasBinPackedFunction = true;
1607 if (Tok->PackingKind == PPK_OnePerLine)
1608 HasOnePerLineFunction = true;
1609
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001610 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001611 }
1612 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001613 if (Style.DerivePointerAlignment)
1614 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1615 ? FormatStyle::PAS_Left
1616 : FormatStyle::PAS_Right;
1617 if (Style.Standard == FormatStyle::LS_Auto)
1618 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1619 ? FormatStyle::LS_Cpp11
1620 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001621 BinPackInconclusiveFunctions =
1622 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001623 }
1624
Craig Topperfb6b25b2014-03-15 04:29:04 +00001625 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001626 assert(!UnwrappedLines.empty());
1627 UnwrappedLines.back().push_back(TheLine);
1628 }
1629
Craig Topperfb6b25b2014-03-15 04:29:04 +00001630 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001631 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001632 }
1633
1634 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001635 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001636 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001637 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001638 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001639 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001640
1641 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001642 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001643};
1644
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001645struct IncludeDirective {
1646 StringRef Filename;
1647 StringRef Text;
1648 unsigned Offset;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001649 unsigned Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001650};
1651
Craig Topperaf35e852013-06-30 22:29:28 +00001652} // end anonymous namespace
1653
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001654// Determines whether 'Ranges' intersects with ('Start', 'End').
1655static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1656 unsigned End) {
1657 for (auto Range : Ranges) {
1658 if (Range.getOffset() < End &&
1659 Range.getOffset() + Range.getLength() > Start)
1660 return true;
1661 }
1662 return false;
1663}
1664
1665// Sorts a block of includes given by 'Includes' alphabetically adding the
1666// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1667// order.
1668static void sortIncludes(const FormatStyle &Style,
1669 const SmallVectorImpl<IncludeDirective> &Includes,
1670 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1671 tooling::Replacements &Replaces) {
1672 if (!affectsRange(Ranges, Includes.front().Offset,
1673 Includes.back().Offset + Includes.back().Text.size()))
1674 return;
1675 SmallVector<unsigned, 16> Indices;
1676 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1677 Indices.push_back(i);
1678 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001679 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1680 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001681 });
1682
1683 // If the #includes are out of order, we generate a single replacement fixing
1684 // the entire block. Otherwise, no replacement is generated.
1685 bool OutOfOrder = false;
1686 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1687 if (Indices[i] != i) {
1688 OutOfOrder = true;
1689 break;
1690 }
1691 }
1692 if (!OutOfOrder)
1693 return;
1694
1695 std::string result = Includes[Indices[0]].Text;
1696 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1697 result += "\n";
1698 result += Includes[Indices[i]].Text;
1699 }
1700
1701 // Sorting #includes shouldn't change their total number of characters.
1702 // This would otherwise mess up 'Ranges'.
1703 assert(result.size() ==
1704 Includes.back().Offset + Includes.back().Text.size() -
1705 Includes.front().Offset);
1706
1707 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1708 result.size(), result));
1709}
1710
1711tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1712 ArrayRef<tooling::Range> Ranges,
1713 StringRef FileName) {
1714 tooling::Replacements Replaces;
1715 unsigned Prev = 0;
1716 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001717 llvm::Regex IncludeRegex(
1718 R"(^[\t\ ]*#[\t\ ]*include[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001719 SmallVector<StringRef, 4> Matches;
1720 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001721
1722 // In compiled files, consider the first #include to be the main #include of
1723 // the file if it is not a system #include. This ensures that the header
1724 // doesn't have hidden dependencies
1725 // (http://llvm.org/docs/CodingStandards.html#include-style).
1726 //
1727 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1728 // cases where the first #include is unlikely to be the main header.
1729 bool LookForMainHeader = FileName.endswith(".c") ||
1730 FileName.endswith(".cc") ||
1731 FileName.endswith(".cpp")||
1732 FileName.endswith(".c++")||
1733 FileName.endswith(".cxx");
1734
1735 // Create pre-compiled regular expressions for the #include categories.
1736 SmallVector<llvm::Regex, 4> CategoryRegexs;
1737 for (const auto &IncludeBlock : Style.IncludeCategories)
1738 CategoryRegexs.emplace_back(IncludeBlock.first);
1739
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001740 for (;;) {
1741 auto Pos = Code.find('\n', SearchFrom);
1742 StringRef Line =
1743 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1744 if (!Line.endswith("\\")) {
1745 if (IncludeRegex.match(Line, &Matches)) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001746 unsigned Category;
1747 if (LookForMainHeader && !Matches[1].startswith("<")) {
1748 Category = 0;
1749 } else {
1750 Category = UINT_MAX;
1751 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1752 if (CategoryRegexs[i].match(Matches[1])) {
1753 Category = Style.IncludeCategories[i].second;
1754 break;
1755 }
1756 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001757 }
Daniel Jasper85c472d2015-09-29 07:53:08 +00001758 LookForMainHeader = false;
1759 IncludesInBlock.push_back({Matches[1], Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001760 } else if (!IncludesInBlock.empty()) {
1761 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1762 IncludesInBlock.clear();
1763 }
1764 Prev = Pos + 1;
1765 }
1766 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1767 break;
1768 SearchFrom = Pos + 1;
1769 }
1770 if (!IncludesInBlock.empty())
1771 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1772 return Replaces;
1773}
1774
Daniel Jasper23376252014-09-09 14:37:39 +00001775tooling::Replacements reformat(const FormatStyle &Style,
1776 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001777 ArrayRef<CharSourceRange> Ranges,
1778 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001779 FormatStyle Expanded = expandPresets(Style);
1780 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001781 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001782 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001783 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001784}
1785
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001786tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001787 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001788 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001789 if (Style.DisableFormat)
1790 return tooling::Replacements();
1791
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001792 FileManager Files((FileSystemOptions()));
1793 DiagnosticsEngine Diagnostics(
1794 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1795 new DiagnosticOptions);
1796 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001797 std::unique_ptr<llvm::MemoryBuffer> Buf =
1798 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001799 const clang::FileEntry *Entry =
1800 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001801 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001802 FileID ID =
1803 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001804 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1805 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001806 for (const tooling::Range &Range : Ranges) {
1807 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1808 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001809 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1810 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001811 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001812}
1813
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001814LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001815 LangOptions LangOpts;
1816 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001817 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1818 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001819 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001820 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001821 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001822 LangOpts.Bool = 1;
1823 LangOpts.ObjC1 = 1;
1824 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001825 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001826 return LangOpts;
1827}
1828
Edwin Vaned544aa72013-09-30 13:31:48 +00001829const char *StyleOptionHelpDescription =
1830 "Coding style, currently supports:\n"
1831 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1832 "Use -style=file to load style configuration from\n"
1833 ".clang-format file located in one of the parent\n"
1834 "directories of the source file (or current\n"
1835 "directory for stdin).\n"
1836 "Use -style=\"{key: value, ...}\" to set specific\n"
1837 "parameters, e.g.:\n"
1838 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1839
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001840static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001841 if (FileName.endswith(".java")) {
1842 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001843 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1844 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001845 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001846 } else if (FileName.endswith_lower(".proto") ||
1847 FileName.endswith_lower(".protodevel")) {
1848 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001849 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001850 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001851}
1852
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001853FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1854 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001855 FormatStyle Style = getLLVMStyle();
1856 Style.Language = getLanguageByFileName(FileName);
1857 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001858 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1859 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001860 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001861 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001862
1863 if (StyleName.startswith("{")) {
1864 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001865 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001866 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1867 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001868 }
1869 return Style;
1870 }
1871
1872 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001873 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001874 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1875 << " style\n";
1876 return Style;
1877 }
1878
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001879 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001880 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001881 SmallString<128> Path(FileName);
1882 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001883 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001884 Directory = llvm::sys::path::parent_path(Directory)) {
1885 if (!llvm::sys::fs::is_directory(Directory))
1886 continue;
1887 SmallString<128> ConfigFile(Directory);
1888
1889 llvm::sys::path::append(ConfigFile, ".clang-format");
1890 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1891 bool IsFile = false;
1892 // Ignore errors from is_regular_file: we only need to know if we can read
1893 // the file or not.
1894 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1895
1896 if (!IsFile) {
1897 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1898 ConfigFile = Directory;
1899 llvm::sys::path::append(ConfigFile, "_clang-format");
1900 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1901 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1902 }
1903
1904 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001905 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1906 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1907 if (std::error_code EC = Text.getError()) {
1908 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001909 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001910 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001911 if (std::error_code ec =
1912 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001913 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001914 if (!UnsuitableConfigFiles.empty())
1915 UnsuitableConfigFiles.append(", ");
1916 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001917 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001918 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001919 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1920 << "\n";
1921 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001922 }
1923 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1924 return Style;
1925 }
1926 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001927 if (!UnsuitableConfigFiles.empty()) {
1928 llvm::errs() << "Configuration file(s) do(es) not support "
1929 << getLanguageName(Style.Language) << ": "
1930 << UnsuitableConfigFiles << "\n";
1931 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001932 return Style;
1933}
1934
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001935} // namespace format
1936} // namespace clang