blob: 56c4d43aa154ff901565f55f063c19c7e5af032c [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());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000735 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000736 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000737 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000738 } while (Tokens.back()->Tok.isNot(tok::eof));
739 return Tokens;
740 }
741
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000742 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000743
744private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000745 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000746 if (tryMerge_TMacro())
747 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000748 if (tryMergeConflictMarkers())
749 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000750 if (tryMergeLessLess())
751 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000752
753 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000754 if (tryMergeJSRegexLiteral())
755 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000756 if (tryMergeEscapeSequence())
757 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000758 if (tryMergeTemplateString())
759 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000760
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000761 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
762 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
763 tok::equal};
764 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
765 tok::greaterequal};
766 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000767 // FIXME: Investigate what token type gives the correct operator priority.
768 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000769 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000770 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000771 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000772 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000773 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000774 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000775 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000776 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000777 }
778
Jacques Pienaarfc275112015-02-18 23:48:37 +0000779 bool tryMergeLessLess() {
780 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000781 if (Tokens.size() < 3)
782 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000783
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000784 bool FourthTokenIsLess = false;
785 if (Tokens.size() > 3)
786 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000787
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000788 auto First = Tokens.end() - 3;
789 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
790 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000791 return false;
792
793 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000794 if (First[1]->WhitespaceRange.getBegin() !=
795 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000796 return false;
797
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000798 First[0]->Tok.setKind(tok::lessless);
799 First[0]->TokenText = "<<";
800 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000801 Tokens.erase(Tokens.end() - 2);
802 return true;
803 }
804
Manuel Klimek79e06082015-05-21 12:23:34 +0000805 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000806 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000807 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000808
809 SmallVectorImpl<FormatToken *>::const_iterator First =
810 Tokens.end() - Kinds.size();
811 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000812 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000813 unsigned AddLength = 0;
814 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000815 if (!First[i]->is(Kinds[i]) ||
816 First[i]->WhitespaceRange.getBegin() !=
817 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000818 return false;
819 AddLength += First[i]->TokenText.size();
820 }
821 Tokens.resize(Tokens.size() - Kinds.size() + 1);
822 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
823 First[0]->TokenText.size() + AddLength);
824 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000825 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000826 return true;
827 }
828
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000829 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000830 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000831 bool tryMergeEscapeSequence() {
832 if (Tokens.size() < 2)
833 return false;
834 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000835 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000836 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000837 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000838 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000839 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
840 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000841 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000842 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000843 return true;
844 }
845
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000846 // Try to determine whether the current token ends a JavaScript regex literal.
847 // We heuristically assume that this is a regex literal if we find two
848 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000849 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
850 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000851 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000852 if (Tokens.size() < 2)
853 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000854
855 // If this is a string literal with a slash inside, compute the slash's
856 // offset and try to find the beginning of the regex literal.
857 // Also look at tok::unknown, as it can be an unterminated char literal.
858 size_t SlashInStringPos = StringRef::npos;
859 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
860 tok::unknown)) {
861 // Start search from position 1 as otherwise, this is an unknown token
862 // for an unterminated /*-comment which is handled elsewhere.
863 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
864 if (SlashInStringPos == StringRef::npos)
865 return false;
866 }
867
Daniel Jasper23376252014-09-09 14:37:39 +0000868 // If a regex literal ends in "\//", this gets represented by an unknown
869 // token "\" and a comment.
870 bool MightEndWithEscapedSlash =
871 Tokens.back()->is(tok::comment) &&
872 Tokens.back()->TokenText.startswith("//") &&
873 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000874 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000875 (Tokens.back()->isNot(tok::slash) ||
876 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
877 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000878 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000879
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000880 unsigned TokenCount = 0;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000881 bool InCharacterClass = false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000882 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
883 ++TokenCount;
Daniel Jasperf7372152015-07-02 14:14:04 +0000884 auto Prev = I + 1;
885 while (Prev != E && Prev[0]->is(tok::comment))
886 ++Prev;
Daniel Jasper8d0e2232015-10-12 03:13:48 +0000887 // Slashes in character classes (delimited by [ and ]) do not need
888 // escaping. Escaping of the squares themselves is already handled by
889 // \c tryMergeEscapeSequence(), a plain tok::r_square must be non-escaped.
890 if (I[0]->is(tok::r_square))
891 InCharacterClass = true;
892 if (I[0]->is(tok::l_square)) {
893 if (!InCharacterClass)
894 return false;
895 InCharacterClass = false;
896 }
897 if (!InCharacterClass && I[0]->isOneOf(tok::slash, tok::slashequal) &&
Daniel Jasperf7372152015-07-02 14:14:04 +0000898 (Prev == E ||
899 ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
900 tok::r_brace, tok::exclaim, tok::l_square,
901 tok::colon, tok::comma, tok::question,
902 tok::kw_return) ||
903 Prev[0]->isBinaryOperator())))) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000904 unsigned LastColumn = Tokens.back()->OriginalColumn;
905 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000906 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000907 // This regex literal ends in '\//'. Skip past the '//' of the last
908 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000909 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000910 } else if (SlashInStringPos != StringRef::npos) {
911 // This regex literal ends in a string_literal with a slash inside.
912 // Calculate end column and reset lexer appropriately.
913 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
914 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000915 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000916 Tokens.resize(Tokens.size() - TokenCount);
917 Tokens.back()->Tok.setKind(tok::unknown);
918 Tokens.back()->Type = TT_RegexLiteral;
Daniel Jasperf1446202015-07-02 15:00:44 +0000919 // Treat regex literals like other string_literals.
920 Tokens.back()->Tok.setKind(tok::string_literal);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000921 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
922 return true;
923 }
924
925 // There can't be a newline inside a regex literal.
926 if (I[0]->NewlinesBefore > 0)
927 return false;
928 }
929 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000930 }
931
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000932 bool tryMergeTemplateString() {
933 if (Tokens.size() < 2)
934 return false;
935
936 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000937 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000938 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
939 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000940 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
941 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000942 return false;
943 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
944 // Unknown token that's not actually a backtick, or a comment that doesn't
945 // contain a backtick.
946 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000947 return false;
948
949 unsigned TokenCount = 0;
950 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000951 unsigned EndColumnInFirstLine =
952 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000953 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
954 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000955 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000956 IsMultiline = true;
957
958 // If there was a preceding template string, this must be the start of a
959 // template string, not the end.
960 if (I[0]->is(TT_TemplateString))
961 return false;
962
963 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
964 // Keep track of the rhs offset of the last token to wrap across lines -
965 // its the rhs offset of the first line of the template string, used to
966 // determine its width.
967 if (I[0]->IsMultiline)
968 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
969 // If the token has newlines, the token before it (if it exists) is the
970 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000971 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000972 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000973 IsMultiline = true;
974 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000975 continue;
976 }
977
978 Tokens.resize(Tokens.size() - TokenCount);
979 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000980 const char *EndOffset =
981 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
982 if (CommentBacktickPos != 0) {
983 // If the backtick was not the first character (e.g. in a comment),
984 // re-lex after the backtick position.
985 SourceLocation Loc = EndBacktick->Tok.getLocation();
986 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
987 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000988 Tokens.back()->TokenText =
989 StringRef(Tokens.back()->TokenText.data(),
990 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000991
992 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
993 if (EndOriginalColumn == 0) {
994 SourceLocation Loc = EndBacktick->Tok.getLocation();
995 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
996 }
997 // If the ` is further down within the token (e.g. in a comment).
998 EndOriginalColumn += CommentBacktickPos;
999
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001000 if (IsMultiline) {
1001 // ColumnWidth is from backtick to last token in line.
1002 // LastLineColumnWidth is 0 to backtick.
1003 // x = `some content
1004 // until here`;
1005 Tokens.back()->ColumnWidth =
1006 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +00001007 // +1 for the ` itself.
1008 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001009 Tokens.back()->IsMultiline = true;
1010 } else {
1011 // Token simply spans from start to end, +1 for the ` itself.
1012 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +00001013 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001014 }
1015 return true;
1016 }
1017 return false;
1018 }
1019
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001020 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001021 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001022 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001023 FormatToken *Last = Tokens.back();
1024 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001025 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001026
1027 FormatToken *String = Tokens[Tokens.size() - 2];
1028 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001029 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001030
1031 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001032 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001033
1034 FormatToken *Macro = Tokens[Tokens.size() - 4];
1035 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001036 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001037
1038 const char *Start = Macro->TokenText.data();
1039 const char *End = Last->TokenText.data() + Last->TokenText.size();
1040 String->TokenText = StringRef(Start, End - Start);
1041 String->IsFirst = Macro->IsFirst;
1042 String->LastNewlineOffset = Macro->LastNewlineOffset;
1043 String->WhitespaceRange = Macro->WhitespaceRange;
1044 String->OriginalColumn = Macro->OriginalColumn;
1045 String->ColumnWidth = encoding::columnWidthWithTabs(
1046 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +00001047 String->NewlinesBefore = Macro->NewlinesBefore;
1048 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001049
1050 Tokens.pop_back();
1051 Tokens.pop_back();
1052 Tokens.pop_back();
1053 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001054 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001055 }
1056
Manuel Klimek68b03042014-04-14 09:14:11 +00001057 bool tryMergeConflictMarkers() {
1058 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1059 return false;
1060
1061 // Conflict lines look like:
1062 // <marker> <text from the vcs>
1063 // For example:
1064 // >>>>>>> /file/in/file/system at revision 1234
1065 //
1066 // We merge all tokens in a line that starts with a conflict marker
1067 // into a single token with a special token type that the unwrapped line
1068 // parser will use to correctly rebuild the underlying code.
1069
1070 FileID ID;
1071 // Get the position of the first token in the line.
1072 unsigned FirstInLineOffset;
1073 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1074 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1075 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1076 // Calculate the offset of the start of the current line.
1077 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1078 if (LineOffset == StringRef::npos) {
1079 LineOffset = 0;
1080 } else {
1081 ++LineOffset;
1082 }
1083
1084 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1085 StringRef LineStart;
1086 if (FirstSpace == StringRef::npos) {
1087 LineStart = Buffer.substr(LineOffset);
1088 } else {
1089 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1090 }
1091
1092 TokenType Type = TT_Unknown;
1093 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1094 Type = TT_ConflictStart;
1095 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1096 LineStart == "====") {
1097 Type = TT_ConflictAlternative;
1098 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1099 Type = TT_ConflictEnd;
1100 }
1101
1102 if (Type != TT_Unknown) {
1103 FormatToken *Next = Tokens.back();
1104
1105 Tokens.resize(FirstInLineIndex + 1);
1106 // We do not need to build a complete token here, as we will skip it
1107 // during parsing anyway (as we must not touch whitespace around conflict
1108 // markers).
1109 Tokens.back()->Type = Type;
1110 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1111
1112 Tokens.push_back(Next);
1113 return true;
1114 }
1115
1116 return false;
1117 }
1118
Jacques Pienaarfc275112015-02-18 23:48:37 +00001119 FormatToken *getStashedToken() {
1120 // Create a synthesized second '>' or '<' token.
1121 Token Tok = FormatTok->Tok;
1122 StringRef TokenText = FormatTok->TokenText;
1123
1124 unsigned OriginalColumn = FormatTok->OriginalColumn;
1125 FormatTok = new (Allocator.Allocate()) FormatToken;
1126 FormatTok->Tok = Tok;
1127 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001128 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1129 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001130 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1131 FormatTok->TokenText = TokenText;
1132 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001133 FormatTok->OriginalColumn = OriginalColumn + 1;
1134
Jacques Pienaarfc275112015-02-18 23:48:37 +00001135 return FormatTok;
1136 }
1137
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001138 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001139 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001140 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001141 return getStashedToken();
1142 }
1143 if (LessStashed) {
1144 LessStashed = false;
1145 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001146 }
1147
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001148 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001149 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001150 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001151 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001152 FormatTok->IsFirst = IsFirstToken;
1153 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001154
1155 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001156 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001157 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001158 StringRef Text = FormatTok->TokenText;
1159 auto EscapesNewline = [&](int pos) {
1160 // A '\r' here is just part of '\r\n'. Skip it.
1161 if (pos >= 0 && Text[pos] == '\r')
1162 --pos;
1163 // See whether there is an odd number of '\' before this.
1164 unsigned count = 0;
1165 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001166 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001167 break;
1168 return count & 1;
1169 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001170 // FIXME: This miscounts tok:unknown tokens that are not just
1171 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001172 for (int i = 0, e = Text.size(); i != e; ++i) {
1173 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001174 case '\n':
1175 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001176 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001177 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1178 Column = 0;
1179 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001180 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001181 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1182 Column = 0;
1183 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001184 case '\f':
1185 case '\v':
1186 Column = 0;
1187 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001188 case ' ':
1189 ++Column;
1190 break;
1191 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001192 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001193 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001194 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001195 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001196 FormatTok->Type = TT_ImplicitStringLiteral;
1197 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001198 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001199 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001200 break;
1201 }
1202 }
1203
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001204 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001205 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001206 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001207
Daniel Jasper8369aa52013-07-16 20:28:33 +00001208 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001209 }
Manuel Klimekef920692013-01-07 07:56:50 +00001210
Manuel Klimek1abf7892013-01-04 23:34:14 +00001211 // In case the token starts with escaped newlines, we want to
1212 // take them into account as whitespace - this pattern is quite frequent
1213 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001214 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001215 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1216 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001217 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001218 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001219 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001220 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001221 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001222 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001223
1224 FormatTok->WhitespaceRange = SourceRange(
1225 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1226
Manuel Klimek31c85922013-08-29 15:21:40 +00001227 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001229 TrailingWhitespace = 0;
1230 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001231 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001232 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001233 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001234 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001235 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001236 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001237 FormatTok->Tok.setIdentifierInfo(&Info);
1238 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001239 if (Style.Language == FormatStyle::LK_Java &&
1240 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1241 FormatTok->Tok.setKind(tok::identifier);
1242 FormatTok->Tok.setIdentifierInfo(nullptr);
1243 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001244 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001245 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001246 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001247 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001248 } else if (FormatTok->Tok.is(tok::lessless)) {
1249 FormatTok->Tok.setKind(tok::less);
1250 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1251 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001252 }
1253
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001254 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001255
Alexander Kornienko39856b72013-09-10 09:38:25 +00001256 StringRef Text = FormatTok->TokenText;
1257 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001258 if (FirstNewlinePos == StringRef::npos) {
1259 // FIXME: ColumnWidth actually depends on the start column, we need to
1260 // take this into account when the token is moved.
1261 FormatTok->ColumnWidth =
1262 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1263 Column += FormatTok->ColumnWidth;
1264 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001265 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001266 // FIXME: ColumnWidth actually depends on the start column, we need to
1267 // take this into account when the token is moved.
1268 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1269 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1270
Alexander Kornienko39856b72013-09-10 09:38:25 +00001271 // The last line of the token always starts in column 0.
1272 // Thus, the length can be precomputed even in the presence of tabs.
1273 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1274 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1275 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001276 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001277 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001278
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001279 if (Style.Language == FormatStyle::LK_Cpp) {
1280 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1281 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1282 tok::pp_define) &&
1283 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1284 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1285 FormatTok->Type = TT_ForEachMacro;
1286 } else if (FormatTok->is(tok::identifier)) {
1287 if (MacroBlockBeginRegex.match(Text)) {
1288 FormatTok->Type = TT_MacroBlockBegin;
1289 } else if (MacroBlockEndRegex.match(Text)) {
1290 FormatTok->Type = TT_MacroBlockEnd;
1291 }
1292 }
1293 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001294
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001295 return FormatTok;
1296 }
1297
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001298 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001299 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001300 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001301 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001302 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001303 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001304 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001305 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001306 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001307 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001308 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001309 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001310 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001311 // Index (in 'Tokens') of the last token that starts a new line.
1312 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001313 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001314 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001315
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001316 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001317
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001318 llvm::Regex MacroBlockBeginRegex;
1319 llvm::Regex MacroBlockEndRegex;
1320
Daniel Jasper8369aa52013-07-16 20:28:33 +00001321 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001322 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001323 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1324 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001325 // For formatting, treat unterminated string literals like normal string
1326 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001327 if (Tok.is(tok::unknown)) {
1328 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1329 Tok.Tok.setKind(tok::string_literal);
1330 Tok.IsUnterminatedLiteral = true;
1331 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1332 Tok.TokenText == "''") {
1333 Tok.Tok.setKind(tok::char_constant);
1334 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001335 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001336
1337 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1338 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001339 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001340 }
1341
Daniel Jasper471894432014-08-06 13:40:26 +00001342 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001343
1344 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1345 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001346 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001347 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001348 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001349
1350 void resetLexer(unsigned Offset) {
1351 StringRef Buffer = SourceMgr.getBufferData(ID);
1352 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1353 getFormattingLangOpts(Style), Buffer.begin(),
1354 Buffer.begin() + Offset, Buffer.end()));
1355 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001356 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001357 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001358};
1359
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001360static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1361 switch (Language) {
1362 case FormatStyle::LK_Cpp:
1363 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001364 case FormatStyle::LK_Java:
1365 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001366 case FormatStyle::LK_JavaScript:
1367 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001368 case FormatStyle::LK_Proto:
1369 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001370 default:
1371 return "Unknown";
1372 }
1373}
1374
Daniel Jasperf7935112012-12-03 18:12:45 +00001375class Formatter : public UnwrappedLineConsumer {
1376public:
Daniel Jasper23376252014-09-09 14:37:39 +00001377 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001378 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001379 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1380 Whitespaces(SourceMgr, Style,
1381 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001382 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001383 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001384 DEBUG(llvm::dbgs() << "File encoding: "
1385 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1386 : "unknown")
1387 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001388 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1389 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001390 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001391
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001392 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001393 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001394 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001395
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001396 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1397 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001398 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001399 assert(UnwrappedLines.rbegin()->empty());
1400 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1401 ++Run) {
1402 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1403 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1404 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1405 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1406 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001407 tooling::Replacements RunResult =
1408 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001409 DEBUG({
1410 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1411 for (tooling::Replacements::iterator I = RunResult.begin(),
1412 E = RunResult.end();
1413 I != E; ++I) {
1414 llvm::dbgs() << I->toString() << "\n";
1415 }
1416 });
1417 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1418 delete AnnotatedLines[i];
1419 }
1420 Result.insert(RunResult.begin(), RunResult.end());
1421 Whitespaces.reset();
1422 }
1423 return Result;
1424 }
1425
1426 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001427 FormatTokenLexer &Tokens,
1428 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001429 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001430 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001431 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001432 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001433 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001434 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001435 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001436 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001437 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001438
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001439 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001440 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1441 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001442 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001443 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1444 IncompleteFormat)
1445 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001446 return Whitespaces.generateReplacements();
1447 }
1448
1449private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001450 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001451 // Returns \c true if at least one line between I and E or one of their
1452 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001453 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1454 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1455 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001456 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001457 while (I != E) {
1458 AnnotatedLine *Line = *I;
1459 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1460
1461 // If a line is part of a preprocessor directive, it needs to be formatted
1462 // if any token within the directive is affected.
1463 if (Line->InPPDirective) {
1464 FormatToken *Last = Line->Last;
1465 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1466 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1467 Last = (*PPEnd)->Last;
1468 ++PPEnd;
1469 }
1470
1471 if (affectsTokenRange(*Line->First, *Last,
1472 /*IncludeLeadingNewlines=*/false)) {
1473 SomeLineAffected = true;
1474 markAllAsAffected(I, PPEnd);
1475 }
1476 I = PPEnd;
1477 continue;
1478 }
1479
Daniel Jasper38c82402013-11-29 09:27:43 +00001480 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001481 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001482
Daniel Jasper38c82402013-11-29 09:27:43 +00001483 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001484 ++I;
1485 }
1486 return SomeLineAffected;
1487 }
1488
Daniel Jasper9c199562013-11-28 15:58:55 +00001489 // Determines whether 'Line' is affected by the SourceRanges given as input.
1490 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001491 bool nonPPLineAffected(AnnotatedLine *Line,
1492 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001493 bool SomeLineAffected = false;
1494 Line->ChildrenAffected =
1495 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1496 if (Line->ChildrenAffected)
1497 SomeLineAffected = true;
1498
1499 // Stores whether one of the line's tokens is directly affected.
1500 bool SomeTokenAffected = false;
1501 // Stores whether we need to look at the leading newlines of the next token
1502 // in order to determine whether it was affected.
1503 bool IncludeLeadingNewlines = false;
1504
1505 // Stores whether the first child line of any of this line's tokens is
1506 // affected.
1507 bool SomeFirstChildAffected = false;
1508
1509 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1510 // Determine whether 'Tok' was affected.
1511 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1512 SomeTokenAffected = true;
1513
1514 // Determine whether the first child of 'Tok' was affected.
1515 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1516 SomeFirstChildAffected = true;
1517
1518 IncludeLeadingNewlines = Tok->Children.empty();
1519 }
1520
1521 // Was this line moved, i.e. has it previously been on the same line as an
1522 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001523 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1524 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001525
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001526 bool IsContinuedComment =
1527 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1528 Line->First->NewlinesBefore < 2 && PreviousLine &&
1529 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001530
1531 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1532 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001533 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001534 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001535 }
1536 return SomeLineAffected;
1537 }
1538
Daniel Jasper5500f612013-11-25 11:08:59 +00001539 // Marks all lines between I and E as well as all their children as affected.
1540 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1541 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1542 while (I != E) {
1543 (*I)->Affected = true;
1544 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1545 ++I;
1546 }
1547 }
1548
1549 // Returns true if the range from 'First' to 'Last' intersects with one of the
1550 // input ranges.
1551 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1552 bool IncludeLeadingNewlines) {
1553 SourceLocation Start = First.WhitespaceRange.getBegin();
1554 if (!IncludeLeadingNewlines)
1555 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001556 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001557 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001558 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1559 return affectsCharSourceRange(Range);
1560 }
1561
1562 // Returns true if one of the input ranges intersect the leading empty lines
1563 // before 'Tok'.
1564 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1565 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1566 Tok.WhitespaceRange.getBegin(),
1567 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1568 return affectsCharSourceRange(EmptyLineRange);
1569 }
1570
1571 // Returns true if 'Range' intersects with one of the input ranges.
1572 bool affectsCharSourceRange(const CharSourceRange &Range) {
1573 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1574 E = Ranges.end();
1575 I != E; ++I) {
1576 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1577 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1578 return true;
1579 }
1580 return false;
1581 }
1582
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001583 static bool inputUsesCRLF(StringRef Text) {
1584 return Text.count('\r') * 2 > Text.count('\n');
1585 }
1586
Daniel Jasper352f0df2015-07-18 16:35:30 +00001587 bool
1588 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1589 for (const AnnotatedLine* Line : Lines) {
1590 if (hasCpp03IncompatibleFormat(Line->Children))
1591 return true;
1592 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1593 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1594 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1595 return true;
1596 if (Tok->is(TT_TemplateCloser) &&
1597 Tok->Previous->is(TT_TemplateCloser))
1598 return true;
1599 }
1600 }
1601 }
1602 return false;
1603 }
1604
1605 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1606 int AlignmentDiff = 0;
1607 for (const AnnotatedLine* Line : Lines) {
1608 AlignmentDiff += countVariableAlignments(Line->Children);
1609 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1610 if (!Tok->is(TT_PointerOrReference))
1611 continue;
1612 bool SpaceBefore =
1613 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1614 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1615 Tok->Next->WhitespaceRange.getEnd();
1616 if (SpaceBefore && !SpaceAfter)
1617 ++AlignmentDiff;
1618 if (!SpaceBefore && SpaceAfter)
1619 --AlignmentDiff;
1620 }
1621 }
1622 return AlignmentDiff;
1623 }
1624
Manuel Klimek71814b42013-10-11 21:25:45 +00001625 void
1626 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001627 bool HasBinPackedFunction = false;
1628 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001629 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001630 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001631 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001632 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001633 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001634 if (Tok->PackingKind == PPK_BinPacked)
1635 HasBinPackedFunction = true;
1636 if (Tok->PackingKind == PPK_OnePerLine)
1637 HasOnePerLineFunction = true;
1638
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001639 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001640 }
1641 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001642 if (Style.DerivePointerAlignment)
1643 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1644 ? FormatStyle::PAS_Left
1645 : FormatStyle::PAS_Right;
1646 if (Style.Standard == FormatStyle::LS_Auto)
1647 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1648 ? FormatStyle::LS_Cpp11
1649 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001650 BinPackInconclusiveFunctions =
1651 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001652 }
1653
Craig Topperfb6b25b2014-03-15 04:29:04 +00001654 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001655 assert(!UnwrappedLines.empty());
1656 UnwrappedLines.back().push_back(TheLine);
1657 }
1658
Craig Topperfb6b25b2014-03-15 04:29:04 +00001659 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001660 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001661 }
1662
1663 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001664 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001665 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001666 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001667 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001668 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001669
1670 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001671 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001672};
1673
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001674struct IncludeDirective {
1675 StringRef Filename;
1676 StringRef Text;
1677 unsigned Offset;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001678 unsigned Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001679};
1680
Craig Topperaf35e852013-06-30 22:29:28 +00001681} // end anonymous namespace
1682
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001683// Determines whether 'Ranges' intersects with ('Start', 'End').
1684static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1685 unsigned End) {
1686 for (auto Range : Ranges) {
1687 if (Range.getOffset() < End &&
1688 Range.getOffset() + Range.getLength() > Start)
1689 return true;
1690 }
1691 return false;
1692}
1693
1694// Sorts a block of includes given by 'Includes' alphabetically adding the
1695// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1696// order.
1697static void sortIncludes(const FormatStyle &Style,
1698 const SmallVectorImpl<IncludeDirective> &Includes,
1699 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1700 tooling::Replacements &Replaces) {
1701 if (!affectsRange(Ranges, Includes.front().Offset,
1702 Includes.back().Offset + Includes.back().Text.size()))
1703 return;
1704 SmallVector<unsigned, 16> Indices;
1705 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1706 Indices.push_back(i);
1707 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001708 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1709 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001710 });
1711
1712 // If the #includes are out of order, we generate a single replacement fixing
1713 // the entire block. Otherwise, no replacement is generated.
1714 bool OutOfOrder = false;
1715 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1716 if (Indices[i] != i) {
1717 OutOfOrder = true;
1718 break;
1719 }
1720 }
1721 if (!OutOfOrder)
1722 return;
1723
1724 std::string result = Includes[Indices[0]].Text;
1725 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1726 result += "\n";
1727 result += Includes[Indices[i]].Text;
1728 }
1729
1730 // Sorting #includes shouldn't change their total number of characters.
1731 // This would otherwise mess up 'Ranges'.
1732 assert(result.size() ==
1733 Includes.back().Offset + Includes.back().Text.size() -
1734 Includes.front().Offset);
1735
1736 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1737 result.size(), result));
1738}
1739
1740tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1741 ArrayRef<tooling::Range> Ranges,
1742 StringRef FileName) {
1743 tooling::Replacements Replaces;
1744 unsigned Prev = 0;
1745 unsigned SearchFrom = 0;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001746 llvm::Regex IncludeRegex(
1747 R"(^[\t\ ]*#[\t\ ]*include[^"<]*(["<][^">]*[">]))");
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001748 SmallVector<StringRef, 4> Matches;
1749 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001750
1751 // In compiled files, consider the first #include to be the main #include of
1752 // the file if it is not a system #include. This ensures that the header
1753 // doesn't have hidden dependencies
1754 // (http://llvm.org/docs/CodingStandards.html#include-style).
1755 //
1756 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1757 // cases where the first #include is unlikely to be the main header.
1758 bool LookForMainHeader = FileName.endswith(".c") ||
1759 FileName.endswith(".cc") ||
1760 FileName.endswith(".cpp")||
1761 FileName.endswith(".c++")||
1762 FileName.endswith(".cxx");
1763
1764 // Create pre-compiled regular expressions for the #include categories.
1765 SmallVector<llvm::Regex, 4> CategoryRegexs;
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001766 for (const auto &Category : Style.IncludeCategories)
1767 CategoryRegexs.emplace_back(Category.Regex);
Daniel Jasper85c472d2015-09-29 07:53:08 +00001768
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001769 for (;;) {
1770 auto Pos = Code.find('\n', SearchFrom);
1771 StringRef Line =
1772 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1773 if (!Line.endswith("\\")) {
1774 if (IncludeRegex.match(Line, &Matches)) {
Daniel Jasper85c472d2015-09-29 07:53:08 +00001775 unsigned Category;
1776 if (LookForMainHeader && !Matches[1].startswith("<")) {
1777 Category = 0;
1778 } else {
1779 Category = UINT_MAX;
1780 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1781 if (CategoryRegexs[i].match(Matches[1])) {
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +00001782 Category = Style.IncludeCategories[i].Priority;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001783 break;
1784 }
1785 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001786 }
Daniel Jasper85c472d2015-09-29 07:53:08 +00001787 LookForMainHeader = false;
1788 IncludesInBlock.push_back({Matches[1], Line, Prev, Category});
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001789 } else if (!IncludesInBlock.empty()) {
1790 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1791 IncludesInBlock.clear();
1792 }
1793 Prev = Pos + 1;
1794 }
1795 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1796 break;
1797 SearchFrom = Pos + 1;
1798 }
1799 if (!IncludesInBlock.empty())
1800 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1801 return Replaces;
1802}
1803
Daniel Jasper23376252014-09-09 14:37:39 +00001804tooling::Replacements reformat(const FormatStyle &Style,
1805 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001806 ArrayRef<CharSourceRange> Ranges,
1807 bool *IncompleteFormat) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001808 FormatStyle Expanded = expandPresets(Style);
1809 if (Expanded.DisableFormat)
Daniel Jasper23376252014-09-09 14:37:39 +00001810 return tooling::Replacements();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001811 Formatter formatter(Expanded, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001812 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001813}
1814
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001815tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001816 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001817 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001818 if (Style.DisableFormat)
1819 return tooling::Replacements();
1820
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001821 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
1822 new vfs::InMemoryFileSystem);
1823 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001824 DiagnosticsEngine Diagnostics(
1825 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1826 new DiagnosticOptions);
1827 SourceManager SourceMgr(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +00001828 InMemoryFileSystem->addFile(FileName, 0,
1829 llvm::MemoryBuffer::getMemBuffer(Code, FileName));
1830 FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
1831 clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001832 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1833 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001834 for (const tooling::Range &Range : Ranges) {
1835 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1836 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001837 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1838 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001839 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001840}
1841
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001842LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001843 LangOptions LangOpts;
1844 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001845 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1846 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001847 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001848 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001849 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001850 LangOpts.Bool = 1;
1851 LangOpts.ObjC1 = 1;
1852 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001853 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00001854 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001855 return LangOpts;
1856}
1857
Edwin Vaned544aa72013-09-30 13:31:48 +00001858const char *StyleOptionHelpDescription =
1859 "Coding style, currently supports:\n"
1860 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1861 "Use -style=file to load style configuration from\n"
1862 ".clang-format file located in one of the parent\n"
1863 "directories of the source file (or current\n"
1864 "directory for stdin).\n"
1865 "Use -style=\"{key: value, ...}\" to set specific\n"
1866 "parameters, e.g.:\n"
1867 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1868
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001869static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001870 if (FileName.endswith(".java")) {
1871 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001872 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1873 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001874 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001875 } else if (FileName.endswith_lower(".proto") ||
1876 FileName.endswith_lower(".protodevel")) {
1877 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001878 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001879 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001880}
1881
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001882FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1883 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001884 FormatStyle Style = getLLVMStyle();
1885 Style.Language = getLanguageByFileName(FileName);
1886 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001887 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1888 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001889 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001890 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001891
1892 if (StyleName.startswith("{")) {
1893 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001894 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001895 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1896 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001897 }
1898 return Style;
1899 }
1900
1901 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001902 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001903 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1904 << " style\n";
1905 return Style;
1906 }
1907
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001908 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001909 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001910 SmallString<128> Path(FileName);
1911 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001912 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001913 Directory = llvm::sys::path::parent_path(Directory)) {
1914 if (!llvm::sys::fs::is_directory(Directory))
1915 continue;
1916 SmallString<128> ConfigFile(Directory);
1917
1918 llvm::sys::path::append(ConfigFile, ".clang-format");
1919 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1920 bool IsFile = false;
1921 // Ignore errors from is_regular_file: we only need to know if we can read
1922 // the file or not.
1923 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1924
1925 if (!IsFile) {
1926 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1927 ConfigFile = Directory;
1928 llvm::sys::path::append(ConfigFile, "_clang-format");
1929 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1930 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1931 }
1932
1933 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001934 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1935 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1936 if (std::error_code EC = Text.getError()) {
1937 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001938 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001939 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001940 if (std::error_code ec =
1941 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001942 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001943 if (!UnsuitableConfigFiles.empty())
1944 UnsuitableConfigFiles.append(", ");
1945 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001946 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001947 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001948 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1949 << "\n";
1950 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001951 }
1952 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1953 return Style;
1954 }
1955 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001956 if (!UnsuitableConfigFiles.empty()) {
1957 llvm::errs() << "Configuration file(s) do(es) not support "
1958 << getLanguageName(Style.Language) << ": "
1959 << UnsuitableConfigFiles << "\n";
1960 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001961 return Style;
1962}
1963
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001964} // namespace format
1965} // namespace clang