blob: 15aa50224bf2dc62303d1fdc46e81097b7f57bd2 [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 Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000018#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000020#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000021#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000022#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000030#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Chandler Carruth10346662014-04-22 03:17:02 +000035#define DEBUG_TYPE "format-formatter"
36
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000037using clang::format::FormatStyle;
38
Daniel Jaspere1e43192014-04-01 12:55:11 +000039LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
40
Alexander Kornienkod6538332013-05-07 15:32:14 +000041namespace llvm {
42namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000043template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
44 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
45 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000046 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000048 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000049 }
50};
51
52template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
53 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
54 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
55 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
56 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
57 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
58 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
59 }
60};
61
62template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
63 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
64 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
65 IO.enumCase(Value, "false", FormatStyle::UT_Never);
66 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
67 IO.enumCase(Value, "true", FormatStyle::UT_Always);
68 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
69 }
70};
71
Daniel Jasperd74cf402014-04-08 12:46:38 +000072template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
73 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
74 IO.enumCase(Value, "None", FormatStyle::SFS_None);
75 IO.enumCase(Value, "false", FormatStyle::SFS_None);
76 IO.enumCase(Value, "All", FormatStyle::SFS_All);
77 IO.enumCase(Value, "true", FormatStyle::SFS_All);
78 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000079 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000080 }
81};
82
Daniel Jasperac043c92014-09-15 11:11:00 +000083template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
84 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
85 IO.enumCase(Value, "All", FormatStyle::BOS_All);
86 IO.enumCase(Value, "true", FormatStyle::BOS_All);
87 IO.enumCase(Value, "None", FormatStyle::BOS_None);
88 IO.enumCase(Value, "false", FormatStyle::BOS_None);
89 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
90 }
91};
92
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000093template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
94 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
95 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
96 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +000097 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000098 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
99 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000100 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000101 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102 }
103};
104
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000105template <> struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
106 static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
107 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
108 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
109 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
110
111 // For backward compatibility.
112 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
113 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
114 }
115};
116
Alexander Kornienkod6538332013-05-07 15:32:14 +0000117template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000118struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000119 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000120 FormatStyle::NamespaceIndentationKind &Value) {
121 IO.enumCase(Value, "None", FormatStyle::NI_None);
122 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
123 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000124 }
125};
126
Jacques Pienaarfc275112015-02-18 23:48:37 +0000127template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
128 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000129 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
130 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
131 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
132
Alp Toker958027b2014-07-14 19:42:55 +0000133 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000134 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
135 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
136 }
137};
138
139template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000140struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000141 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000142 FormatStyle::SpaceBeforeParensOptions &Value) {
143 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000144 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000145 FormatStyle::SBPO_ControlStatements);
146 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000147
148 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000149 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
150 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000151 }
152};
153
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000154template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000155 static void mapping(IO &IO, FormatStyle &Style) {
156 // When reading, read the language first, we need it for getPredefinedStyle.
157 IO.mapOptional("Language", Style.Language);
158
Alexander Kornienko49149672013-05-10 11:56:10 +0000159 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000160 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
161 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000162 ArrayRef<StringRef> Styles(StylesArray);
163 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
164 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000165 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000166 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000167 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000168 IO.mapOptional("# BasedOnStyle", StyleName);
169 break;
170 }
171 }
172 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000173 StringRef BasedOnStyle;
174 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000175 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000176 FormatStyle::LanguageKind OldLanguage = Style.Language;
177 FormatStyle::LanguageKind Language =
178 ((FormatStyle *)IO.getContext())->Language;
179 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000180 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
181 return;
182 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000183 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000184 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185 }
186
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000187 // For backward compatibility.
188 if (!IO.outputting()) {
189 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
190 IO.mapOptional("IndentFunctionDeclarationAfterType",
191 Style.IndentWrappedFunctionNames);
192 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
193 IO.mapOptional("SpaceAfterControlStatementKeyword",
194 Style.SpaceBeforeParens);
195 }
196
Alexander Kornienkod6538332013-05-07 15:32:14 +0000197 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000198 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000199 IO.mapOptional("AlignConsecutiveAssignments",
200 Style.AlignConsecutiveAssignments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000202 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000203 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000204 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
205 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000206 IO.mapOptional("AllowShortBlocksOnASingleLine",
207 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000208 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
209 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000210 IO.mapOptional("AllowShortFunctionsOnASingleLine",
211 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000212 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
213 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000214 IO.mapOptional("AllowShortLoopsOnASingleLine",
215 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000216 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
217 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000218 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
219 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000220 IO.mapOptional("AlwaysBreakTemplateDeclarations",
221 Style.AlwaysBreakTemplateDeclarations);
222 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
223 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000224 IO.mapOptional("BreakBeforeBinaryOperators",
225 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000226 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000227 IO.mapOptional("BreakBeforeTernaryOperators",
228 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000229 IO.mapOptional("BreakConstructorInitializersBeforeComma",
230 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000232 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000233 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
234 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000235 IO.mapOptional("ConstructorInitializerIndentWidth",
236 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000237 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
238 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000239 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000240 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000241 IO.mapOptional("ExperimentalAutoDetectBinPacking",
242 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000243 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000244 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000245 IO.mapOptional("IndentWidth", Style.IndentWidth);
246 IO.mapOptional("IndentWrappedFunctionNames",
247 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000248 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
249 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000250 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
251 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000252 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000253 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000254 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000255 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000256 IO.mapOptional("ObjCSpaceBeforeProtocolList",
257 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000258 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
259 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000260 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000261 IO.mapOptional("PenaltyBreakFirstLessLess",
262 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000263 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000264 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
265 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
266 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000267 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000268 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000269 IO.mapOptional("SpaceBeforeAssignmentOperators",
270 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000271 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
272 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
273 IO.mapOptional("SpacesBeforeTrailingComments",
274 Style.SpacesBeforeTrailingComments);
275 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
276 IO.mapOptional("SpacesInContainerLiterals",
277 Style.SpacesInContainerLiterals);
278 IO.mapOptional("SpacesInCStyleCastParentheses",
279 Style.SpacesInCStyleCastParentheses);
280 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
281 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
282 IO.mapOptional("Standard", Style.Standard);
283 IO.mapOptional("TabWidth", Style.TabWidth);
284 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000285 }
286};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000287
288// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000289// IO.getContext() should contain a pointer to the FormatStyle structure, that
290// will be used to get default values for missing keys.
291// If the first element has no Language specified, it will be treated as the
292// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000293template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000294 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
295 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000296 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000297 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000298 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000299 if (Index >= Seq.size()) {
300 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000301 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000302 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000303 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000304 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000305 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000306 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000307 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000308 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000309 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000310 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000311 }
312};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000313} // namespace yaml
314} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000315
Daniel Jasperf7935112012-12-03 18:12:45 +0000316namespace clang {
317namespace format {
318
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000319const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000320 static ParseErrorCategory C;
321 return C;
322}
323std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000324 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000325}
326
327const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
328 return "clang-format.parse_error";
329}
330
331std::string ParseErrorCategory::message(int EV) const {
332 switch (static_cast<ParseError>(EV)) {
333 case ParseError::Success:
334 return "Success";
335 case ParseError::Error:
336 return "Invalid argument";
337 case ParseError::Unsuitable:
338 return "Unsuitable";
339 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000340 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000341}
342
Daniel Jasperf7935112012-12-03 18:12:45 +0000343FormatStyle getLLVMStyle() {
344 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000345 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000346 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000347 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000348 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000349 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000350 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000351 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000352 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000353 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000354 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000355 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000356 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000357 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000358 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000359 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000360 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000361 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000362 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000363 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000364 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000365 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
366 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000367 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000368 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000369 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000370 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000371 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000372 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000373 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000374 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000375 LLVMStyle.ForEachMacros.push_back("foreach");
376 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
377 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000378 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000379 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000380 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000381 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000382 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000383 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000384 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000385 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000386 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000387 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000388 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000389 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000390 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000391 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000392 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000393 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000394 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000395 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000396 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000397 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000398 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000399 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000400 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000401
Daniel Jasper19a541e2013-12-19 16:45:34 +0000402 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000403 LLVMStyle.PenaltyBreakFirstLessLess = 120;
404 LLVMStyle.PenaltyBreakString = 1000;
405 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000406 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000407 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000408
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000409 LLVMStyle.DisableFormat = false;
410
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 return LLVMStyle;
412}
413
Nico Weber514ecc82014-02-02 20:50:45 +0000414FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000415 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000416 GoogleStyle.Language = Language;
417
Daniel Jasperf7935112012-12-03 18:12:45 +0000418 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000419 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000420 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000421 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000422 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000423 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000424 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000425 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000426 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000427 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000428 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000429 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000430 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000431 GoogleStyle.SpacesBeforeTrailingComments = 2;
432 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000433
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000434 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000435 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000436
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000437 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000438 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000439 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000440 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000441 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000442 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000443 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000444 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
445 GoogleStyle.ColumnLimit = 100;
446 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000447 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000448 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000449 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000450 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000451 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000452 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000453 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000454 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000455 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000456 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000457 }
458
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 return GoogleStyle;
460}
461
Nico Weber514ecc82014-02-02 20:50:45 +0000462FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
463 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000464 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000465 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000466 ChromiumStyle.IndentWidth = 4;
467 ChromiumStyle.ContinuationIndentWidth = 8;
468 } else {
469 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
470 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
471 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
472 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
473 ChromiumStyle.BinPackParameters = false;
474 ChromiumStyle.DerivePointerAlignment = false;
475 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000476 return ChromiumStyle;
477}
478
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000479FormatStyle getMozillaStyle() {
480 FormatStyle MozillaStyle = getLLVMStyle();
481 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000482 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000483 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
484 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000485 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000486 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000487 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
488 MozillaStyle.ConstructorInitializerIndentWidth = 2;
489 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000490 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000491 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000492 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000493 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
494 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000495 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000496 return MozillaStyle;
497}
498
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000499FormatStyle getWebKitStyle() {
500 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000501 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000502 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000503 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000504 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000505 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000506 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000507 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000508 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000509 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000510 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000511 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000512 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000513 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000514 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000515 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000516 return Style;
517}
518
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000519FormatStyle getGNUStyle() {
520 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000521 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000522 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000523 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000524 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000525 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000526 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000527 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000528 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000529 return Style;
530}
531
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000532FormatStyle getNoStyle() {
533 FormatStyle NoStyle = getLLVMStyle();
534 NoStyle.DisableFormat = true;
535 return NoStyle;
536}
537
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000538bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
539 FormatStyle *Style) {
540 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000541 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000543 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000544 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000545 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000546 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000547 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000549 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000550 } else if (Name.equals_lower("gnu")) {
551 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000552 } else if (Name.equals_lower("none")) {
553 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000554 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000555 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000556 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000557
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000559 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000560}
561
Rafael Espindolac0809172014-06-12 14:02:15 +0000562std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000563 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000564 FormatStyle::LanguageKind Language = Style->Language;
565 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000566 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000567 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000568
569 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000570 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000571 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
572 // values for the fields, keys for which are missing from the configuration.
573 // Mapping also uses the context to get the language to find the correct
574 // base style.
575 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000576 Input >> Styles;
577 if (Input.error())
578 return Input.error();
579
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000580 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000581 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000582 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000583 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000584 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000585 for (unsigned j = 0; j < i; ++j) {
586 if (Styles[i].Language == Styles[j].Language) {
587 DEBUG(llvm::dbgs()
588 << "Duplicate languages in the config file on positions " << j
589 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000590 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000591 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000592 }
593 }
594 // Look for a suitable configuration starting from the end, so we can
595 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000596 // configuration (which can only be at slot 0) after it.
597 for (int i = Styles.size() - 1; i >= 0; --i) {
598 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000599 Styles[i].Language == FormatStyle::LK_None) {
600 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000601 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000602 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000603 }
604 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000605 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000606}
607
608std::string configurationAsText(const FormatStyle &Style) {
609 std::string Text;
610 llvm::raw_string_ostream Stream(Text);
611 llvm::yaml::Output Output(Stream);
612 // We use the same mapping method for input and output, so we need a non-const
613 // reference here.
614 FormatStyle NonConstStyle = Style;
615 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000616 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000617}
618
Craig Topperaf35e852013-06-30 22:29:28 +0000619namespace {
620
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000621class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000622public:
Daniel Jasper23376252014-09-09 14:37:39 +0000623 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000624 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000625 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000626 LessStashed(false), Column(0), TrailingWhitespace(0),
627 SourceMgr(SourceMgr), ID(ID), Style(Style),
628 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000629 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
630 MacroBlockBeginRegex(Style.MacroBlockBegin),
631 MacroBlockEndRegex(Style.MacroBlockEnd) {
Daniel Jasper23376252014-09-09 14:37:39 +0000632 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
633 getFormattingLangOpts(Style)));
634 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000635
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000636 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000637 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
638 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000639 }
640
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000641 ArrayRef<FormatToken *> lex() {
642 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000643 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000644 do {
645 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000646 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000647 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000648 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000649 } while (Tokens.back()->Tok.isNot(tok::eof));
650 return Tokens;
651 }
652
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000653 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000654
655private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000656 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000657 if (tryMerge_TMacro())
658 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000659 if (tryMergeConflictMarkers())
660 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000661 if (tryMergeLessLess())
662 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000663
664 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000665 if (tryMergeJSRegexLiteral())
666 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000667 if (tryMergeEscapeSequence())
668 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000669 if (tryMergeTemplateString())
670 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000671
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000672 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
673 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
674 tok::equal};
675 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
676 tok::greaterequal};
677 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000678 // FIXME: Investigate what token type gives the correct operator priority.
679 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000680 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000681 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000682 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000683 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000684 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000685 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000686 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000687 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000688 }
689
Jacques Pienaarfc275112015-02-18 23:48:37 +0000690 bool tryMergeLessLess() {
691 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000692 if (Tokens.size() < 3)
693 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000694
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000695 bool FourthTokenIsLess = false;
696 if (Tokens.size() > 3)
697 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000698
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000699 auto First = Tokens.end() - 3;
700 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
701 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000702 return false;
703
704 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000705 if (First[1]->WhitespaceRange.getBegin() !=
706 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000707 return false;
708
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000709 First[0]->Tok.setKind(tok::lessless);
710 First[0]->TokenText = "<<";
711 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000712 Tokens.erase(Tokens.end() - 2);
713 return true;
714 }
715
Manuel Klimek79e06082015-05-21 12:23:34 +0000716 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000717 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000718 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000719
720 SmallVectorImpl<FormatToken *>::const_iterator First =
721 Tokens.end() - Kinds.size();
722 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000723 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000724 unsigned AddLength = 0;
725 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000726 if (!First[i]->is(Kinds[i]) ||
727 First[i]->WhitespaceRange.getBegin() !=
728 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000729 return false;
730 AddLength += First[i]->TokenText.size();
731 }
732 Tokens.resize(Tokens.size() - Kinds.size() + 1);
733 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
734 First[0]->TokenText.size() + AddLength);
735 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000736 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000737 return true;
738 }
739
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000740 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000741 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000742 bool tryMergeEscapeSequence() {
743 if (Tokens.size() < 2)
744 return false;
745 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000746 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000747 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000748 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000749 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000750 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
751 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000752 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000753 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000754 return true;
755 }
756
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000757 // Try to determine whether the current token ends a JavaScript regex literal.
758 // We heuristically assume that this is a regex literal if we find two
759 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000760 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
761 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000762 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000763 if (Tokens.size() < 2)
764 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000765
766 // If this is a string literal with a slash inside, compute the slash's
767 // offset and try to find the beginning of the regex literal.
768 // Also look at tok::unknown, as it can be an unterminated char literal.
769 size_t SlashInStringPos = StringRef::npos;
770 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
771 tok::unknown)) {
772 // Start search from position 1 as otherwise, this is an unknown token
773 // for an unterminated /*-comment which is handled elsewhere.
774 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
775 if (SlashInStringPos == StringRef::npos)
776 return false;
777 }
778
Daniel Jasper23376252014-09-09 14:37:39 +0000779 // If a regex literal ends in "\//", this gets represented by an unknown
780 // token "\" and a comment.
781 bool MightEndWithEscapedSlash =
782 Tokens.back()->is(tok::comment) &&
783 Tokens.back()->TokenText.startswith("//") &&
784 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000785 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000786 (Tokens.back()->isNot(tok::slash) ||
787 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
788 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000789 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000790
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000791 unsigned TokenCount = 0;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000792 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
793 ++TokenCount;
Daniel Jasperf7372152015-07-02 14:14:04 +0000794 auto Prev = I + 1;
795 while (Prev != E && Prev[0]->is(tok::comment))
796 ++Prev;
Daniel Jasperc553ae12015-07-02 13:20:45 +0000797 if (I[0]->isOneOf(tok::slash, tok::slashequal) &&
Daniel Jasperf7372152015-07-02 14:14:04 +0000798 (Prev == E ||
799 ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
800 tok::r_brace, tok::exclaim, tok::l_square,
801 tok::colon, tok::comma, tok::question,
802 tok::kw_return) ||
803 Prev[0]->isBinaryOperator())))) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000804 unsigned LastColumn = Tokens.back()->OriginalColumn;
805 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000806 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000807 // This regex literal ends in '\//'. Skip past the '//' of the last
808 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000809 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000810 } else if (SlashInStringPos != StringRef::npos) {
811 // This regex literal ends in a string_literal with a slash inside.
812 // Calculate end column and reset lexer appropriately.
813 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
814 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000815 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000816 Tokens.resize(Tokens.size() - TokenCount);
817 Tokens.back()->Tok.setKind(tok::unknown);
818 Tokens.back()->Type = TT_RegexLiteral;
Daniel Jasperf1446202015-07-02 15:00:44 +0000819 // Treat regex literals like other string_literals.
820 Tokens.back()->Tok.setKind(tok::string_literal);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000821 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
822 return true;
823 }
824
825 // There can't be a newline inside a regex literal.
826 if (I[0]->NewlinesBefore > 0)
827 return false;
828 }
829 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000830 }
831
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000832 bool tryMergeTemplateString() {
833 if (Tokens.size() < 2)
834 return false;
835
836 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000837 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000838 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
839 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000840 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
841 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000842 return false;
843 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
844 // Unknown token that's not actually a backtick, or a comment that doesn't
845 // contain a backtick.
846 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000847 return false;
848
849 unsigned TokenCount = 0;
850 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000851 unsigned EndColumnInFirstLine =
852 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000853 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
854 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000855 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000856 IsMultiline = true;
857
858 // If there was a preceding template string, this must be the start of a
859 // template string, not the end.
860 if (I[0]->is(TT_TemplateString))
861 return false;
862
863 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
864 // Keep track of the rhs offset of the last token to wrap across lines -
865 // its the rhs offset of the first line of the template string, used to
866 // determine its width.
867 if (I[0]->IsMultiline)
868 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
869 // If the token has newlines, the token before it (if it exists) is the
870 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000871 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000872 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000873 IsMultiline = true;
874 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000875 continue;
876 }
877
878 Tokens.resize(Tokens.size() - TokenCount);
879 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000880 const char *EndOffset =
881 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
882 if (CommentBacktickPos != 0) {
883 // If the backtick was not the first character (e.g. in a comment),
884 // re-lex after the backtick position.
885 SourceLocation Loc = EndBacktick->Tok.getLocation();
886 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
887 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000888 Tokens.back()->TokenText =
889 StringRef(Tokens.back()->TokenText.data(),
890 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000891
892 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
893 if (EndOriginalColumn == 0) {
894 SourceLocation Loc = EndBacktick->Tok.getLocation();
895 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
896 }
897 // If the ` is further down within the token (e.g. in a comment).
898 EndOriginalColumn += CommentBacktickPos;
899
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000900 if (IsMultiline) {
901 // ColumnWidth is from backtick to last token in line.
902 // LastLineColumnWidth is 0 to backtick.
903 // x = `some content
904 // until here`;
905 Tokens.back()->ColumnWidth =
906 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000907 // +1 for the ` itself.
908 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000909 Tokens.back()->IsMultiline = true;
910 } else {
911 // Token simply spans from start to end, +1 for the ` itself.
912 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000913 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000914 }
915 return true;
916 }
917 return false;
918 }
919
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000920 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000921 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000922 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000923 FormatToken *Last = Tokens.back();
924 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000925 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000926
927 FormatToken *String = Tokens[Tokens.size() - 2];
928 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000929 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000930
931 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000932 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000933
934 FormatToken *Macro = Tokens[Tokens.size() - 4];
935 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000936 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000937
938 const char *Start = Macro->TokenText.data();
939 const char *End = Last->TokenText.data() + Last->TokenText.size();
940 String->TokenText = StringRef(Start, End - Start);
941 String->IsFirst = Macro->IsFirst;
942 String->LastNewlineOffset = Macro->LastNewlineOffset;
943 String->WhitespaceRange = Macro->WhitespaceRange;
944 String->OriginalColumn = Macro->OriginalColumn;
945 String->ColumnWidth = encoding::columnWidthWithTabs(
946 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +0000947 String->NewlinesBefore = Macro->NewlinesBefore;
948 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000949
950 Tokens.pop_back();
951 Tokens.pop_back();
952 Tokens.pop_back();
953 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000954 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000955 }
956
Manuel Klimek68b03042014-04-14 09:14:11 +0000957 bool tryMergeConflictMarkers() {
958 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
959 return false;
960
961 // Conflict lines look like:
962 // <marker> <text from the vcs>
963 // For example:
964 // >>>>>>> /file/in/file/system at revision 1234
965 //
966 // We merge all tokens in a line that starts with a conflict marker
967 // into a single token with a special token type that the unwrapped line
968 // parser will use to correctly rebuild the underlying code.
969
970 FileID ID;
971 // Get the position of the first token in the line.
972 unsigned FirstInLineOffset;
973 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
974 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
975 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
976 // Calculate the offset of the start of the current line.
977 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
978 if (LineOffset == StringRef::npos) {
979 LineOffset = 0;
980 } else {
981 ++LineOffset;
982 }
983
984 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
985 StringRef LineStart;
986 if (FirstSpace == StringRef::npos) {
987 LineStart = Buffer.substr(LineOffset);
988 } else {
989 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
990 }
991
992 TokenType Type = TT_Unknown;
993 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
994 Type = TT_ConflictStart;
995 } else if (LineStart == "|||||||" || LineStart == "=======" ||
996 LineStart == "====") {
997 Type = TT_ConflictAlternative;
998 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
999 Type = TT_ConflictEnd;
1000 }
1001
1002 if (Type != TT_Unknown) {
1003 FormatToken *Next = Tokens.back();
1004
1005 Tokens.resize(FirstInLineIndex + 1);
1006 // We do not need to build a complete token here, as we will skip it
1007 // during parsing anyway (as we must not touch whitespace around conflict
1008 // markers).
1009 Tokens.back()->Type = Type;
1010 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1011
1012 Tokens.push_back(Next);
1013 return true;
1014 }
1015
1016 return false;
1017 }
1018
Jacques Pienaarfc275112015-02-18 23:48:37 +00001019 FormatToken *getStashedToken() {
1020 // Create a synthesized second '>' or '<' token.
1021 Token Tok = FormatTok->Tok;
1022 StringRef TokenText = FormatTok->TokenText;
1023
1024 unsigned OriginalColumn = FormatTok->OriginalColumn;
1025 FormatTok = new (Allocator.Allocate()) FormatToken;
1026 FormatTok->Tok = Tok;
1027 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001028 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1029 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001030 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1031 FormatTok->TokenText = TokenText;
1032 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001033 FormatTok->OriginalColumn = OriginalColumn + 1;
1034
Jacques Pienaarfc275112015-02-18 23:48:37 +00001035 return FormatTok;
1036 }
1037
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001038 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001039 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001040 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001041 return getStashedToken();
1042 }
1043 if (LessStashed) {
1044 LessStashed = false;
1045 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001046 }
1047
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001048 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001049 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001050 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001051 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001052 FormatTok->IsFirst = IsFirstToken;
1053 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001054
1055 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001056 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001057 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001058 StringRef Text = FormatTok->TokenText;
1059 auto EscapesNewline = [&](int pos) {
1060 // A '\r' here is just part of '\r\n'. Skip it.
1061 if (pos >= 0 && Text[pos] == '\r')
1062 --pos;
1063 // See whether there is an odd number of '\' before this.
1064 unsigned count = 0;
1065 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001066 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001067 break;
1068 return count & 1;
1069 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001070 // FIXME: This miscounts tok:unknown tokens that are not just
1071 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001072 for (int i = 0, e = Text.size(); i != e; ++i) {
1073 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001074 case '\n':
1075 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001076 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001077 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1078 Column = 0;
1079 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001080 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001081 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1082 Column = 0;
1083 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001084 case '\f':
1085 case '\v':
1086 Column = 0;
1087 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001088 case ' ':
1089 ++Column;
1090 break;
1091 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001092 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001093 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001094 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001095 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001096 FormatTok->Type = TT_ImplicitStringLiteral;
1097 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001098 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001099 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001100 break;
1101 }
1102 }
1103
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001104 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001105 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001106 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001107
Daniel Jasper8369aa52013-07-16 20:28:33 +00001108 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001109 }
Manuel Klimekef920692013-01-07 07:56:50 +00001110
Manuel Klimek1abf7892013-01-04 23:34:14 +00001111 // In case the token starts with escaped newlines, we want to
1112 // take them into account as whitespace - this pattern is quite frequent
1113 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001114 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001115 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1116 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001117 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001118 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001119 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001120 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001121 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001122 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001123
1124 FormatTok->WhitespaceRange = SourceRange(
1125 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1126
Manuel Klimek31c85922013-08-29 15:21:40 +00001127 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001128
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001129 TrailingWhitespace = 0;
1130 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001131 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001132 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001133 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001134 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001135 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001136 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001137 FormatTok->Tok.setIdentifierInfo(&Info);
1138 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001139 if (Style.Language == FormatStyle::LK_Java &&
1140 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1141 FormatTok->Tok.setKind(tok::identifier);
1142 FormatTok->Tok.setIdentifierInfo(nullptr);
1143 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001144 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001145 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001146 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001147 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001148 } else if (FormatTok->Tok.is(tok::lessless)) {
1149 FormatTok->Tok.setKind(tok::less);
1150 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1151 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001152 }
1153
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001154 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001155
Alexander Kornienko39856b72013-09-10 09:38:25 +00001156 StringRef Text = FormatTok->TokenText;
1157 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001158 if (FirstNewlinePos == StringRef::npos) {
1159 // FIXME: ColumnWidth actually depends on the start column, we need to
1160 // take this into account when the token is moved.
1161 FormatTok->ColumnWidth =
1162 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1163 Column += FormatTok->ColumnWidth;
1164 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001165 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001166 // FIXME: ColumnWidth actually depends on the start column, we need to
1167 // take this into account when the token is moved.
1168 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1169 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1170
Alexander Kornienko39856b72013-09-10 09:38:25 +00001171 // The last line of the token always starts in column 0.
1172 // Thus, the length can be precomputed even in the presence of tabs.
1173 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1174 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1175 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001176 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001177 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001178
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001179 if (Style.Language == FormatStyle::LK_Cpp) {
1180 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1181 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1182 tok::pp_define) &&
1183 std::find(ForEachMacros.begin(), ForEachMacros.end(),
1184 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1185 FormatTok->Type = TT_ForEachMacro;
1186 } else if (FormatTok->is(tok::identifier)) {
1187 if (MacroBlockBeginRegex.match(Text)) {
1188 FormatTok->Type = TT_MacroBlockBegin;
1189 } else if (MacroBlockEndRegex.match(Text)) {
1190 FormatTok->Type = TT_MacroBlockEnd;
1191 }
1192 }
1193 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001194
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001195 return FormatTok;
1196 }
1197
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001198 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001199 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001200 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001201 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001202 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001203 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001204 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001205 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001206 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001207 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001208 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001209 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001210 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001211 // Index (in 'Tokens') of the last token that starts a new line.
1212 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001213 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001214 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001215
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001216 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001217
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001218 llvm::Regex MacroBlockBeginRegex;
1219 llvm::Regex MacroBlockEndRegex;
1220
Daniel Jasper8369aa52013-07-16 20:28:33 +00001221 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001222 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001223 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1224 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001225 // For formatting, treat unterminated string literals like normal string
1226 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001227 if (Tok.is(tok::unknown)) {
1228 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1229 Tok.Tok.setKind(tok::string_literal);
1230 Tok.IsUnterminatedLiteral = true;
1231 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1232 Tok.TokenText == "''") {
1233 Tok.Tok.setKind(tok::char_constant);
1234 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001235 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001236
1237 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1238 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001239 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001240 }
1241
Daniel Jasper471894432014-08-06 13:40:26 +00001242 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001243
1244 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1245 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001246 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001247 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001248 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001249
1250 void resetLexer(unsigned Offset) {
1251 StringRef Buffer = SourceMgr.getBufferData(ID);
1252 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1253 getFormattingLangOpts(Style), Buffer.begin(),
1254 Buffer.begin() + Offset, Buffer.end()));
1255 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001256 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001257 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001258};
1259
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001260static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1261 switch (Language) {
1262 case FormatStyle::LK_Cpp:
1263 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001264 case FormatStyle::LK_Java:
1265 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001266 case FormatStyle::LK_JavaScript:
1267 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001268 case FormatStyle::LK_Proto:
1269 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001270 default:
1271 return "Unknown";
1272 }
1273}
1274
Daniel Jasperf7935112012-12-03 18:12:45 +00001275class Formatter : public UnwrappedLineConsumer {
1276public:
Daniel Jasper23376252014-09-09 14:37:39 +00001277 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001278 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001279 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1280 Whitespaces(SourceMgr, Style,
1281 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001282 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001283 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001284 DEBUG(llvm::dbgs() << "File encoding: "
1285 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1286 : "unknown")
1287 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001288 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1289 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001290 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001291
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001292 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001293 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001294 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001295
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001296 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1297 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001298 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001299 assert(UnwrappedLines.rbegin()->empty());
1300 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1301 ++Run) {
1302 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1303 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1304 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1305 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1306 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001307 tooling::Replacements RunResult =
1308 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001309 DEBUG({
1310 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1311 for (tooling::Replacements::iterator I = RunResult.begin(),
1312 E = RunResult.end();
1313 I != E; ++I) {
1314 llvm::dbgs() << I->toString() << "\n";
1315 }
1316 });
1317 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1318 delete AnnotatedLines[i];
1319 }
1320 Result.insert(RunResult.begin(), RunResult.end());
1321 Whitespaces.reset();
1322 }
1323 return Result;
1324 }
1325
1326 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001327 FormatTokenLexer &Tokens,
1328 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001329 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001330 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001331 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001332 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001333 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001334 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001335 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001336 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001337 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001338
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001339 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001340 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1341 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001342 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001343 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1344 IncompleteFormat)
1345 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001346 return Whitespaces.generateReplacements();
1347 }
1348
1349private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001350 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001351 // Returns \c true if at least one line between I and E or one of their
1352 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001353 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1354 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1355 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001356 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001357 while (I != E) {
1358 AnnotatedLine *Line = *I;
1359 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1360
1361 // If a line is part of a preprocessor directive, it needs to be formatted
1362 // if any token within the directive is affected.
1363 if (Line->InPPDirective) {
1364 FormatToken *Last = Line->Last;
1365 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1366 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1367 Last = (*PPEnd)->Last;
1368 ++PPEnd;
1369 }
1370
1371 if (affectsTokenRange(*Line->First, *Last,
1372 /*IncludeLeadingNewlines=*/false)) {
1373 SomeLineAffected = true;
1374 markAllAsAffected(I, PPEnd);
1375 }
1376 I = PPEnd;
1377 continue;
1378 }
1379
Daniel Jasper38c82402013-11-29 09:27:43 +00001380 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001381 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001382
Daniel Jasper38c82402013-11-29 09:27:43 +00001383 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001384 ++I;
1385 }
1386 return SomeLineAffected;
1387 }
1388
Daniel Jasper9c199562013-11-28 15:58:55 +00001389 // Determines whether 'Line' is affected by the SourceRanges given as input.
1390 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001391 bool nonPPLineAffected(AnnotatedLine *Line,
1392 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001393 bool SomeLineAffected = false;
1394 Line->ChildrenAffected =
1395 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1396 if (Line->ChildrenAffected)
1397 SomeLineAffected = true;
1398
1399 // Stores whether one of the line's tokens is directly affected.
1400 bool SomeTokenAffected = false;
1401 // Stores whether we need to look at the leading newlines of the next token
1402 // in order to determine whether it was affected.
1403 bool IncludeLeadingNewlines = false;
1404
1405 // Stores whether the first child line of any of this line's tokens is
1406 // affected.
1407 bool SomeFirstChildAffected = false;
1408
1409 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1410 // Determine whether 'Tok' was affected.
1411 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1412 SomeTokenAffected = true;
1413
1414 // Determine whether the first child of 'Tok' was affected.
1415 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1416 SomeFirstChildAffected = true;
1417
1418 IncludeLeadingNewlines = Tok->Children.empty();
1419 }
1420
1421 // Was this line moved, i.e. has it previously been on the same line as an
1422 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001423 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1424 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001425
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001426 bool IsContinuedComment =
1427 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1428 Line->First->NewlinesBefore < 2 && PreviousLine &&
1429 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001430
1431 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1432 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001433 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001434 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001435 }
1436 return SomeLineAffected;
1437 }
1438
Daniel Jasper5500f612013-11-25 11:08:59 +00001439 // Marks all lines between I and E as well as all their children as affected.
1440 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1441 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1442 while (I != E) {
1443 (*I)->Affected = true;
1444 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1445 ++I;
1446 }
1447 }
1448
1449 // Returns true if the range from 'First' to 'Last' intersects with one of the
1450 // input ranges.
1451 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1452 bool IncludeLeadingNewlines) {
1453 SourceLocation Start = First.WhitespaceRange.getBegin();
1454 if (!IncludeLeadingNewlines)
1455 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001456 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001457 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001458 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1459 return affectsCharSourceRange(Range);
1460 }
1461
1462 // Returns true if one of the input ranges intersect the leading empty lines
1463 // before 'Tok'.
1464 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1465 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1466 Tok.WhitespaceRange.getBegin(),
1467 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1468 return affectsCharSourceRange(EmptyLineRange);
1469 }
1470
1471 // Returns true if 'Range' intersects with one of the input ranges.
1472 bool affectsCharSourceRange(const CharSourceRange &Range) {
1473 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1474 E = Ranges.end();
1475 I != E; ++I) {
1476 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1477 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1478 return true;
1479 }
1480 return false;
1481 }
1482
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001483 static bool inputUsesCRLF(StringRef Text) {
1484 return Text.count('\r') * 2 > Text.count('\n');
1485 }
1486
Daniel Jasper352f0df2015-07-18 16:35:30 +00001487 bool
1488 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1489 for (const AnnotatedLine* Line : Lines) {
1490 if (hasCpp03IncompatibleFormat(Line->Children))
1491 return true;
1492 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1493 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1494 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1495 return true;
1496 if (Tok->is(TT_TemplateCloser) &&
1497 Tok->Previous->is(TT_TemplateCloser))
1498 return true;
1499 }
1500 }
1501 }
1502 return false;
1503 }
1504
1505 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1506 int AlignmentDiff = 0;
1507 for (const AnnotatedLine* Line : Lines) {
1508 AlignmentDiff += countVariableAlignments(Line->Children);
1509 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1510 if (!Tok->is(TT_PointerOrReference))
1511 continue;
1512 bool SpaceBefore =
1513 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1514 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1515 Tok->Next->WhitespaceRange.getEnd();
1516 if (SpaceBefore && !SpaceAfter)
1517 ++AlignmentDiff;
1518 if (!SpaceBefore && SpaceAfter)
1519 --AlignmentDiff;
1520 }
1521 }
1522 return AlignmentDiff;
1523 }
1524
Manuel Klimek71814b42013-10-11 21:25:45 +00001525 void
1526 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001527 bool HasBinPackedFunction = false;
1528 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001529 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001530 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001531 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001532 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001533 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001534 if (Tok->PackingKind == PPK_BinPacked)
1535 HasBinPackedFunction = true;
1536 if (Tok->PackingKind == PPK_OnePerLine)
1537 HasOnePerLineFunction = true;
1538
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001539 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001540 }
1541 }
Daniel Jasper352f0df2015-07-18 16:35:30 +00001542 if (Style.DerivePointerAlignment)
1543 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1544 ? FormatStyle::PAS_Left
1545 : FormatStyle::PAS_Right;
1546 if (Style.Standard == FormatStyle::LS_Auto)
1547 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1548 ? FormatStyle::LS_Cpp11
1549 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001550 BinPackInconclusiveFunctions =
1551 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001552 }
1553
Craig Topperfb6b25b2014-03-15 04:29:04 +00001554 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001555 assert(!UnwrappedLines.empty());
1556 UnwrappedLines.back().push_back(TheLine);
1557 }
1558
Craig Topperfb6b25b2014-03-15 04:29:04 +00001559 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001560 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001561 }
1562
1563 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001564 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001565 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001566 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001567 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001568 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001569
1570 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001571 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001572};
1573
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001574struct IncludeDirective {
1575 StringRef Filename;
1576 StringRef Text;
1577 unsigned Offset;
1578 bool IsAngled;
1579};
1580
Craig Topperaf35e852013-06-30 22:29:28 +00001581} // end anonymous namespace
1582
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001583// Determines whether 'Ranges' intersects with ('Start', 'End').
1584static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1585 unsigned End) {
1586 for (auto Range : Ranges) {
1587 if (Range.getOffset() < End &&
1588 Range.getOffset() + Range.getLength() > Start)
1589 return true;
1590 }
1591 return false;
1592}
1593
1594// Sorts a block of includes given by 'Includes' alphabetically adding the
1595// necessary replacement to 'Replaces'. 'Includes' must be in strict source
1596// order.
1597static void sortIncludes(const FormatStyle &Style,
1598 const SmallVectorImpl<IncludeDirective> &Includes,
1599 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1600 tooling::Replacements &Replaces) {
1601 if (!affectsRange(Ranges, Includes.front().Offset,
1602 Includes.back().Offset + Includes.back().Text.size()))
1603 return;
1604 SmallVector<unsigned, 16> Indices;
1605 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1606 Indices.push_back(i);
1607 std::sort(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1608 return Includes[LHSI].Filename < Includes[RHSI].Filename;
1609 });
1610
1611 // If the #includes are out of order, we generate a single replacement fixing
1612 // the entire block. Otherwise, no replacement is generated.
1613 bool OutOfOrder = false;
1614 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1615 if (Indices[i] != i) {
1616 OutOfOrder = true;
1617 break;
1618 }
1619 }
1620 if (!OutOfOrder)
1621 return;
1622
1623 std::string result = Includes[Indices[0]].Text;
1624 for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1625 result += "\n";
1626 result += Includes[Indices[i]].Text;
1627 }
1628
1629 // Sorting #includes shouldn't change their total number of characters.
1630 // This would otherwise mess up 'Ranges'.
1631 assert(result.size() ==
1632 Includes.back().Offset + Includes.back().Text.size() -
1633 Includes.front().Offset);
1634
1635 Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1636 result.size(), result));
1637}
1638
1639tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1640 ArrayRef<tooling::Range> Ranges,
1641 StringRef FileName) {
1642 tooling::Replacements Replaces;
1643 unsigned Prev = 0;
1644 unsigned SearchFrom = 0;
1645 llvm::Regex IncludeRegex(R"(^[\t\ ]*#[\t\ ]*include[^"<]*["<]([^">]*)([">]))");
1646 SmallVector<StringRef, 4> Matches;
1647 SmallVector<IncludeDirective, 16> IncludesInBlock;
1648 for (;;) {
1649 auto Pos = Code.find('\n', SearchFrom);
1650 StringRef Line =
1651 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1652 if (!Line.endswith("\\")) {
1653 if (IncludeRegex.match(Line, &Matches)) {
1654 bool IsAngled = Matches[2] == ">";
1655 if (!IncludesInBlock.empty() &&
1656 IsAngled != IncludesInBlock.back().IsAngled) {
1657 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1658 IncludesInBlock.clear();
1659 }
1660 IncludesInBlock.push_back({Matches[1], Line, Prev, Matches[2] == ">"});
1661 } else if (!IncludesInBlock.empty()) {
1662 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1663 IncludesInBlock.clear();
1664 }
1665 Prev = Pos + 1;
1666 }
1667 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1668 break;
1669 SearchFrom = Pos + 1;
1670 }
1671 if (!IncludesInBlock.empty())
1672 sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
1673 return Replaces;
1674}
1675
Daniel Jasper23376252014-09-09 14:37:39 +00001676tooling::Replacements reformat(const FormatStyle &Style,
1677 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001678 ArrayRef<CharSourceRange> Ranges,
1679 bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001680 if (Style.DisableFormat)
1681 return tooling::Replacements();
1682 Formatter formatter(Style, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001683 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001684}
1685
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001686tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001687 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001688 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001689 if (Style.DisableFormat)
1690 return tooling::Replacements();
1691
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001692 FileManager Files((FileSystemOptions()));
1693 DiagnosticsEngine Diagnostics(
1694 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1695 new DiagnosticOptions);
1696 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001697 std::unique_ptr<llvm::MemoryBuffer> Buf =
1698 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001699 const clang::FileEntry *Entry =
1700 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001701 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001702 FileID ID =
1703 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001704 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1705 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001706 for (const tooling::Range &Range : Ranges) {
1707 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1708 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001709 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1710 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001711 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001712}
1713
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001714LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001715 LangOptions LangOpts;
1716 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001717 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1718 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001719 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001720 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001721 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001722 LangOpts.Bool = 1;
1723 LangOpts.ObjC1 = 1;
1724 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001725 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001726 return LangOpts;
1727}
1728
Edwin Vaned544aa72013-09-30 13:31:48 +00001729const char *StyleOptionHelpDescription =
1730 "Coding style, currently supports:\n"
1731 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1732 "Use -style=file to load style configuration from\n"
1733 ".clang-format file located in one of the parent\n"
1734 "directories of the source file (or current\n"
1735 "directory for stdin).\n"
1736 "Use -style=\"{key: value, ...}\" to set specific\n"
1737 "parameters, e.g.:\n"
1738 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1739
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001740static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001741 if (FileName.endswith(".java")) {
1742 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001743 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1744 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001745 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001746 } else if (FileName.endswith_lower(".proto") ||
1747 FileName.endswith_lower(".protodevel")) {
1748 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001749 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001750 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001751}
1752
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001753FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1754 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001755 FormatStyle Style = getLLVMStyle();
1756 Style.Language = getLanguageByFileName(FileName);
1757 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001758 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1759 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001760 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001761 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001762
1763 if (StyleName.startswith("{")) {
1764 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001765 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001766 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1767 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001768 }
1769 return Style;
1770 }
1771
1772 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001773 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001774 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1775 << " style\n";
1776 return Style;
1777 }
1778
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001779 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001780 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001781 SmallString<128> Path(FileName);
1782 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001783 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001784 Directory = llvm::sys::path::parent_path(Directory)) {
1785 if (!llvm::sys::fs::is_directory(Directory))
1786 continue;
1787 SmallString<128> ConfigFile(Directory);
1788
1789 llvm::sys::path::append(ConfigFile, ".clang-format");
1790 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1791 bool IsFile = false;
1792 // Ignore errors from is_regular_file: we only need to know if we can read
1793 // the file or not.
1794 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1795
1796 if (!IsFile) {
1797 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1798 ConfigFile = Directory;
1799 llvm::sys::path::append(ConfigFile, "_clang-format");
1800 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1801 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1802 }
1803
1804 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001805 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1806 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1807 if (std::error_code EC = Text.getError()) {
1808 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001809 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001810 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001811 if (std::error_code ec =
1812 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001813 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001814 if (!UnsuitableConfigFiles.empty())
1815 UnsuitableConfigFiles.append(", ");
1816 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001817 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001818 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001819 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1820 << "\n";
1821 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001822 }
1823 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1824 return Style;
1825 }
1826 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001827 if (!UnsuitableConfigFiles.empty()) {
1828 llvm::errs() << "Configuration file(s) do(es) not support "
1829 << getLanguageName(Style.Language) << ": "
1830 << UnsuitableConfigFiles << "\n";
1831 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001832 return Style;
1833}
1834
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001835} // namespace format
1836} // namespace clang