blob: d8a15e4cdfbbb1b493166284d3dd974948ce7d4b [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);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000204 IO.mapOptional("AlignConsecutiveDeclarations",
205 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000206 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000207 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000208 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000209 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
210 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000211 IO.mapOptional("AllowShortBlocksOnASingleLine",
212 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000213 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
214 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000215 IO.mapOptional("AllowShortFunctionsOnASingleLine",
216 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000217 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
218 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000219 IO.mapOptional("AllowShortLoopsOnASingleLine",
220 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000221 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
222 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000223 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
224 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000225 IO.mapOptional("AlwaysBreakTemplateDeclarations",
226 Style.AlwaysBreakTemplateDeclarations);
227 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
228 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000229 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000230 IO.mapOptional("BreakBeforeBinaryOperators",
231 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000232 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000233 IO.mapOptional("BreakBeforeTernaryOperators",
234 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000235 IO.mapOptional("BreakConstructorInitializersBeforeComma",
236 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000237 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000238 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000239 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
240 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000241 IO.mapOptional("ConstructorInitializerIndentWidth",
242 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000243 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
244 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000245 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000246 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000247 IO.mapOptional("ExperimentalAutoDetectBinPacking",
248 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000249 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000250 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000251 IO.mapOptional("IndentWidth", Style.IndentWidth);
252 IO.mapOptional("IndentWrappedFunctionNames",
253 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000254 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
255 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000256 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
257 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000258 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000259 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000260 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000261 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000262 IO.mapOptional("ObjCSpaceBeforeProtocolList",
263 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000264 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
265 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000266 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000267 IO.mapOptional("PenaltyBreakFirstLessLess",
268 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000269 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000270 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
271 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
272 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000273 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000274 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000275 IO.mapOptional("SpaceBeforeAssignmentOperators",
276 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000277 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
278 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
279 IO.mapOptional("SpacesBeforeTrailingComments",
280 Style.SpacesBeforeTrailingComments);
281 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
282 IO.mapOptional("SpacesInContainerLiterals",
283 Style.SpacesInContainerLiterals);
284 IO.mapOptional("SpacesInCStyleCastParentheses",
285 Style.SpacesInCStyleCastParentheses);
286 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
287 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
288 IO.mapOptional("Standard", Style.Standard);
289 IO.mapOptional("TabWidth", Style.TabWidth);
290 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000291 }
292};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000293
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000294template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
295 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
296 IO.mapOptional("AfterClass", Wrapping.AfterClass);
297 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
298 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
299 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
300 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
301 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
302 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
303 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
304 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
305 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
306 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
307 }
308};
309
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000310// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000311// IO.getContext() should contain a pointer to the FormatStyle structure, that
312// will be used to get default values for missing keys.
313// If the first element has no Language specified, it will be treated as the
314// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000315template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000316 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
317 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000318 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000319 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000320 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000321 if (Index >= Seq.size()) {
322 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000323 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000324 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000325 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000326 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000327 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000328 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000329 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000330 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000331 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000332 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000333 }
334};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000335} // namespace yaml
336} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000337
Daniel Jasperf7935112012-12-03 18:12:45 +0000338namespace clang {
339namespace format {
340
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000341const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000342 static ParseErrorCategory C;
343 return C;
344}
345std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000346 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000347}
348
349const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
350 return "clang-format.parse_error";
351}
352
353std::string ParseErrorCategory::message(int EV) const {
354 switch (static_cast<ParseError>(EV)) {
355 case ParseError::Success:
356 return "Success";
357 case ParseError::Error:
358 return "Invalid argument";
359 case ParseError::Unsuitable:
360 return "Unsuitable";
361 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000362 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000363}
364
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000365static FormatStyle expandPresets(const FormatStyle &Style) {
366 FormatStyle Expanded = Style;
367 Expanded.BraceWrapping = {false, false, false, false, false, false,
368 false, false, false, false, false};
369 switch (Style.BreakBeforeBraces) {
370 case FormatStyle::BS_Linux:
371 Expanded.BraceWrapping.AfterClass = true;
372 Expanded.BraceWrapping.AfterFunction = true;
373 Expanded.BraceWrapping.AfterNamespace = true;
374 Expanded.BraceWrapping.BeforeElse = true;
375 break;
376 case FormatStyle::BS_Mozilla:
377 Expanded.BraceWrapping.AfterClass = true;
378 Expanded.BraceWrapping.AfterEnum = true;
379 Expanded.BraceWrapping.AfterFunction = true;
380 Expanded.BraceWrapping.AfterStruct = true;
381 Expanded.BraceWrapping.AfterUnion = true;
382 break;
383 case FormatStyle::BS_Stroustrup:
384 Expanded.BraceWrapping.AfterFunction = true;
385 Expanded.BraceWrapping.BeforeCatch = true;
386 Expanded.BraceWrapping.BeforeElse = true;
387 break;
388 case FormatStyle::BS_Allman:
389 Expanded.BraceWrapping.AfterClass = true;
390 Expanded.BraceWrapping.AfterControlStatement = true;
391 Expanded.BraceWrapping.AfterEnum = true;
392 Expanded.BraceWrapping.AfterFunction = true;
393 Expanded.BraceWrapping.AfterNamespace = true;
394 Expanded.BraceWrapping.AfterObjCDeclaration = true;
395 Expanded.BraceWrapping.AfterStruct = true;
396 Expanded.BraceWrapping.BeforeCatch = true;
397 Expanded.BraceWrapping.BeforeElse = true;
398 break;
399 case FormatStyle::BS_GNU:
400 Expanded.BraceWrapping = {true, true, true, true, true, true,
401 true, true, true, true, true};
402 break;
403 case FormatStyle::BS_WebKit:
404 Expanded.BraceWrapping.AfterFunction = true;
405 break;
406 default:
407 break;
408 }
409 return Expanded;
410}
411
Daniel Jasperf7935112012-12-03 18:12:45 +0000412FormatStyle getLLVMStyle() {
413 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000414 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000415 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000416 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000417 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000418 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000419 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000420 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000421 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000422 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000423 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000424 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000425 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000426 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000427 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000428 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000429 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000430 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000431 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000432 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000433 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000434 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000435 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
436 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000437 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000438 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000439 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000440 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000441 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000442 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000443 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000444 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000445 LLVMStyle.ForEachMacros.push_back("foreach");
446 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
447 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000448 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
449 {"^(<|\"(gtest|isl|json)/)", 3},
450 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000451 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000452 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000453 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000454 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000455 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000456 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000457 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000458 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000459 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000460 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000461 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000462 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000463 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000464 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000465 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000466 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000467 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000468 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000469 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000470 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000471 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000472 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000473 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000474
Daniel Jasper19a541e2013-12-19 16:45:34 +0000475 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000476 LLVMStyle.PenaltyBreakFirstLessLess = 120;
477 LLVMStyle.PenaltyBreakString = 1000;
478 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000479 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000480 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000481
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000482 LLVMStyle.DisableFormat = false;
483
Daniel Jasperf7935112012-12-03 18:12:45 +0000484 return LLVMStyle;
485}
486
Nico Weber514ecc82014-02-02 20:50:45 +0000487FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000488 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000489 GoogleStyle.Language = Language;
490
Daniel Jasperf7935112012-12-03 18:12:45 +0000491 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000492 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000493 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000494 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000495 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000496 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000497 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000498 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000499 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000500 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000501 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000502 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000503 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000504 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000505 GoogleStyle.SpacesBeforeTrailingComments = 2;
506 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000507
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000508 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000509 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000510
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000511 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000512 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000513 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000514 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000515 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000516 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000517 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000518 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
519 GoogleStyle.ColumnLimit = 100;
520 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000521 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000522 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000523 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000524 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000525 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000526 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000527 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000528 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000529 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000530 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000531 }
532
Daniel Jasperf7935112012-12-03 18:12:45 +0000533 return GoogleStyle;
534}
535
Nico Weber514ecc82014-02-02 20:50:45 +0000536FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
537 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000538 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000539 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000540 ChromiumStyle.IndentWidth = 4;
541 ChromiumStyle.ContinuationIndentWidth = 8;
542 } else {
543 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
544 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
545 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
546 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
547 ChromiumStyle.BinPackParameters = false;
548 ChromiumStyle.DerivePointerAlignment = false;
549 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000550 return ChromiumStyle;
551}
552
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000553FormatStyle getMozillaStyle() {
554 FormatStyle MozillaStyle = getLLVMStyle();
555 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000556 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000557 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
558 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000559 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000560 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000561 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
562 MozillaStyle.ConstructorInitializerIndentWidth = 2;
563 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000564 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000565 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000566 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000567 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
568 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000569 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000570 return MozillaStyle;
571}
572
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000573FormatStyle getWebKitStyle() {
574 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000575 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000576 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000577 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000578 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000579 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000580 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000581 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000582 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000583 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000584 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000585 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000586 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000587 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000588 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000589 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000590 return Style;
591}
592
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000593FormatStyle getGNUStyle() {
594 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000595 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000596 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000597 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000598 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000599 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000600 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000601 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000602 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000603 return Style;
604}
605
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000606FormatStyle getNoStyle() {
607 FormatStyle NoStyle = getLLVMStyle();
608 NoStyle.DisableFormat = true;
609 return NoStyle;
610}
611
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000612bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
613 FormatStyle *Style) {
614 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000615 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000616 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000617 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000618 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000619 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000620 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000621 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000622 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000623 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000624 } else if (Name.equals_lower("gnu")) {
625 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000626 } else if (Name.equals_lower("none")) {
627 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000628 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000629 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000630 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000631
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000632 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000633 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000634}
635
Rafael Espindolac0809172014-06-12 14:02:15 +0000636std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000637 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000638 FormatStyle::LanguageKind Language = Style->Language;
639 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000640 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000641 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000642
643 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000644 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000645 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
646 // values for the fields, keys for which are missing from the configuration.
647 // Mapping also uses the context to get the language to find the correct
648 // base style.
649 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000650 Input >> Styles;
651 if (Input.error())
652 return Input.error();
653
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000654 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000655 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000656 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000657 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000658 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000659 for (unsigned j = 0; j < i; ++j) {
660 if (Styles[i].Language == Styles[j].Language) {
661 DEBUG(llvm::dbgs()
662 << "Duplicate languages in the config file on positions " << j
663 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000664 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000665 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000666 }
667 }
668 // Look for a suitable configuration starting from the end, so we can
669 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000670 // configuration (which can only be at slot 0) after it.
671 for (int i = Styles.size() - 1; i >= 0; --i) {
672 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000673 Styles[i].Language == FormatStyle::LK_None) {
674 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000675 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000676 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000677 }
678 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000679 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000680}
681
682std::string configurationAsText(const FormatStyle &Style) {
683 std::string Text;
684 llvm::raw_string_ostream Stream(Text);
685 llvm::yaml::Output Output(Stream);
686 // We use the same mapping method for input and output, so we need a non-const
687 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000688 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000689 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000690 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000691}
692
Craig Topperaf35e852013-06-30 22:29:28 +0000693namespace {
694
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000695class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000696public:
Daniel Jasper23376252014-09-09 14:37:39 +0000697 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000698 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000699 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000700 LessStashed(false), Column(0), TrailingWhitespace(0),
701 SourceMgr(SourceMgr), ID(ID), Style(Style),
702 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000703 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
704 MacroBlockBeginRegex(Style.MacroBlockBegin),
705 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000706 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
707 getFormattingLangOpts(Style)));
708 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000709
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000710 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000711 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
712 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000713 }
714
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000715 ArrayRef<FormatToken *> lex() {
716 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000717 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000718 do {
719 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000720 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000721 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000722 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000723 } while (Tokens.back()->Tok.isNot(tok::eof));
724 return Tokens;
725 }
726
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000727 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000728
729private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000730 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000731 if (tryMerge_TMacro())
732 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000733 if (tryMergeConflictMarkers())
734 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000735 if (tryMergeLessLess())
736 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000737
738 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000739 if (tryMergeJSRegexLiteral())
740 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000741 if (tryMergeEscapeSequence())
742 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000743 if (tryMergeTemplateString())
744 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000745
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000746 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
747 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
748 tok::equal};
749 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
750 tok::greaterequal};
751 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000752 // FIXME: Investigate what token type gives the correct operator priority.
753 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000754 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000755 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000756 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000757 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000758 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000759 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000760 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000761 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000762 }
763
Jacques Pienaarfc275112015-02-18 23:48:37 +0000764 bool tryMergeLessLess() {
765 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000766 if (Tokens.size() < 3)
767 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000768
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000769 bool FourthTokenIsLess = false;
770 if (Tokens.size() > 3)
771 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000772
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000773 auto First = Tokens.end() - 3;
774 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
775 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000776 return false;
777
778 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000779 if (First[1]->WhitespaceRange.getBegin() !=
780 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000781 return false;
782
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000783 First[0]->Tok.setKind(tok::lessless);
784 First[0]->TokenText = "<<";
785 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000786 Tokens.erase(Tokens.end() - 2);
787 return true;
788 }
789
Manuel Klimek79e06082015-05-21 12:23:34 +0000790 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000791 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000792 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000793
794 SmallVectorImpl<FormatToken *>::const_iterator First =
795 Tokens.end() - Kinds.size();
796 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000797 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000798 unsigned AddLength = 0;
799 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000800 if (!First[i]->is(Kinds[i]) ||
801 First[i]->WhitespaceRange.getBegin() !=
802 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000803 return false;
804 AddLength += First[i]->TokenText.size();
805 }
806 Tokens.resize(Tokens.size() - Kinds.size() + 1);
807 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
808 First[0]->TokenText.size() + AddLength);
809 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000810 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000811 return true;
812 }
813
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000814 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000815 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000816 bool tryMergeEscapeSequence() {
817 if (Tokens.size() < 2)
818 return false;
819 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000820 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000821 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000822 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000823 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000824 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
825 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000826 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000827 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000828 return true;
829 }
830
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000831 // Try to determine whether the current token ends a JavaScript regex literal.
832 // We heuristically assume that this is a regex literal if we find two
833 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000834 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
835 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000836 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000837 if (Tokens.size() < 2)
838 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000839
840 // If this is a string literal with a slash inside, compute the slash's
841 // offset and try to find the beginning of the regex literal.
842 // Also look at tok::unknown, as it can be an unterminated char literal.
843 size_t SlashInStringPos = StringRef::npos;
844 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
845 tok::unknown)) {
846 // Start search from position 1 as otherwise, this is an unknown token
847 // for an unterminated /*-comment which is handled elsewhere.
848 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
849 if (SlashInStringPos == StringRef::npos)
850 return false;
851 }
852
Daniel Jasper23376252014-09-09 14:37:39 +0000853 // If a regex literal ends in "\//", this gets represented by an unknown
854 // token "\" and a comment.
855 bool MightEndWithEscapedSlash =
856 Tokens.back()->is(tok::comment) &&
857 Tokens.back()->TokenText.startswith("//") &&
858 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000859 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000860 (Tokens.back()->isNot(tok::slash) ||
861 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
862 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000863 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000864
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000865 unsigned TokenCount = 0;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000866 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
867 ++TokenCount;
Daniel Jasperf7372152015-07-02 14:14:04 +0000868 auto Prev = I + 1;
869 while (Prev != E && Prev[0]->is(tok::comment))
870 ++Prev;
Daniel Jasperc553ae12015-07-02 13:20:45 +0000871 if (I[0]->isOneOf(tok::slash, tok::slashequal) &&
Daniel Jasperf7372152015-07-02 14:14:04 +0000872 (Prev == E ||
873 ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
874 tok::r_brace, tok::exclaim, tok::l_square,
875 tok::colon, tok::comma, tok::question,
876 tok::kw_return) ||
877 Prev[0]->isBinaryOperator())))) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000878 unsigned LastColumn = Tokens.back()->OriginalColumn;
879 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000880 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000881 // This regex literal ends in '\//'. Skip past the '//' of the last
882 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000883 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000884 } else if (SlashInStringPos != StringRef::npos) {
885 // This regex literal ends in a string_literal with a slash inside.
886 // Calculate end column and reset lexer appropriately.
887 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
888 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000889 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000890 Tokens.resize(Tokens.size() - TokenCount);
891 Tokens.back()->Tok.setKind(tok::unknown);
892 Tokens.back()->Type = TT_RegexLiteral;
Daniel Jasperf1446202015-07-02 15:00:44 +0000893 // Treat regex literals like other string_literals.
894 Tokens.back()->Tok.setKind(tok::string_literal);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000895 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
896 return true;
897 }
898
899 // There can't be a newline inside a regex literal.
900 if (I[0]->NewlinesBefore > 0)
901 return false;
902 }
903 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000904 }
905
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000906 bool tryMergeTemplateString() {
907 if (Tokens.size() < 2)
908 return false;
909
910 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000911 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000912 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
913 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000914 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
915 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000916 return false;
917 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
918 // Unknown token that's not actually a backtick, or a comment that doesn't
919 // contain a backtick.
920 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000921 return false;
922
923 unsigned TokenCount = 0;
924 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000925 unsigned EndColumnInFirstLine =
926 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000927 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
928 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000929 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000930 IsMultiline = true;
931
932 // If there was a preceding template string, this must be the start of a
933 // template string, not the end.
934 if (I[0]->is(TT_TemplateString))
935 return false;
936
937 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
938 // Keep track of the rhs offset of the last token to wrap across lines -
939 // its the rhs offset of the first line of the template string, used to
940 // determine its width.
941 if (I[0]->IsMultiline)
942 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
943 // If the token has newlines, the token before it (if it exists) is the
944 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000945 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000946 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000947 IsMultiline = true;
948 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000949 continue;
950 }
951
952 Tokens.resize(Tokens.size() - TokenCount);
953 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000954 const char *EndOffset =
955 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
956 if (CommentBacktickPos != 0) {
957 // If the backtick was not the first character (e.g. in a comment),
958 // re-lex after the backtick position.
959 SourceLocation Loc = EndBacktick->Tok.getLocation();
960 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
961 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000962 Tokens.back()->TokenText =
963 StringRef(Tokens.back()->TokenText.data(),
964 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000965
966 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
967 if (EndOriginalColumn == 0) {
968 SourceLocation Loc = EndBacktick->Tok.getLocation();
969 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
970 }
971 // If the ` is further down within the token (e.g. in a comment).
972 EndOriginalColumn += CommentBacktickPos;
973
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000974 if (IsMultiline) {
975 // ColumnWidth is from backtick to last token in line.
976 // LastLineColumnWidth is 0 to backtick.
977 // x = `some content
978 // until here`;
979 Tokens.back()->ColumnWidth =
980 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000981 // +1 for the ` itself.
982 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000983 Tokens.back()->IsMultiline = true;
984 } else {
985 // Token simply spans from start to end, +1 for the ` itself.
986 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000987 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000988 }
989 return true;
990 }
991 return false;
992 }
993
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000994 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000995 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000996 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000997 FormatToken *Last = Tokens.back();
998 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000999 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001000
1001 FormatToken *String = Tokens[Tokens.size() - 2];
1002 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001003 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001004
1005 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001006 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001007
1008 FormatToken *Macro = Tokens[Tokens.size() - 4];
1009 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001010 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001011
1012 const char *Start = Macro->TokenText.data();
1013 const char *End = Last->TokenText.data() + Last->TokenText.size();
1014 String->TokenText = StringRef(Start, End - Start);
1015 String->IsFirst = Macro->IsFirst;
1016 String->LastNewlineOffset = Macro->LastNewlineOffset;
1017 String->WhitespaceRange = Macro->WhitespaceRange;
1018 String->OriginalColumn = Macro->OriginalColumn;
1019 String->ColumnWidth = encoding::columnWidthWithTabs(
1020 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001021 String->NewlinesBefore = Macro->NewlinesBefore;
1022 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001023
1024 Tokens.pop_back();
1025 Tokens.pop_back();
1026 Tokens.pop_back();
1027 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001028 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001029 }
1030
Manuel Klimek68b03042014-04-14 09:14:11 +00001031 bool tryMergeConflictMarkers() {
1032 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1033 return false;
1034
1035 // Conflict lines look like:
1036 // <marker> <text from the vcs>
1037 // For example:
1038 // >>>>>>> /file/in/file/system at revision 1234
1039 //
1040 // We merge all tokens in a line that starts with a conflict marker
1041 // into a single token with a special token type that the unwrapped line
1042 // parser will use to correctly rebuild the underlying code.
1043
1044 FileID ID;
1045 // Get the position of the first token in the line.
1046 unsigned FirstInLineOffset;
1047 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1048 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1049 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1050 // Calculate the offset of the start of the current line.
1051 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1052 if (LineOffset == StringRef::npos) {
1053 LineOffset = 0;
1054 } else {
1055 ++LineOffset;
1056 }
1057
1058 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1059 StringRef LineStart;
1060 if (FirstSpace == StringRef::npos) {
1061 LineStart = Buffer.substr(LineOffset);
1062 } else {
1063 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1064 }
1065
1066 TokenType Type = TT_Unknown;
1067 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1068 Type = TT_ConflictStart;
1069 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1070 LineStart == "====") {
1071 Type = TT_ConflictAlternative;
1072 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1073 Type = TT_ConflictEnd;
1074 }
1075
1076 if (Type != TT_Unknown) {
1077 FormatToken *Next = Tokens.back();
1078
1079 Tokens.resize(FirstInLineIndex + 1);
1080 // We do not need to build a complete token here, as we will skip it
1081 // during parsing anyway (as we must not touch whitespace around conflict
1082 // markers).
1083 Tokens.back()->Type = Type;
1084 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1085
1086 Tokens.push_back(Next);
1087 return true;
1088 }
1089
1090 return false;
1091 }
1092
Jacques Pienaarfc275112015-02-18 23:48:37 +00001093 FormatToken *getStashedToken() {
1094 // Create a synthesized second '>' or '<' token.
1095 Token Tok = FormatTok->Tok;
1096 StringRef TokenText = FormatTok->TokenText;
1097
1098 unsigned OriginalColumn = FormatTok->OriginalColumn;
1099 FormatTok = new (Allocator.Allocate()) FormatToken;
1100 FormatTok->Tok = Tok;
1101 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001102 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1103 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001104 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1105 FormatTok->TokenText = TokenText;
1106 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001107 FormatTok->OriginalColumn = OriginalColumn + 1;
1108
Jacques Pienaarfc275112015-02-18 23:48:37 +00001109 return FormatTok;
1110 }
1111
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001112 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001113 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001114 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001115 return getStashedToken();
1116 }
1117 if (LessStashed) {
1118 LessStashed = false;
1119 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001120 }
1121
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001122 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001123 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001124 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001125 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001126 FormatTok->IsFirst = IsFirstToken;
1127 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001128
1129 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001130 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001131 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001132 StringRef Text = FormatTok->TokenText;
1133 auto EscapesNewline = [&](int pos) {
1134 // A '\r' here is just part of '\r\n'. Skip it.
1135 if (pos >= 0 && Text[pos] == '\r')
1136 --pos;
1137 // See whether there is an odd number of '\' before this.
1138 unsigned count = 0;
1139 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001140 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001141 break;
1142 return count & 1;
1143 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001144 // FIXME: This miscounts tok:unknown tokens that are not just
1145 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001146 for (int i = 0, e = Text.size(); i != e; ++i) {
1147 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001148 case '\n':
1149 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001150 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001151 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1152 Column = 0;
1153 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001154 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001155 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1156 Column = 0;
1157 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001158 case '\f':
1159 case '\v':
1160 Column = 0;
1161 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001162 case ' ':
1163 ++Column;
1164 break;
1165 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001166 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001167 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001168 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001169 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001170 FormatTok->Type = TT_ImplicitStringLiteral;
1171 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001172 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001173 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001174 break;
1175 }
1176 }
1177
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001178 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001179 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001180 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001181
Daniel Jasper8369aa52013-07-16 20:28:33 +00001182 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001183 }
Manuel Klimekef920692013-01-07 07:56:50 +00001184
Manuel Klimek1abf7892013-01-04 23:34:14 +00001185 // In case the token starts with escaped newlines, we want to
1186 // take them into account as whitespace - this pattern is quite frequent
1187 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001188 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001189 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1190 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001191 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001192 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001193 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001194 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001195 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001196 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001197
1198 FormatTok->WhitespaceRange = SourceRange(
1199 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1200
Manuel Klimek31c85922013-08-29 15:21:40 +00001201 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001202
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001203 TrailingWhitespace = 0;
1204 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001205 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001206 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001207 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001208 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001209 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001210 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001211 FormatTok->Tok.setIdentifierInfo(&Info);
1212 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001213 if (Style.Language == FormatStyle::LK_Java &&
1214 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1215 FormatTok->Tok.setKind(tok::identifier);
1216 FormatTok->Tok.setIdentifierInfo(nullptr);
1217 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001218 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001219 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001220 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001221 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001222 } else if (FormatTok->Tok.is(tok::lessless)) {
1223 FormatTok->Tok.setKind(tok::less);
1224 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1225 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001226 }
1227
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001228 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001229
Alexander Kornienko39856b72013-09-10 09:38:25 +00001230 StringRef Text = FormatTok->TokenText;
1231 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001232 if (FirstNewlinePos == StringRef::npos) {
1233 // FIXME: ColumnWidth actually depends on the start column, we need to
1234 // take this into account when the token is moved.
1235 FormatTok->ColumnWidth =
1236 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1237 Column += FormatTok->ColumnWidth;
1238 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001239 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001240 // FIXME: ColumnWidth actually depends on the start column, we need to
1241 // take this into account when the token is moved.
1242 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1243 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1244
Alexander Kornienko39856b72013-09-10 09:38:25 +00001245 // The last line of the token always starts in column 0.
1246 // Thus, the length can be precomputed even in the presence of tabs.
1247 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1248 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1249 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001250 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001251 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001252
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001253 if (Style.Language == FormatStyle::LK_Cpp) {
1254 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1255 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1256 tok::pp_define) &&
1257 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1258 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1259 FormatTok->Type = TT_ForEachMacro;
1260 } else if (FormatTok->is(tok::identifier)) {
1261 if (MacroBlockBeginRegex.match(Text)) {
1262 FormatTok->Type = TT_MacroBlockBegin;
1263 } else if (MacroBlockEndRegex.match(Text)) {
1264 FormatTok->Type = TT_MacroBlockEnd;
1265 }
1266 }
1267 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001268
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001269 return FormatTok;
1270 }
1271
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001272 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001273 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001274 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001275 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001276 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001277 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001278 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001279 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001280 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001282 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001283 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001284 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001285 // Index (in 'Tokens') of the last token that starts a new line.
1286 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001287 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001288 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001289
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001290 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001291
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001292 llvm::Regex MacroBlockBeginRegex;
1293 llvm::Regex MacroBlockEndRegex;
1294
Daniel Jasper8369aa52013-07-16 20:28:33 +00001295 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001296 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001297 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1298 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001299 // For formatting, treat unterminated string literals like normal string
1300 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001301 if (Tok.is(tok::unknown)) {
1302 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1303 Tok.Tok.setKind(tok::string_literal);
1304 Tok.IsUnterminatedLiteral = true;
1305 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1306 Tok.TokenText == "''") {
1307 Tok.Tok.setKind(tok::char_constant);
1308 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001309 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001310
1311 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1312 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001313 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001314 }
1315
Daniel Jasper471894432014-08-06 13:40:26 +00001316 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001317
1318 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1319 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001320 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001321 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001322 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001323
1324 void resetLexer(unsigned Offset) {
1325 StringRef Buffer = SourceMgr.getBufferData(ID);
1326 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1327 getFormattingLangOpts(Style), Buffer.begin(),
1328 Buffer.begin() + Offset, Buffer.end()));
1329 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001330 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001331 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001332};
1333
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001334static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1335 switch (Language) {
1336 case FormatStyle::LK_Cpp:
1337 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001338 case FormatStyle::LK_Java:
1339 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001340 case FormatStyle::LK_JavaScript:
1341 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001342 case FormatStyle::LK_Proto:
1343 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001344 default:
1345 return "Unknown";
1346 }
1347}
1348
Daniel Jasperf7935112012-12-03 18:12:45 +00001349class Formatter : public UnwrappedLineConsumer {
1350public:
Daniel Jasper23376252014-09-09 14:37:39 +00001351 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001352 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001353 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1354 Whitespaces(SourceMgr, Style,
1355 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001356 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001357 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001358 DEBUG(llvm::dbgs() << "File encoding: "
1359 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1360 : "unknown")
1361 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001362 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1363 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001364 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001365
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001366 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001367 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001368 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001369
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001370 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1371 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001372 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001373 assert(UnwrappedLines.rbegin()->empty());
1374 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1375 ++Run) {
1376 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1377 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1378 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1379 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1380 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001381 tooling::Replacements RunResult =
1382 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001383 DEBUG({
1384 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1385 for (tooling::Replacements::iterator I = RunResult.begin(),
1386 E = RunResult.end();
1387 I != E; ++I) {
1388 llvm::dbgs() << I->toString() << "\n";
1389 }
1390 });
1391 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1392 delete AnnotatedLines[i];
1393 }
1394 Result.insert(RunResult.begin(), RunResult.end());
1395 Whitespaces.reset();
1396 }
1397 return Result;
1398 }
1399
1400 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001401 FormatTokenLexer &Tokens,
1402 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001403 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001404 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001405 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001406 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001407 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001408 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001409 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001410 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001411 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001412
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001413 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001414 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1415 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001416 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001417 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1418 IncompleteFormat)
1419 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001420 return Whitespaces.generateReplacements();
1421 }
1422
1423private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001424 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001425 // Returns \c true if at least one line between I and E or one of their
1426 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001427 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1428 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1429 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001430 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001431 while (I != E) {
1432 AnnotatedLine *Line = *I;
1433 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1434
1435 // If a line is part of a preprocessor directive, it needs to be formatted
1436 // if any token within the directive is affected.
1437 if (Line->InPPDirective) {
1438 FormatToken *Last = Line->Last;
1439 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1440 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1441 Last = (*PPEnd)->Last;
1442 ++PPEnd;
1443 }
1444
1445 if (affectsTokenRange(*Line->First, *Last,
1446 /*IncludeLeadingNewlines=*/false)) {
1447 SomeLineAffected = true;
1448 markAllAsAffected(I, PPEnd);
1449 }
1450 I = PPEnd;
1451 continue;
1452 }
1453
Daniel Jasper38c82402013-11-29 09:27:43 +00001454 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001455 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001456
Daniel Jasper38c82402013-11-29 09:27:43 +00001457 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001458 ++I;
1459 }
1460 return SomeLineAffected;
1461 }
1462
Daniel Jasper9c199562013-11-28 15:58:55 +00001463 // Determines whether 'Line' is affected by the SourceRanges given as input.
1464 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001465 bool nonPPLineAffected(AnnotatedLine *Line,
1466 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001467 bool SomeLineAffected = false;
1468 Line->ChildrenAffected =
1469 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1470 if (Line->ChildrenAffected)
1471 SomeLineAffected = true;
1472
1473 // Stores whether one of the line's tokens is directly affected.
1474 bool SomeTokenAffected = false;
1475 // Stores whether we need to look at the leading newlines of the next token
1476 // in order to determine whether it was affected.
1477 bool IncludeLeadingNewlines = false;
1478
1479 // Stores whether the first child line of any of this line's tokens is
1480 // affected.
1481 bool SomeFirstChildAffected = false;
1482
1483 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1484 // Determine whether 'Tok' was affected.
1485 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1486 SomeTokenAffected = true;
1487
1488 // Determine whether the first child of 'Tok' was affected.
1489 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1490 SomeFirstChildAffected = true;
1491
1492 IncludeLeadingNewlines = Tok->Children.empty();
1493 }
1494
1495 // Was this line moved, i.e. has it previously been on the same line as an
1496 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001497 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1498 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001499
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001500 bool IsContinuedComment =
1501 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1502 Line->First->NewlinesBefore < 2 && PreviousLine &&
1503 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001504
1505 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1506 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001507 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001508 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001509 }
1510 return SomeLineAffected;
1511 }
1512
Daniel Jasper5500f612013-11-25 11:08:59 +00001513 // Marks all lines between I and E as well as all their children as affected.
1514 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1515 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1516 while (I != E) {
1517 (*I)->Affected = true;
1518 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1519 ++I;
1520 }
1521 }
1522
1523 // Returns true if the range from 'First' to 'Last' intersects with one of the
1524 // input ranges.
1525 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1526 bool IncludeLeadingNewlines) {
1527 SourceLocation Start = First.WhitespaceRange.getBegin();
1528 if (!IncludeLeadingNewlines)
1529 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001530 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001531 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001532 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1533 return affectsCharSourceRange(Range);
1534 }
1535
1536 // Returns true if one of the input ranges intersect the leading empty lines
1537 // before 'Tok'.
1538 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1539 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1540 Tok.WhitespaceRange.getBegin(),
1541 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1542 return affectsCharSourceRange(EmptyLineRange);
1543 }
1544
1545 // Returns true if 'Range' intersects with one of the input ranges.
1546 bool affectsCharSourceRange(const CharSourceRange &Range) {
1547 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1548 E = Ranges.end();
1549 I != E; ++I) {
1550 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1551 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1552 return true;
1553 }
1554 return false;
1555 }
1556
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001557 static bool inputUsesCRLF(StringRef Text) {
1558 return Text.count('\r') * 2 > Text.count('\n');
1559 }
1560
Daniel Jasper352f0df2015-07-18 16:35:30 +00001561 bool
1562 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1563 for (const AnnotatedLine* Line : Lines) {
1564 if (hasCpp03IncompatibleFormat(Line->Children))
1565 return true;
1566 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1567 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1568 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1569 return true;
1570 if (Tok->is(TT_TemplateCloser) &&
1571 Tok->Previous->is(TT_TemplateCloser))
1572 return true;
1573 }
1574 }
1575 }
1576 return false;
1577 }
1578
1579 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1580 int AlignmentDiff = 0;
1581 for (const AnnotatedLine* Line : Lines) {
1582 AlignmentDiff += countVariableAlignments(Line->Children);
1583 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1584 if (!Tok->is(TT_PointerOrReference))
1585 continue;
1586 bool SpaceBefore =
1587 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1588 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1589 Tok->Next->WhitespaceRange.getEnd();
1590 if (SpaceBefore && !SpaceAfter)
1591 ++AlignmentDiff;
1592 if (!SpaceBefore && SpaceAfter)
1593 --AlignmentDiff;
1594 }
1595 }
1596 return AlignmentDiff;
1597 }
1598
Manuel Klimek71814b42013-10-11 21:25:45 +00001599 void
1600 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001601 bool HasBinPackedFunction = false;
1602 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001603 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001604 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001605 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001606 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001607 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001608 if (Tok->PackingKind == PPK_BinPacked)
1609 HasBinPackedFunction = true;
1610 if (Tok->PackingKind == PPK_OnePerLine)
1611 HasOnePerLineFunction = true;
1612
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001613 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001614 }
1615 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001616 if (Style.DerivePointerAlignment)
1617 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1618 ? FormatStyle::PAS_Left
1619 : FormatStyle::PAS_Right;
1620 if (Style.Standard == FormatStyle::LS_Auto)
1621 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1622 ? FormatStyle::LS_Cpp11
1623 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001624 BinPackInconclusiveFunctions =
1625 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001626 }
1627
Craig Topperfb6b25b2014-03-15 04:29:04 +00001628 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001629 assert(!UnwrappedLines.empty());
1630 UnwrappedLines.back().push_back(TheLine);
1631 }
1632
Craig Topperfb6b25b2014-03-15 04:29:04 +00001633 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001634 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001635 }
1636
1637 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001638 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001639 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001640 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001641 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001642 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001643
1644 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001645 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001646};
1647
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001648struct IncludeDirective {
1649 StringRef Filename;
1650 StringRef Text;
1651 unsigned Offset;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001652 unsigned Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001653};
1654
Craig Topperaf35e852013-06-30 22:29:28 +00001655} // end anonymous namespace
1656
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001657// Determines whether 'Ranges' intersects with ('Start', 'End').
1658static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1659 unsigned End) {
1660 for (auto Range : Ranges) {
1661 if (Range.getOffset() < End &&
1662 Range.getOffset() + Range.getLength() > Start)
1663 return true;
1664 }
1665 return false;
1666}
1667
1668// Sorts a block of includes given by 'Includes' alphabetically adding the
1669// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1670// order.
1671static void sortIncludes(const FormatStyle &Style,
1672 const SmallVectorImpl<IncludeDirective> &Includes,
1673 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1674 tooling::Replacements &Replaces) {
1675 if (!affectsRange(Ranges, Includes.front().Offset,
1676 Includes.back().Offset + Includes.back().Text.size()))
1677 return;
1678 SmallVector<unsigned, 16> Indices;
1679 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1680 Indices.push_back(i);
1681 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001682 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1683 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001684 });
1685
1686 // If the #includes are out of order, we generate a single replacement fixing
1687 // the entire block. Otherwise, no replacement is generated.
1688 bool OutOfOrder = false;
1689 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1690 if (Indices[i] != i) {
1691 OutOfOrder = true;
1692 break;
1693 }
1694 }
1695 if (!OutOfOrder)
1696 return;
1697
1698 std::string result = Includes[Indices[0]].Text;
1699 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1700 result += "\n";
1701 result += Includes[Indices[i]].Text;
1702 }
1703
1704 // Sorting #includes shouldn't change their total number of characters.
1705 // This would otherwise mess up 'Ranges'.
1706 assert(result.size() ==
1707 Includes.back().Offset + Includes.back().Text.size() -
1708 Includes.front().Offset);
1709
1710 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1711 result.size(), result));
1712}
1713
1714tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1715 ArrayRef<tooling::Range> Ranges,
1716 StringRef FileName) {
1717 tooling::Replacements Replaces;
1718 unsigned Prev = 0;
1719 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001720 llvm::Regex IncludeRegex(
1721 R"(^[\t\ ]*#[\t\ ]*include[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001722 SmallVector<StringRef, 4> Matches;
1723 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001724
1725 // In compiled files, consider the first #include to be the main #include of
1726 // the file if it is not a system #include. This ensures that the header
1727 // doesn't have hidden dependencies
1728 // (http://llvm.org/docs/CodingStandards.html#include-style).
1729 //
1730 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1731 // cases where the first #include is unlikely to be the main header.
1732 bool LookForMainHeader = FileName.endswith(".c") ||
1733 FileName.endswith(".cc") ||
1734 FileName.endswith(".cpp")||
1735 FileName.endswith(".c++")||
1736 FileName.endswith(".cxx");
1737
1738 // Create pre-compiled regular expressions for the #include categories.
1739 SmallVector<llvm::Regex, 4> CategoryRegexs;
1740 for (const auto &IncludeBlock : Style.IncludeCategories)
1741 CategoryRegexs.emplace_back(IncludeBlock.first);
1742
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001743 for (;;) {
1744 auto Pos = Code.find('\n', SearchFrom);
1745 StringRef Line =
1746 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1747 if (!Line.endswith("\\")) {
1748 if (IncludeRegex.match(Line, &Matches)) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001749 unsigned Category;
1750 if (LookForMainHeader && !Matches[1].startswith("<")) {
1751 Category = 0;
1752 } else {
1753 Category = UINT_MAX;
1754 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1755 if (CategoryRegexs[i].match(Matches[1])) {
1756 Category = Style.IncludeCategories[i].second;
1757 break;
1758 }
1759 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001760 }
Daniel Jasper85c472d2015-09-29 07:53:08 +00001761 LookForMainHeader = false;
1762 IncludesInBlock.push_back({Matches[1], Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001763 } else if (!IncludesInBlock.empty()) {
1764 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1765 IncludesInBlock.clear();
1766 }
1767 Prev = Pos + 1;
1768 }
1769 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1770 break;
1771 SearchFrom = Pos + 1;
1772 }
1773 if (!IncludesInBlock.empty())
1774 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1775 return Replaces;
1776}
1777
Daniel Jasper23376252014-09-09 14:37:39 +00001778tooling::Replacements reformat(const FormatStyle &Style,
1779 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001780 ArrayRef<CharSourceRange> Ranges,
1781 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001782 FormatStyle Expanded = expandPresets(Style);
1783 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001784 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001785 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001786 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001787}
1788
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001789tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001790 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001791 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001792 if (Style.DisableFormat)
1793 return tooling::Replacements();
1794
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001795 FileManager Files((FileSystemOptions()));
1796 DiagnosticsEngine Diagnostics(
1797 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1798 new DiagnosticOptions);
1799 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001800 std::unique_ptr<llvm::MemoryBuffer> Buf =
1801 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001802 const clang::FileEntry *Entry =
1803 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001804 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001805 FileID ID =
1806 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001807 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1808 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001809 for (const tooling::Range &Range : Ranges) {
1810 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1811 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001812 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1813 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001814 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001815}
1816
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001817LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001818 LangOptions LangOpts;
1819 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001820 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1821 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001822 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001823 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001824 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001825 LangOpts.Bool = 1;
1826 LangOpts.ObjC1 = 1;
1827 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001828 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001829 return LangOpts;
1830}
1831
Edwin Vaned544aa72013-09-30 13:31:48 +00001832const char *StyleOptionHelpDescription =
1833 "Coding style, currently supports:\n"
1834 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1835 "Use -style=file to load style configuration from\n"
1836 ".clang-format file located in one of the parent\n"
1837 "directories of the source file (or current\n"
1838 "directory for stdin).\n"
1839 "Use -style=\"{key: value, ...}\" to set specific\n"
1840 "parameters, e.g.:\n"
1841 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1842
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001843static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001844 if (FileName.endswith(".java")) {
1845 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001846 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1847 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001848 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001849 } else if (FileName.endswith_lower(".proto") ||
1850 FileName.endswith_lower(".protodevel")) {
1851 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001852 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001853 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001854}
1855
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001856FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1857 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001858 FormatStyle Style = getLLVMStyle();
1859 Style.Language = getLanguageByFileName(FileName);
1860 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001861 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1862 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001863 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001864 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001865
1866 if (StyleName.startswith("{")) {
1867 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001868 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001869 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1870 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001871 }
1872 return Style;
1873 }
1874
1875 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001876 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001877 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1878 << " style\n";
1879 return Style;
1880 }
1881
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001882 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001883 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001884 SmallString<128> Path(FileName);
1885 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001886 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001887 Directory = llvm::sys::path::parent_path(Directory)) {
1888 if (!llvm::sys::fs::is_directory(Directory))
1889 continue;
1890 SmallString<128> ConfigFile(Directory);
1891
1892 llvm::sys::path::append(ConfigFile, ".clang-format");
1893 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1894 bool IsFile = false;
1895 // Ignore errors from is_regular_file: we only need to know if we can read
1896 // the file or not.
1897 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1898
1899 if (!IsFile) {
1900 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1901 ConfigFile = Directory;
1902 llvm::sys::path::append(ConfigFile, "_clang-format");
1903 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1904 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1905 }
1906
1907 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001908 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1909 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1910 if (std::error_code EC = Text.getError()) {
1911 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001912 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001913 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001914 if (std::error_code ec =
1915 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001916 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001917 if (!UnsuitableConfigFiles.empty())
1918 UnsuitableConfigFiles.append(", ");
1919 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001920 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001921 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001922 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1923 << "\n";
1924 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001925 }
1926 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1927 return Style;
1928 }
1929 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001930 if (!UnsuitableConfigFiles.empty()) {
1931 llvm::errs() << "Configuration file(s) do(es) not support "
1932 << getLanguageName(Style.Language) << ": "
1933 << UnsuitableConfigFiles << "\n";
1934 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001935 return Style;
1936}
1937
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001938} // namespace format
1939} // namespace clang