blob: 674af7ac5312dfd9d3c4e1e1e9184e4486fa05d8 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasper85c472d2015-09-29 07:53:08 +000016#include "clang/Format/Format.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000017#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000019#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000030#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Chandler Carruth10346662014-04-22 03:17:02 +000035#define DEBUG_TYPE "format-formatter"
36
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000037using clang::format::FormatStyle;
38
Daniel Jaspere1e43192014-04-01 12:55:11 +000039LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +000040LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
Daniel Jaspere1e43192014-04-01 12:55:11 +000041
Alexander Kornienkod6538332013-05-07 15:32:14 +000042namespace llvm {
43namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000044template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
45 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
46 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000047 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000048 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000049 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000050 }
51};
52
53template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
54 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
55 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
56 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
57 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
58 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
59 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
60 }
61};
62
63template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
64 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
65 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
66 IO.enumCase(Value, "false", FormatStyle::UT_Never);
67 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
68 IO.enumCase(Value, "true", FormatStyle::UT_Always);
69 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
70 }
71};
72
Daniel Jasperd74cf402014-04-08 12:46:38 +000073template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
74 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
75 IO.enumCase(Value, "None", FormatStyle::SFS_None);
76 IO.enumCase(Value, "false", FormatStyle::SFS_None);
77 IO.enumCase(Value, "All", FormatStyle::SFS_All);
78 IO.enumCase(Value, "true", FormatStyle::SFS_All);
79 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000080 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000081 }
82};
83
Daniel Jasperac043c92014-09-15 11:11:00 +000084template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
85 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
86 IO.enumCase(Value, "All", FormatStyle::BOS_All);
87 IO.enumCase(Value, "true", FormatStyle::BOS_All);
88 IO.enumCase(Value, "None", FormatStyle::BOS_None);
89 IO.enumCase(Value, "false", FormatStyle::BOS_None);
90 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
91 }
92};
93
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000094template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
95 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
96 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
97 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000098 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
100 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000101 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000102 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000103 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 }
105};
106
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000107template <>
108struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
109 static void
110 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000111 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
112 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
113 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
114
115 // For backward compatibility.
116 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
117 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
118 }
119};
120
Alexander Kornienkod6538332013-05-07 15:32:14 +0000121template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000122struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000123 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000124 FormatStyle::NamespaceIndentationKind &Value) {
125 IO.enumCase(Value, "None", FormatStyle::NI_None);
126 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
127 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000128 }
129};
130
Jacques Pienaarfc275112015-02-18 23:48:37 +0000131template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
132 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000133 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
134 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
135 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
136
Alp Toker958027b2014-07-14 19:42:55 +0000137 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000138 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
139 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
140 }
141};
142
143template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000144struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000145 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000146 FormatStyle::SpaceBeforeParensOptions &Value) {
147 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000148 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000149 FormatStyle::SBPO_ControlStatements);
150 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000151
152 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000153 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
154 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000155 }
156};
157
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000158template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000159 static void mapping(IO &IO, FormatStyle &Style) {
160 // When reading, read the language first, we need it for getPredefinedStyle.
161 IO.mapOptional("Language", Style.Language);
162
Alexander Kornienko49149672013-05-10 11:56:10 +0000163 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000164 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
165 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000166 ArrayRef<StringRef> Styles(StylesArray);
167 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
168 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000169 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000170 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000171 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000172 IO.mapOptional("# BasedOnStyle", StyleName);
173 break;
174 }
175 }
176 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177 StringRef BasedOnStyle;
178 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000179 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000180 FormatStyle::LanguageKind OldLanguage = Style.Language;
181 FormatStyle::LanguageKind Language =
182 ((FormatStyle *)IO.getContext())->Language;
183 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000184 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
185 return;
186 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000187 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000188 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000189 }
190
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000191 // For backward compatibility.
192 if (!IO.outputting()) {
193 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
194 IO.mapOptional("IndentFunctionDeclarationAfterType",
195 Style.IndentWrappedFunctionNames);
196 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
197 IO.mapOptional("SpaceAfterControlStatementKeyword",
198 Style.SpaceBeforeParens);
199 }
200
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000202 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000203 IO.mapOptional("AlignConsecutiveAssignments",
204 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000205 IO.mapOptional("AlignConsecutiveDeclarations",
206 Style.AlignConsecutiveDeclarations);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000207 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000208 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000209 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000210 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
211 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000212 IO.mapOptional("AllowShortBlocksOnASingleLine",
213 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000214 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
215 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000216 IO.mapOptional("AllowShortFunctionsOnASingleLine",
217 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000218 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
219 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000220 IO.mapOptional("AllowShortLoopsOnASingleLine",
221 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000222 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
223 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000224 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
225 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000226 IO.mapOptional("AlwaysBreakTemplateDeclarations",
227 Style.AlwaysBreakTemplateDeclarations);
228 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
229 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000230 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000231 IO.mapOptional("BreakBeforeBinaryOperators",
232 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000233 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000234 IO.mapOptional("BreakBeforeTernaryOperators",
235 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000236 IO.mapOptional("BreakConstructorInitializersBeforeComma",
237 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000238 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000239 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000240 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
241 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000242 IO.mapOptional("ConstructorInitializerIndentWidth",
243 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000244 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
245 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000246 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000247 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000248 IO.mapOptional("ExperimentalAutoDetectBinPacking",
249 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000250 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000251 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000252 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000253 IO.mapOptional("IndentWidth", Style.IndentWidth);
254 IO.mapOptional("IndentWrappedFunctionNames",
255 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000256 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
257 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000258 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
259 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000260 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000261 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000262 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000263 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000264 IO.mapOptional("ObjCSpaceBeforeProtocolList",
265 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000266 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
267 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000268 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000269 IO.mapOptional("PenaltyBreakFirstLessLess",
270 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000271 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000272 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
273 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
274 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000275 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000276 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000277 IO.mapOptional("SpaceBeforeAssignmentOperators",
278 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000279 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
280 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
281 IO.mapOptional("SpacesBeforeTrailingComments",
282 Style.SpacesBeforeTrailingComments);
283 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
284 IO.mapOptional("SpacesInContainerLiterals",
285 Style.SpacesInContainerLiterals);
286 IO.mapOptional("SpacesInCStyleCastParentheses",
287 Style.SpacesInCStyleCastParentheses);
288 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
289 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
290 IO.mapOptional("Standard", Style.Standard);
291 IO.mapOptional("TabWidth", Style.TabWidth);
292 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000293 }
294};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000295
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000296template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
297 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
298 IO.mapOptional("AfterClass", Wrapping.AfterClass);
299 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
300 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
301 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
302 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
303 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
304 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
305 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
306 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
307 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
308 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
309 }
310};
311
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000312template <> struct MappingTraits<FormatStyle::IncludeCategory> {
313 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
314 IO.mapOptional("Regex", Category.Regex);
315 IO.mapOptional("Priority", Category.Priority);
316 }
317};
318
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000319// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000320// IO.getContext() should contain a pointer to the FormatStyle structure, that
321// will be used to get default values for missing keys.
322// If the first element has no Language specified, it will be treated as the
323// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000324template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000325 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
326 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000327 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000328 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000329 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000330 if (Index >= Seq.size()) {
331 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000332 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000333 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000334 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000335 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000336 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000337 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000338 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000339 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000340 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000341 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000342 }
343};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000344} // namespace yaml
345} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000346
Daniel Jasperf7935112012-12-03 18:12:45 +0000347namespace clang {
348namespace format {
349
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000350const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000351 static ParseErrorCategory C;
352 return C;
353}
354std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000355 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000356}
357
358const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
359 return "clang-format.parse_error";
360}
361
362std::string ParseErrorCategory::message(int EV) const {
363 switch (static_cast<ParseError>(EV)) {
364 case ParseError::Success:
365 return "Success";
366 case ParseError::Error:
367 return "Invalid argument";
368 case ParseError::Unsuitable:
369 return "Unsuitable";
370 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000371 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000372}
373
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000374static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000375 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
376 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000377 FormatStyle Expanded = Style;
378 Expanded.BraceWrapping = {false, false, false, false, false, false,
379 false, false, false, false, false};
380 switch (Style.BreakBeforeBraces) {
381 case FormatStyle::BS_Linux:
382 Expanded.BraceWrapping.AfterClass = true;
383 Expanded.BraceWrapping.AfterFunction = true;
384 Expanded.BraceWrapping.AfterNamespace = true;
385 Expanded.BraceWrapping.BeforeElse = true;
386 break;
387 case FormatStyle::BS_Mozilla:
388 Expanded.BraceWrapping.AfterClass = true;
389 Expanded.BraceWrapping.AfterEnum = true;
390 Expanded.BraceWrapping.AfterFunction = true;
391 Expanded.BraceWrapping.AfterStruct = true;
392 Expanded.BraceWrapping.AfterUnion = true;
393 break;
394 case FormatStyle::BS_Stroustrup:
395 Expanded.BraceWrapping.AfterFunction = true;
396 Expanded.BraceWrapping.BeforeCatch = true;
397 Expanded.BraceWrapping.BeforeElse = true;
398 break;
399 case FormatStyle::BS_Allman:
400 Expanded.BraceWrapping.AfterClass = true;
401 Expanded.BraceWrapping.AfterControlStatement = true;
402 Expanded.BraceWrapping.AfterEnum = true;
403 Expanded.BraceWrapping.AfterFunction = true;
404 Expanded.BraceWrapping.AfterNamespace = true;
405 Expanded.BraceWrapping.AfterObjCDeclaration = true;
406 Expanded.BraceWrapping.AfterStruct = true;
407 Expanded.BraceWrapping.BeforeCatch = true;
408 Expanded.BraceWrapping.BeforeElse = true;
409 break;
410 case FormatStyle::BS_GNU:
411 Expanded.BraceWrapping = {true, true, true, true, true, true,
412 true, true, true, true, true};
413 break;
414 case FormatStyle::BS_WebKit:
415 Expanded.BraceWrapping.AfterFunction = true;
416 break;
417 default:
418 break;
419 }
420 return Expanded;
421}
422
Daniel Jasperf7935112012-12-03 18:12:45 +0000423FormatStyle getLLVMStyle() {
424 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000425 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000427 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000428 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000429 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000430 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000431 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000432 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000433 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000434 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000435 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000436 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000437 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000438 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000439 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000440 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000441 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000442 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000443 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000444 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000445 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000446 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasper55bbe662015-10-07 04:06:10 +0000447 LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
448 false, false, false, false, false};
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000449 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Nico Weber2cd92f12015-10-15 16:03:01 +0000450 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000451 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000452 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000453 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000454 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000455 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000456 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000457 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000458 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000459 LLVMStyle.ForEachMacros.push_back("foreach");
460 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
461 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000462 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
463 {"^(<|\"(gtest|isl|json)/)", 3},
464 {".*", 1}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000465 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000466 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000467 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000468 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000469 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000470 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000471 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000472 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000473 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000474 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000475 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000476 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000477 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000478 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000479 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000480 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000481 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000482 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000483 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000484 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000485 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000486 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000487 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000488
Daniel Jasper19a541e2013-12-19 16:45:34 +0000489 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000490 LLVMStyle.PenaltyBreakFirstLessLess = 120;
491 LLVMStyle.PenaltyBreakString = 1000;
492 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000493 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000494 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000495
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000496 LLVMStyle.DisableFormat = false;
497
Daniel Jasperf7935112012-12-03 18:12:45 +0000498 return LLVMStyle;
499}
500
Nico Weber514ecc82014-02-02 20:50:45 +0000501FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000502 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000503 GoogleStyle.Language = Language;
504
Daniel Jasperf7935112012-12-03 18:12:45 +0000505 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000506 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000507 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000508 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000509 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000510 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000511 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000512 GoogleStyle.DerivePointerAlignment = true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000513 GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000514 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000515 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000516 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000517 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000518 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000519 GoogleStyle.SpacesBeforeTrailingComments = 2;
520 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000521
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000522 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000523 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000524
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000525 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000526 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000527 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000528 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000529 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000530 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000531 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000532 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
533 GoogleStyle.ColumnLimit = 100;
534 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000535 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000536 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000537 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000538 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000539 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000540 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000541 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000542 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000543 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000544 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000545 }
546
Daniel Jasperf7935112012-12-03 18:12:45 +0000547 return GoogleStyle;
548}
549
Nico Weber514ecc82014-02-02 20:50:45 +0000550FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
551 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000552 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000553 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000554 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000555 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000556 ChromiumStyle.IndentWidth = 4;
Nico Weber450425c2014-11-26 16:43:18 +0000557 } else {
558 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
559 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
560 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
561 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
562 ChromiumStyle.BinPackParameters = false;
563 ChromiumStyle.DerivePointerAlignment = false;
564 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000565 return ChromiumStyle;
566}
567
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000568FormatStyle getMozillaStyle() {
569 FormatStyle MozillaStyle = getLLVMStyle();
570 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000571 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000572 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
573 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000574 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000575 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000576 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
577 MozillaStyle.ConstructorInitializerIndentWidth = 2;
578 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000579 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000580 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000581 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000582 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
583 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000584 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000585 return MozillaStyle;
586}
587
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000588FormatStyle getWebKitStyle() {
589 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000590 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000591 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000592 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000593 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000594 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000595 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000596 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000597 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000598 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000599 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000600 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000601 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000602 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000603 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000604 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000605 return Style;
606}
607
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000608FormatStyle getGNUStyle() {
609 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000610 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000611 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000612 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000613 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000614 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000615 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000616 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000617 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000618 return Style;
619}
620
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000621FormatStyle getNoStyle() {
622 FormatStyle NoStyle = getLLVMStyle();
623 NoStyle.DisableFormat = true;
624 return NoStyle;
625}
626
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000627bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
628 FormatStyle *Style) {
629 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000630 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000631 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000632 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000633 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000634 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000635 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000636 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000637 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000638 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000639 } else if (Name.equals_lower("gnu")) {
640 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000641 } else if (Name.equals_lower("none")) {
642 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000643 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000644 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000645 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000646
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000647 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000648 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000649}
650
Rafael Espindolac0809172014-06-12 14:02:15 +0000651std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000652 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000653 FormatStyle::LanguageKind Language = Style->Language;
654 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000655 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000656 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000657
658 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000659 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000660 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
661 // values for the fields, keys for which are missing from the configuration.
662 // Mapping also uses the context to get the language to find the correct
663 // base style.
664 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000665 Input >> Styles;
666 if (Input.error())
667 return Input.error();
668
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000669 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000670 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000671 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000672 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000673 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000674 for (unsigned j = 0; j < i; ++j) {
675 if (Styles[i].Language == Styles[j].Language) {
676 DEBUG(llvm::dbgs()
677 << "Duplicate languages in the config file on positions " << j
678 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000679 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000680 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000681 }
682 }
683 // Look for a suitable configuration starting from the end, so we can
684 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000685 // configuration (which can only be at slot 0) after it.
686 for (int i = Styles.size() - 1; i >= 0; --i) {
687 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000688 Styles[i].Language == FormatStyle::LK_None) {
689 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000690 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000691 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000692 }
693 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000694 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000695}
696
697std::string configurationAsText(const FormatStyle &Style) {
698 std::string Text;
699 llvm::raw_string_ostream Stream(Text);
700 llvm::yaml::Output Output(Stream);
701 // We use the same mapping method for input and output, so we need a non-const
702 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000703 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000704 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000705 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000706}
707
Craig Topperaf35e852013-06-30 22:29:28 +0000708namespace {
709
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000710class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000711public:
Daniel Jasper23376252014-09-09 14:37:39 +0000712 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000713 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000714 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000715 LessStashed(false), Column(0), TrailingWhitespace(0),
716 SourceMgr(SourceMgr), ID(ID), Style(Style),
717 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000718 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
719 MacroBlockBeginRegex(Style.MacroBlockBegin),
720 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000721 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
722 getFormattingLangOpts(Style)));
723 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000724
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000725 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000726 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
727 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000728 }
729
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000730 ArrayRef<FormatToken *> lex() {
731 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000732 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000733 do {
734 Tokens.push_back(getNextToken());
Daniel Jasper265309e2015-10-18 07:02:28 +0000735 if (Style.Language == FormatStyle::LK_JavaScript)
736 tryParseJSRegexLiteral();
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000737 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000738 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000739 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000740 } while (Tokens.back()->Tok.isNot(tok::eof));
741 return Tokens;
742 }
743
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000744 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000745
746private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000747 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000748 if (tryMerge_TMacro())
749 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000750 if (tryMergeConflictMarkers())
751 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000752 if (tryMergeLessLess())
753 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000754
755 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000756 if (tryMergeTemplateString())
757 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000758
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000759 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
760 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
761 tok::equal};
762 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
763 tok::greaterequal};
764 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000765 // FIXME: Investigate what token type gives the correct operator priority.
766 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000767 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000768 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000769 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000770 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000771 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000772 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000773 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000774 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000775 }
776
Jacques Pienaarfc275112015-02-18 23:48:37 +0000777 bool tryMergeLessLess() {
778 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000779 if (Tokens.size() < 3)
780 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000781
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000782 bool FourthTokenIsLess = false;
783 if (Tokens.size() > 3)
784 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000785
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000786 auto First = Tokens.end() - 3;
787 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
788 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000789 return false;
790
791 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000792 if (First[1]->WhitespaceRange.getBegin() !=
793 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000794 return false;
795
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000796 First[0]->Tok.setKind(tok::lessless);
797 First[0]->TokenText = "<<";
798 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000799 Tokens.erase(Tokens.end() - 2);
800 return true;
801 }
802
Manuel Klimek79e06082015-05-21 12:23:34 +0000803 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000804 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000805 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000806
807 SmallVectorImpl<FormatToken *>::const_iterator First =
808 Tokens.end() - Kinds.size();
809 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000810 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000811 unsigned AddLength = 0;
812 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000813 if (!First[i]->is(Kinds[i]) ||
814 First[i]->WhitespaceRange.getBegin() !=
815 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000816 return false;
817 AddLength += First[i]->TokenText.size();
818 }
819 Tokens.resize(Tokens.size() - Kinds.size() + 1);
820 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
821 First[0]->TokenText.size() + AddLength);
822 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000823 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000824 return true;
825 }
826
Daniel Jasper265309e2015-10-18 07:02:28 +0000827 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
828 bool precedesOperand(FormatToken *Tok) {
829 // NB: This is not entirely correct, as an r_paren can introduce an operand
830 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
831 // corner case to not matter in practice, though.
832 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
833 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
834 tok::colon, tok::question, tok::tilde) ||
835 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
836 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
837 tok::kw_typeof, Keywords.kw_instanceof,
838 Keywords.kw_in) ||
839 Tok->isBinaryOperator();
840 }
841
842 bool canPrecedeRegexLiteral(FormatToken *Prev) {
843 if (!Prev)
844 return true;
845
846 // Regex literals can only follow after prefix unary operators, not after
847 // postfix unary operators. If the '++' is followed by a non-operand
848 // introducing token, the slash here is the operand and not the start of a
849 // regex.
850 if (Prev->isOneOf(tok::plusplus, tok::minusminus))
851 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
852
853 // The previous token must introduce an operand location where regex
854 // literals can occur.
855 if (!precedesOperand(Prev))
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000856 return false;
Daniel Jasper265309e2015-10-18 07:02:28 +0000857
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000858 return true;
859 }
860
Daniel Jasper265309e2015-10-18 07:02:28 +0000861 // Tries to parse a JavaScript Regex literal starting at the current token,
862 // if that begins with a slash and is in a location where JavaScript allows
863 // regex literals. Changes the current token to a regex literal and updates
864 // its text if successful.
865 void tryParseJSRegexLiteral() {
866 FormatToken *RegexToken = Tokens.back();
867 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
868 return;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000869
Daniel Jasper265309e2015-10-18 07:02:28 +0000870 FormatToken *Prev = nullptr;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000871 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
Daniel Jasper265309e2015-10-18 07:02:28 +0000872 // NB: Because previous pointers are not initialized yet, this cannot use
873 // Token.getPreviousNonComment.
874 if ((*I)->isNot(tok::comment)) {
875 Prev = *I;
876 break;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000877 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000878 }
Daniel Jasper265309e2015-10-18 07:02:28 +0000879
880 if (!canPrecedeRegexLiteral(Prev))
881 return;
882
883 // 'Manually' lex ahead in the current file buffer.
884 const char *Offset = Lex->getBufferLocation();
885 const char *RegexBegin = Offset - RegexToken->TokenText.size();
886 StringRef Buffer = Lex->getBuffer();
887 bool InCharacterClass = false;
888 bool HaveClosingSlash = false;
889 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
890 // Regular expressions are terminated with a '/', which can only be
891 // escaped using '\' or a character class between '[' and ']'.
892 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
893 switch (*Offset) {
894 case '\\':
895 // Skip the escaped character.
896 ++Offset;
897 break;
898 case '[':
899 InCharacterClass = true;
900 break;
901 case ']':
902 InCharacterClass = false;
903 break;
904 case '/':
905 if (!InCharacterClass)
906 HaveClosingSlash = true;
907 break;
908 }
909 }
910
911 RegexToken->Type = TT_RegexLiteral;
912 // Treat regex literals like other string_literals.
913 RegexToken->Tok.setKind(tok::string_literal);
914 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
915 RegexToken->ColumnWidth = RegexToken->TokenText.size();
916
917 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000918 }
919
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000920 bool tryMergeTemplateString() {
921 if (Tokens.size() < 2)
922 return false;
923
924 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000925 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000926 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
927 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000928 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
929 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000930 return false;
931 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
932 // Unknown token that's not actually a backtick, or a comment that doesn't
933 // contain a backtick.
934 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000935 return false;
936
937 unsigned TokenCount = 0;
938 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000939 unsigned EndColumnInFirstLine =
940 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000941 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
942 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000943 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000944 IsMultiline = true;
945
946 // If there was a preceding template string, this must be the start of a
947 // template string, not the end.
948 if (I[0]->is(TT_TemplateString))
949 return false;
950
951 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
952 // Keep track of the rhs offset of the last token to wrap across lines -
953 // its the rhs offset of the first line of the template string, used to
954 // determine its width.
955 if (I[0]->IsMultiline)
956 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
957 // If the token has newlines, the token before it (if it exists) is the
958 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000959 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000960 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000961 IsMultiline = true;
962 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000963 continue;
964 }
965
966 Tokens.resize(Tokens.size() - TokenCount);
967 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000968 const char *EndOffset =
969 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
970 if (CommentBacktickPos != 0) {
971 // If the backtick was not the first character (e.g. in a comment),
972 // re-lex after the backtick position.
973 SourceLocation Loc = EndBacktick->Tok.getLocation();
974 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
975 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000976 Tokens.back()->TokenText =
977 StringRef(Tokens.back()->TokenText.data(),
978 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000979
980 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
981 if (EndOriginalColumn == 0) {
982 SourceLocation Loc = EndBacktick->Tok.getLocation();
983 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
984 }
985 // If the ` is further down within the token (e.g. in a comment).
986 EndOriginalColumn += CommentBacktickPos;
987
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000988 if (IsMultiline) {
989 // ColumnWidth is from backtick to last token in line.
990 // LastLineColumnWidth is 0 to backtick.
991 // x = `some content
992 // until here`;
993 Tokens.back()->ColumnWidth =
994 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000995 // +1 for the ` itself.
996 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000997 Tokens.back()->IsMultiline = true;
998 } else {
999 // Token simply spans from start to end, +1 for the ` itself.
1000 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001001 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001002 }
1003 return true;
1004 }
1005 return false;
1006 }
1007
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001008 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001009 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001010 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001011 FormatToken *Last = Tokens.back();
1012 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001013 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001014
1015 FormatToken *String = Tokens[Tokens.size() - 2];
1016 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001017 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001018
1019 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001020 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001021
1022 FormatToken *Macro = Tokens[Tokens.size() - 4];
1023 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001024 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001025
1026 const char *Start = Macro->TokenText.data();
1027 const char *End = Last->TokenText.data() + Last->TokenText.size();
1028 String->TokenText = StringRef(Start, End - Start);
1029 String->IsFirst = Macro->IsFirst;
1030 String->LastNewlineOffset = Macro->LastNewlineOffset;
1031 String->WhitespaceRange = Macro->WhitespaceRange;
1032 String->OriginalColumn = Macro->OriginalColumn;
1033 String->ColumnWidth = encoding::columnWidthWithTabs(
1034 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001035 String->NewlinesBefore = Macro->NewlinesBefore;
1036 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001037
1038 Tokens.pop_back();
1039 Tokens.pop_back();
1040 Tokens.pop_back();
1041 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001042 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001043 }
1044
Manuel Klimek68b03042014-04-14 09:14:11 +00001045 bool tryMergeConflictMarkers() {
1046 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1047 return false;
1048
1049 // Conflict lines look like:
1050 // <marker> <text from the vcs>
1051 // For example:
1052 // >>>>>>> /file/in/file/system at revision 1234
1053 //
1054 // We merge all tokens in a line that starts with a conflict marker
1055 // into a single token with a special token type that the unwrapped line
1056 // parser will use to correctly rebuild the underlying code.
1057
1058 FileID ID;
1059 // Get the position of the first token in the line.
1060 unsigned FirstInLineOffset;
1061 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1062 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1063 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1064 // Calculate the offset of the start of the current line.
1065 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1066 if (LineOffset == StringRef::npos) {
1067 LineOffset = 0;
1068 } else {
1069 ++LineOffset;
1070 }
1071
1072 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1073 StringRef LineStart;
1074 if (FirstSpace == StringRef::npos) {
1075 LineStart = Buffer.substr(LineOffset);
1076 } else {
1077 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1078 }
1079
1080 TokenType Type = TT_Unknown;
1081 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1082 Type = TT_ConflictStart;
1083 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1084 LineStart == "====") {
1085 Type = TT_ConflictAlternative;
1086 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1087 Type = TT_ConflictEnd;
1088 }
1089
1090 if (Type != TT_Unknown) {
1091 FormatToken *Next = Tokens.back();
1092
1093 Tokens.resize(FirstInLineIndex + 1);
1094 // We do not need to build a complete token here, as we will skip it
1095 // during parsing anyway (as we must not touch whitespace around conflict
1096 // markers).
1097 Tokens.back()->Type = Type;
1098 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1099
1100 Tokens.push_back(Next);
1101 return true;
1102 }
1103
1104 return false;
1105 }
1106
Jacques Pienaarfc275112015-02-18 23:48:37 +00001107 FormatToken *getStashedToken() {
1108 // Create a synthesized second '>' or '<' token.
1109 Token Tok = FormatTok->Tok;
1110 StringRef TokenText = FormatTok->TokenText;
1111
1112 unsigned OriginalColumn = FormatTok->OriginalColumn;
1113 FormatTok = new (Allocator.Allocate()) FormatToken;
1114 FormatTok->Tok = Tok;
1115 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001116 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1117 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001118 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1119 FormatTok->TokenText = TokenText;
1120 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001121 FormatTok->OriginalColumn = OriginalColumn + 1;
1122
Jacques Pienaarfc275112015-02-18 23:48:37 +00001123 return FormatTok;
1124 }
1125
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001126 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001127 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001128 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001129 return getStashedToken();
1130 }
1131 if (LessStashed) {
1132 LessStashed = false;
1133 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001134 }
1135
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001136 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001137 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001138 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001139 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001140 FormatTok->IsFirst = IsFirstToken;
1141 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001142
1143 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001144 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001145 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001146 StringRef Text = FormatTok->TokenText;
1147 auto EscapesNewline = [&](int pos) {
1148 // A '\r' here is just part of '\r\n'. Skip it.
1149 if (pos >= 0 && Text[pos] == '\r')
1150 --pos;
1151 // See whether there is an odd number of '\' before this.
1152 unsigned count = 0;
1153 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001154 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001155 break;
1156 return count & 1;
1157 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001158 // FIXME: This miscounts tok:unknown tokens that are not just
1159 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001160 for (int i = 0, e = Text.size(); i != e; ++i) {
1161 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001162 case '\n':
1163 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001164 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001165 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1166 Column = 0;
1167 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001168 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001169 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1170 Column = 0;
1171 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001172 case '\f':
1173 case '\v':
1174 Column = 0;
1175 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001176 case ' ':
1177 ++Column;
1178 break;
1179 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001180 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001181 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001182 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001183 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001184 FormatTok->Type = TT_ImplicitStringLiteral;
1185 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001186 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001187 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001188 break;
1189 }
1190 }
1191
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001192 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001193 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001194 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001195
Daniel Jasper8369aa52013-07-16 20:28:33 +00001196 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001197 }
Manuel Klimekef920692013-01-07 07:56:50 +00001198
Manuel Klimek1abf7892013-01-04 23:34:14 +00001199 // In case the token starts with escaped newlines, we want to
1200 // take them into account as whitespace - this pattern is quite frequent
1201 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001202 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001203 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1204 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001205 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001206 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001207 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001208 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001209 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001210 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001211
1212 FormatTok->WhitespaceRange = SourceRange(
1213 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1214
Manuel Klimek31c85922013-08-29 15:21:40 +00001215 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001216
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001217 TrailingWhitespace = 0;
1218 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001219 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001220 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001221 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001222 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001223 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001224 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001225 FormatTok->Tok.setIdentifierInfo(&Info);
1226 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001227 if (Style.Language == FormatStyle::LK_Java &&
1228 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1229 FormatTok->Tok.setKind(tok::identifier);
1230 FormatTok->Tok.setIdentifierInfo(nullptr);
1231 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001232 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001233 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001234 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001235 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001236 } else if (FormatTok->Tok.is(tok::lessless)) {
1237 FormatTok->Tok.setKind(tok::less);
1238 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1239 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001240 }
1241
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001242 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001243
Alexander Kornienko39856b72013-09-10 09:38:25 +00001244 StringRef Text = FormatTok->TokenText;
1245 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001246 if (FirstNewlinePos == StringRef::npos) {
1247 // FIXME: ColumnWidth actually depends on the start column, we need to
1248 // take this into account when the token is moved.
1249 FormatTok->ColumnWidth =
1250 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1251 Column += FormatTok->ColumnWidth;
1252 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001253 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001254 // FIXME: ColumnWidth actually depends on the start column, we need to
1255 // take this into account when the token is moved.
1256 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1257 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1258
Alexander Kornienko39856b72013-09-10 09:38:25 +00001259 // The last line of the token always starts in column 0.
1260 // Thus, the length can be precomputed even in the presence of tabs.
1261 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1262 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1263 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001264 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001265 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001266
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001267 if (Style.Language == FormatStyle::LK_Cpp) {
1268 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1269 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1270 tok::pp_define) &&
1271 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1272 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1273 FormatTok->Type = TT_ForEachMacro;
1274 } else if (FormatTok->is(tok::identifier)) {
1275 if (MacroBlockBeginRegex.match(Text)) {
1276 FormatTok->Type = TT_MacroBlockBegin;
1277 } else if (MacroBlockEndRegex.match(Text)) {
1278 FormatTok->Type = TT_MacroBlockEnd;
1279 }
1280 }
1281 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001282
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001283 return FormatTok;
1284 }
1285
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001286 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001287 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001288 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001289 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001290 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001291 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001292 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001293 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001294 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001295 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001296 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001297 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001298 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001299 // Index (in 'Tokens') of the last token that starts a new line.
1300 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001301 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001302 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001303
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001304 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001305
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001306 llvm::Regex MacroBlockBeginRegex;
1307 llvm::Regex MacroBlockEndRegex;
1308
Daniel Jasper8369aa52013-07-16 20:28:33 +00001309 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001310 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001311 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1312 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001313 // For formatting, treat unterminated string literals like normal string
1314 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001315 if (Tok.is(tok::unknown)) {
1316 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1317 Tok.Tok.setKind(tok::string_literal);
1318 Tok.IsUnterminatedLiteral = true;
1319 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1320 Tok.TokenText == "''") {
1321 Tok.Tok.setKind(tok::char_constant);
1322 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001323 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001324
1325 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1326 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001327 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001328 }
1329
Daniel Jasper471894432014-08-06 13:40:26 +00001330 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001331
1332 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1333 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001334 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001335 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001336 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001337
1338 void resetLexer(unsigned Offset) {
1339 StringRef Buffer = SourceMgr.getBufferData(ID);
1340 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1341 getFormattingLangOpts(Style), Buffer.begin(),
1342 Buffer.begin() + Offset, Buffer.end()));
1343 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001344 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001345 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001346};
1347
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001348static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1349 switch (Language) {
1350 case FormatStyle::LK_Cpp:
1351 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001352 case FormatStyle::LK_Java:
1353 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001354 case FormatStyle::LK_JavaScript:
1355 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001356 case FormatStyle::LK_Proto:
1357 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001358 default:
1359 return "Unknown";
1360 }
1361}
1362
Daniel Jasperf7935112012-12-03 18:12:45 +00001363class Formatter : public UnwrappedLineConsumer {
1364public:
Daniel Jasper23376252014-09-09 14:37:39 +00001365 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001366 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001367 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1368 Whitespaces(SourceMgr, Style,
1369 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001370 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001371 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001372 DEBUG(llvm::dbgs() << "File encoding: "
1373 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1374 : "unknown")
1375 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001376 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1377 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001378 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001379
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001380 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001381 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001382 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001383
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001384 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1385 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001386 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001387 assert(UnwrappedLines.rbegin()->empty());
1388 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1389 ++Run) {
1390 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1391 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1392 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1393 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1394 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001395 tooling::Replacements RunResult =
1396 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001397 DEBUG({
1398 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1399 for (tooling::Replacements::iterator I = RunResult.begin(),
1400 E = RunResult.end();
1401 I != E; ++I) {
1402 llvm::dbgs() << I->toString() << "\n";
1403 }
1404 });
1405 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1406 delete AnnotatedLines[i];
1407 }
1408 Result.insert(RunResult.begin(), RunResult.end());
1409 Whitespaces.reset();
1410 }
1411 return Result;
1412 }
1413
1414 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001415 FormatTokenLexer &Tokens,
1416 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001417 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001418 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001419 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001420 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001421 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001422 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001423 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001424 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001425 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001426
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001427 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001428 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1429 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001430 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001431 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1432 IncompleteFormat)
1433 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001434 return Whitespaces.generateReplacements();
1435 }
1436
1437private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001438 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001439 // Returns \c true if at least one line between I and E or one of their
1440 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001441 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1442 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1443 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001444 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001445 while (I != E) {
1446 AnnotatedLine *Line = *I;
1447 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1448
1449 // If a line is part of a preprocessor directive, it needs to be formatted
1450 // if any token within the directive is affected.
1451 if (Line->InPPDirective) {
1452 FormatToken *Last = Line->Last;
1453 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1454 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1455 Last = (*PPEnd)->Last;
1456 ++PPEnd;
1457 }
1458
1459 if (affectsTokenRange(*Line->First, *Last,
1460 /*IncludeLeadingNewlines=*/false)) {
1461 SomeLineAffected = true;
1462 markAllAsAffected(I, PPEnd);
1463 }
1464 I = PPEnd;
1465 continue;
1466 }
1467
Daniel Jasper38c82402013-11-29 09:27:43 +00001468 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001469 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001470
Daniel Jasper38c82402013-11-29 09:27:43 +00001471 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001472 ++I;
1473 }
1474 return SomeLineAffected;
1475 }
1476
Daniel Jasper9c199562013-11-28 15:58:55 +00001477 // Determines whether 'Line' is affected by the SourceRanges given as input.
1478 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001479 bool nonPPLineAffected(AnnotatedLine *Line,
1480 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001481 bool SomeLineAffected = false;
1482 Line->ChildrenAffected =
1483 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1484 if (Line->ChildrenAffected)
1485 SomeLineAffected = true;
1486
1487 // Stores whether one of the line's tokens is directly affected.
1488 bool SomeTokenAffected = false;
1489 // Stores whether we need to look at the leading newlines of the next token
1490 // in order to determine whether it was affected.
1491 bool IncludeLeadingNewlines = false;
1492
1493 // Stores whether the first child line of any of this line's tokens is
1494 // affected.
1495 bool SomeFirstChildAffected = false;
1496
1497 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1498 // Determine whether 'Tok' was affected.
1499 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1500 SomeTokenAffected = true;
1501
1502 // Determine whether the first child of 'Tok' was affected.
1503 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1504 SomeFirstChildAffected = true;
1505
1506 IncludeLeadingNewlines = Tok->Children.empty();
1507 }
1508
1509 // Was this line moved, i.e. has it previously been on the same line as an
1510 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001511 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1512 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001513
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001514 bool IsContinuedComment =
1515 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1516 Line->First->NewlinesBefore < 2 && PreviousLine &&
1517 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001518
1519 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1520 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001521 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001522 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001523 }
1524 return SomeLineAffected;
1525 }
1526
Daniel Jasper5500f612013-11-25 11:08:59 +00001527 // Marks all lines between I and E as well as all their children as affected.
1528 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1529 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1530 while (I != E) {
1531 (*I)->Affected = true;
1532 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1533 ++I;
1534 }
1535 }
1536
1537 // Returns true if the range from 'First' to 'Last' intersects with one of the
1538 // input ranges.
1539 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1540 bool IncludeLeadingNewlines) {
1541 SourceLocation Start = First.WhitespaceRange.getBegin();
1542 if (!IncludeLeadingNewlines)
1543 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001544 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001545 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001546 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1547 return affectsCharSourceRange(Range);
1548 }
1549
1550 // Returns true if one of the input ranges intersect the leading empty lines
1551 // before 'Tok'.
1552 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1553 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1554 Tok.WhitespaceRange.getBegin(),
1555 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1556 return affectsCharSourceRange(EmptyLineRange);
1557 }
1558
1559 // Returns true if 'Range' intersects with one of the input ranges.
1560 bool affectsCharSourceRange(const CharSourceRange &Range) {
1561 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1562 E = Ranges.end();
1563 I != E; ++I) {
1564 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1565 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1566 return true;
1567 }
1568 return false;
1569 }
1570
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001571 static bool inputUsesCRLF(StringRef Text) {
1572 return Text.count('\r') * 2 > Text.count('\n');
1573 }
1574
Daniel Jasper352f0df2015-07-18 16:35:30 +00001575 bool
1576 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1577 for (const AnnotatedLine* Line : Lines) {
1578 if (hasCpp03IncompatibleFormat(Line->Children))
1579 return true;
1580 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1581 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1582 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1583 return true;
1584 if (Tok->is(TT_TemplateCloser) &&
1585 Tok->Previous->is(TT_TemplateCloser))
1586 return true;
1587 }
1588 }
1589 }
1590 return false;
1591 }
1592
1593 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1594 int AlignmentDiff = 0;
1595 for (const AnnotatedLine* Line : Lines) {
1596 AlignmentDiff += countVariableAlignments(Line->Children);
1597 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1598 if (!Tok->is(TT_PointerOrReference))
1599 continue;
1600 bool SpaceBefore =
1601 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1602 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1603 Tok->Next->WhitespaceRange.getEnd();
1604 if (SpaceBefore && !SpaceAfter)
1605 ++AlignmentDiff;
1606 if (!SpaceBefore && SpaceAfter)
1607 --AlignmentDiff;
1608 }
1609 }
1610 return AlignmentDiff;
1611 }
1612
Manuel Klimek71814b42013-10-11 21:25:45 +00001613 void
1614 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001615 bool HasBinPackedFunction = false;
1616 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001617 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001618 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001619 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001620 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001621 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001622 if (Tok->PackingKind == PPK_BinPacked)
1623 HasBinPackedFunction = true;
1624 if (Tok->PackingKind == PPK_OnePerLine)
1625 HasOnePerLineFunction = true;
1626
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001627 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001628 }
1629 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001630 if (Style.DerivePointerAlignment)
1631 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1632 ? FormatStyle::PAS_Left
1633 : FormatStyle::PAS_Right;
1634 if (Style.Standard == FormatStyle::LS_Auto)
1635 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1636 ? FormatStyle::LS_Cpp11
1637 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001638 BinPackInconclusiveFunctions =
1639 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001640 }
1641
Craig Topperfb6b25b2014-03-15 04:29:04 +00001642 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001643 assert(!UnwrappedLines.empty());
1644 UnwrappedLines.back().push_back(TheLine);
1645 }
1646
Craig Topperfb6b25b2014-03-15 04:29:04 +00001647 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001648 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001649 }
1650
1651 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001652 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001653 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001654 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001655 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001656 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001657
1658 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001659 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001660};
1661
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001662struct IncludeDirective {
1663 StringRef Filename;
1664 StringRef Text;
1665 unsigned Offset;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001666 unsigned Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001667};
1668
Craig Topperaf35e852013-06-30 22:29:28 +00001669} // end anonymous namespace
1670
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001671// Determines whether 'Ranges' intersects with ('Start', 'End').
1672static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1673 unsigned End) {
1674 for (auto Range : Ranges) {
1675 if (Range.getOffset() < End &&
1676 Range.getOffset() + Range.getLength() > Start)
1677 return true;
1678 }
1679 return false;
1680}
1681
1682// Sorts a block of includes given by 'Includes' alphabetically adding the
1683// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1684// order.
1685static void sortIncludes(const FormatStyle &Style,
1686 const SmallVectorImpl<IncludeDirective> &Includes,
1687 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1688 tooling::Replacements &Replaces) {
1689 if (!affectsRange(Ranges, Includes.front().Offset,
1690 Includes.back().Offset + Includes.back().Text.size()))
1691 return;
1692 SmallVector<unsigned, 16> Indices;
1693 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1694 Indices.push_back(i);
1695 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001696 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1697 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001698 });
1699
1700 // If the #includes are out of order, we generate a single replacement fixing
1701 // the entire block. Otherwise, no replacement is generated.
1702 bool OutOfOrder = false;
1703 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1704 if (Indices[i] != i) {
1705 OutOfOrder = true;
1706 break;
1707 }
1708 }
1709 if (!OutOfOrder)
1710 return;
1711
1712 std::string result = Includes[Indices[0]].Text;
1713 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1714 result += "\n";
1715 result += Includes[Indices[i]].Text;
1716 }
1717
1718 // Sorting #includes shouldn't change their total number of characters.
1719 // This would otherwise mess up 'Ranges'.
1720 assert(result.size() ==
1721 Includes.back().Offset + Includes.back().Text.size() -
1722 Includes.front().Offset);
1723
1724 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1725 result.size(), result));
1726}
1727
1728tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1729 ArrayRef<tooling::Range> Ranges,
1730 StringRef FileName) {
1731 tooling::Replacements Replaces;
1732 unsigned Prev = 0;
1733 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001734 llvm::Regex IncludeRegex(
1735 R"(^[\t\ ]*#[\t\ ]*include[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001736 SmallVector<StringRef, 4> Matches;
1737 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001738
1739 // In compiled files, consider the first #include to be the main #include of
1740 // the file if it is not a system #include. This ensures that the header
1741 // doesn't have hidden dependencies
1742 // (http://llvm.org/docs/CodingStandards.html#include-style).
1743 //
1744 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1745 // cases where the first #include is unlikely to be the main header.
1746 bool LookForMainHeader = FileName.endswith(".c") ||
1747 FileName.endswith(".cc") ||
1748 FileName.endswith(".cpp")||
1749 FileName.endswith(".c++")||
1750 FileName.endswith(".cxx");
1751
1752 // Create pre-compiled regular expressions for the #include categories.
1753 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001754 for (const auto &Category : Style.IncludeCategories)
1755 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001756
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001757 for (;;) {
1758 auto Pos = Code.find('\n', SearchFrom);
1759 StringRef Line =
1760 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1761 if (!Line.endswith("\\")) {
1762 if (IncludeRegex.match(Line, &Matches)) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001763 unsigned Category;
1764 if (LookForMainHeader && !Matches[1].startswith("<")) {
1765 Category = 0;
1766 } else {
1767 Category = UINT_MAX;
1768 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1769 if (CategoryRegexs[i].match(Matches[1])) {
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001770 Category = Style.IncludeCategories[i].Priority;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001771 break;
1772 }
1773 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001774 }
Daniel Jasper85c472d2015-09-29 07:53:08 +00001775 LookForMainHeader = false;
1776 IncludesInBlock.push_back({Matches[1], Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001777 } else if (!IncludesInBlock.empty()) {
1778 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1779 IncludesInBlock.clear();
1780 }
1781 Prev = Pos + 1;
1782 }
1783 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1784 break;
1785 SearchFrom = Pos + 1;
1786 }
1787 if (!IncludesInBlock.empty())
1788 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1789 return Replaces;
1790}
1791
Daniel Jasper23376252014-09-09 14:37:39 +00001792tooling::Replacements reformat(const FormatStyle &Style,
1793 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001794 ArrayRef<CharSourceRange> Ranges,
1795 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001796 FormatStyle Expanded = expandPresets(Style);
1797 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001798 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001799 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001800 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001801}
1802
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001803tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001804 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001805 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001806 if (Style.DisableFormat)
1807 return tooling::Replacements();
1808
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001809 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1810 new vfs::InMemoryFileSystem);
1811 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001812 DiagnosticsEngine Diagnostics(
1813 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1814 new DiagnosticOptions);
1815 SourceManager SourceMgr(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001816 InMemoryFileSystem->addFile(FileName, 0,
1817 llvm::MemoryBuffer::getMemBuffer(Code, FileName));
1818 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1819 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001820 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1821 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001822 for (const tooling::Range &Range : Ranges) {
1823 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1824 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001825 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1826 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001827 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001828}
1829
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001830LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001831 LangOptions LangOpts;
1832 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001833 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1834 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001835 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001836 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001837 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001838 LangOpts.Bool = 1;
1839 LangOpts.ObjC1 = 1;
1840 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001841 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001842 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001843 return LangOpts;
1844}
1845
Edwin Vaned544aa72013-09-30 13:31:48 +00001846const char *StyleOptionHelpDescription =
1847 "Coding style, currently supports:\n"
1848 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1849 "Use -style=file to load style configuration from\n"
1850 ".clang-format file located in one of the parent\n"
1851 "directories of the source file (or current\n"
1852 "directory for stdin).\n"
1853 "Use -style=\"{key: value, ...}\" to set specific\n"
1854 "parameters, e.g.:\n"
1855 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1856
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001857static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001858 if (FileName.endswith(".java")) {
1859 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001860 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1861 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001862 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001863 } else if (FileName.endswith_lower(".proto") ||
1864 FileName.endswith_lower(".protodevel")) {
1865 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001866 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001867 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001868}
1869
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001870FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1871 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001872 FormatStyle Style = getLLVMStyle();
1873 Style.Language = getLanguageByFileName(FileName);
1874 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001875 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1876 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001877 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001878 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001879
1880 if (StyleName.startswith("{")) {
1881 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001882 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001883 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1884 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001885 }
1886 return Style;
1887 }
1888
1889 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001890 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001891 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1892 << " style\n";
1893 return Style;
1894 }
1895
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001896 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001897 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001898 SmallString<128> Path(FileName);
1899 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001900 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001901 Directory = llvm::sys::path::parent_path(Directory)) {
1902 if (!llvm::sys::fs::is_directory(Directory))
1903 continue;
1904 SmallString<128> ConfigFile(Directory);
1905
1906 llvm::sys::path::append(ConfigFile, ".clang-format");
1907 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1908 bool IsFile = false;
1909 // Ignore errors from is_regular_file: we only need to know if we can read
1910 // the file or not.
1911 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1912
1913 if (!IsFile) {
1914 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1915 ConfigFile = Directory;
1916 llvm::sys::path::append(ConfigFile, "_clang-format");
1917 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1918 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1919 }
1920
1921 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001922 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1923 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1924 if (std::error_code EC = Text.getError()) {
1925 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001926 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001927 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001928 if (std::error_code ec =
1929 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001930 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001931 if (!UnsuitableConfigFiles.empty())
1932 UnsuitableConfigFiles.append(", ");
1933 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001934 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001935 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001936 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1937 << "\n";
1938 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001939 }
1940 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1941 return Style;
1942 }
1943 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001944 if (!UnsuitableConfigFiles.empty()) {
1945 llvm::errs() << "Configuration file(s) do(es) not support "
1946 << getLanguageName(Style.Language) << ": "
1947 << UnsuitableConfigFiles << "\n";
1948 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001949 return Style;
1950}
1951
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001952} // namespace format
1953} // namespace clang