blob: 2bbe4c63d156782bb7a21b968d2aadf83e75759f [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Chandler Carruth10346662014-04-22 03:17:02 +000034#define DEBUG_TYPE "format-formatter"
35
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000036using clang::format::FormatStyle;
37
Daniel Jaspere1e43192014-04-01 12:55:11 +000038LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
39
Alexander Kornienkod6538332013-05-07 15:32:14 +000040namespace llvm {
41namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000042template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
43 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
44 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000045 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000047 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000048 }
49};
50
51template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
52 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
53 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
55 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
57 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
58 }
59};
60
61template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
62 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
63 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
64 IO.enumCase(Value, "false", FormatStyle::UT_Never);
65 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
66 IO.enumCase(Value, "true", FormatStyle::UT_Always);
67 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
68 }
69};
70
Daniel Jasperd74cf402014-04-08 12:46:38 +000071template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
72 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
73 IO.enumCase(Value, "None", FormatStyle::SFS_None);
74 IO.enumCase(Value, "false", FormatStyle::SFS_None);
75 IO.enumCase(Value, "All", FormatStyle::SFS_All);
76 IO.enumCase(Value, "true", FormatStyle::SFS_All);
77 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000078 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000079 }
80};
81
Daniel Jasperac043c92014-09-15 11:11:00 +000082template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
83 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
84 IO.enumCase(Value, "All", FormatStyle::BOS_All);
85 IO.enumCase(Value, "true", FormatStyle::BOS_All);
86 IO.enumCase(Value, "None", FormatStyle::BOS_None);
87 IO.enumCase(Value, "false", FormatStyle::BOS_None);
88 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
89 }
90};
91
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
93 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
94 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
95 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
96 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
97 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000098 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099 }
100};
101
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000102template <> struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
103 static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
104 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
105 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
106 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
107
108 // For backward compatibility.
109 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
110 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
111 }
112};
113
Alexander Kornienkod6538332013-05-07 15:32:14 +0000114template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000115struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000116 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000117 FormatStyle::NamespaceIndentationKind &Value) {
118 IO.enumCase(Value, "None", FormatStyle::NI_None);
119 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
120 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000121 }
122};
123
Jacques Pienaarfc275112015-02-18 23:48:37 +0000124template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
125 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000126 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
127 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
128 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
129
Alp Toker958027b2014-07-14 19:42:55 +0000130 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000131 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
132 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
133 }
134};
135
136template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000137struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000138 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139 FormatStyle::SpaceBeforeParensOptions &Value) {
140 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000141 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000142 FormatStyle::SBPO_ControlStatements);
143 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000144
145 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000146 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
147 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000148 }
149};
150
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000151template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000152 static void mapping(IO &IO, FormatStyle &Style) {
153 // When reading, read the language first, we need it for getPredefinedStyle.
154 IO.mapOptional("Language", Style.Language);
155
Alexander Kornienko49149672013-05-10 11:56:10 +0000156 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000157 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
158 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000159 ArrayRef<StringRef> Styles(StylesArray);
160 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
161 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000162 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000163 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000164 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000165 IO.mapOptional("# BasedOnStyle", StyleName);
166 break;
167 }
168 }
169 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 StringRef BasedOnStyle;
171 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000172 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000173 FormatStyle::LanguageKind OldLanguage = Style.Language;
174 FormatStyle::LanguageKind Language =
175 ((FormatStyle *)IO.getContext())->Language;
176 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000177 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
178 return;
179 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000180 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000181 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000182 }
183
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000184 // For backward compatibility.
185 if (!IO.outputting()) {
186 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
187 IO.mapOptional("IndentFunctionDeclarationAfterType",
188 Style.IndentWrappedFunctionNames);
189 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
190 IO.mapOptional("SpaceAfterControlStatementKeyword",
191 Style.SpaceBeforeParens);
192 }
193
Alexander Kornienkod6538332013-05-07 15:32:14 +0000194 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000195 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000196 IO.mapOptional("AlignConsecutiveAssignments",
197 Style.AlignConsecutiveAssignments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000198 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000199 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000200 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
202 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000203 IO.mapOptional("AllowShortBlocksOnASingleLine",
204 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000205 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
206 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000207 IO.mapOptional("AllowShortFunctionsOnASingleLine",
208 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000209 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
210 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000211 IO.mapOptional("AllowShortLoopsOnASingleLine",
212 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000213 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
214 Style.AlwaysBreakAfterDefinitionReturnType);
Alexander Kornienko58611712013-07-04 12:02:44 +0000215 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
216 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000217 IO.mapOptional("AlwaysBreakTemplateDeclarations",
218 Style.AlwaysBreakTemplateDeclarations);
219 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
220 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000221 IO.mapOptional("BreakBeforeBinaryOperators",
222 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000223 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000224 IO.mapOptional("BreakBeforeTernaryOperators",
225 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000226 IO.mapOptional("BreakConstructorInitializersBeforeComma",
227 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000228 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000229 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000230 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
231 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000232 IO.mapOptional("ConstructorInitializerIndentWidth",
233 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000234 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
235 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000236 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000237 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000238 IO.mapOptional("ExperimentalAutoDetectBinPacking",
239 Style.ExperimentalAutoDetectBinPacking);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000240 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000241 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000242 IO.mapOptional("IndentWidth", Style.IndentWidth);
243 IO.mapOptional("IndentWrappedFunctionNames",
244 Style.IndentWrappedFunctionNames);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000245 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
246 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000247 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000248 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000249 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000250 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000251 IO.mapOptional("ObjCSpaceBeforeProtocolList",
252 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000253 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
254 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000255 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000256 IO.mapOptional("PenaltyBreakFirstLessLess",
257 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000258 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000259 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
260 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
261 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000262 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000263 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000264 IO.mapOptional("SpaceBeforeAssignmentOperators",
265 Style.SpaceBeforeAssignmentOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000266 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
267 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
268 IO.mapOptional("SpacesBeforeTrailingComments",
269 Style.SpacesBeforeTrailingComments);
270 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
271 IO.mapOptional("SpacesInContainerLiterals",
272 Style.SpacesInContainerLiterals);
273 IO.mapOptional("SpacesInCStyleCastParentheses",
274 Style.SpacesInCStyleCastParentheses);
275 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
276 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
277 IO.mapOptional("Standard", Style.Standard);
278 IO.mapOptional("TabWidth", Style.TabWidth);
279 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000280 }
281};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000282
283// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000284// IO.getContext() should contain a pointer to the FormatStyle structure, that
285// will be used to get default values for missing keys.
286// If the first element has no Language specified, it will be treated as the
287// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000288template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000289 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
290 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000291 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000292 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000293 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000294 if (Index >= Seq.size()) {
295 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000296 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000297 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000298 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000299 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000300 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000301 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000302 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000303 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000304 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000305 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000306 }
307};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000308}
309}
Alexander Kornienkod6538332013-05-07 15:32:14 +0000310
Daniel Jasperf7935112012-12-03 18:12:45 +0000311namespace clang {
312namespace format {
313
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000314const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000315 static ParseErrorCategory C;
316 return C;
317}
318std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000319 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000320}
321
322const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
323 return "clang-format.parse_error";
324}
325
326std::string ParseErrorCategory::message(int EV) const {
327 switch (static_cast<ParseError>(EV)) {
328 case ParseError::Success:
329 return "Success";
330 case ParseError::Error:
331 return "Invalid argument";
332 case ParseError::Unsuitable:
333 return "Unsuitable";
334 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000335 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000336}
337
Daniel Jasperf7935112012-12-03 18:12:45 +0000338FormatStyle getLLVMStyle() {
339 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000340 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000341 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000342 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000343 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000344 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000345 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000346 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000347 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000348 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000349 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000350 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000351 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000352 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000353 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000354 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000355 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000356 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000357 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000358 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000359 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000360 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
361 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000362 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000363 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000364 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000365 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000366 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000367 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000368 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000369 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000370 LLVMStyle.ForEachMacros.push_back("foreach");
371 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
372 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000373 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000374 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000375 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000376 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000377 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000378 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000379 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000380 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000381 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000382 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000383 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000384 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000385 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000386 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000387 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000388 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000389 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000390 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000391 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000392 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000393 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000394 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000395 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000396
Daniel Jasper19a541e2013-12-19 16:45:34 +0000397 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000398 LLVMStyle.PenaltyBreakFirstLessLess = 120;
399 LLVMStyle.PenaltyBreakString = 1000;
400 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000401 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000402 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000403
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000404 LLVMStyle.DisableFormat = false;
405
Daniel Jasperf7935112012-12-03 18:12:45 +0000406 return LLVMStyle;
407}
408
Nico Weber514ecc82014-02-02 20:50:45 +0000409FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000410 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000411 GoogleStyle.Language = Language;
412
Daniel Jasperf7935112012-12-03 18:12:45 +0000413 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000414 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000415 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000416 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000417 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000418 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000419 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000420 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000421 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000422 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000423 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000424 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000425 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000426 GoogleStyle.SpacesBeforeTrailingComments = 2;
427 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000428
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000429 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000430 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000431
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000432 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000433 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000434 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000435 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000436 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000437 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000438 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000439 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
440 GoogleStyle.ColumnLimit = 100;
441 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000442 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000443 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000444 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000445 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000446 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000447 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000448 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000449 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000450 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000451 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000452 }
453
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 return GoogleStyle;
455}
456
Nico Weber514ecc82014-02-02 20:50:45 +0000457FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
458 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000459 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000460 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000461 ChromiumStyle.IndentWidth = 4;
462 ChromiumStyle.ContinuationIndentWidth = 8;
463 } else {
464 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
465 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
466 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
467 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
468 ChromiumStyle.BinPackParameters = false;
469 ChromiumStyle.DerivePointerAlignment = false;
470 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000471 return ChromiumStyle;
472}
473
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000474FormatStyle getMozillaStyle() {
475 FormatStyle MozillaStyle = getLLVMStyle();
476 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000477 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000478 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
479 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000480 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
481 MozillaStyle.BreakConstructorInitializersBeforeComma = true;
482 MozillaStyle.ConstructorInitializerIndentWidth = 2;
483 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000484 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000485 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000486 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000487 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
488 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000489 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000490 return MozillaStyle;
491}
492
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000493FormatStyle getWebKitStyle() {
494 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000495 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000496 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000497 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000498 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000499 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000500 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000501 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000502 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000503 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000504 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000505 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000506 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000507 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000508 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000509 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000510 return Style;
511}
512
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000513FormatStyle getGNUStyle() {
514 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000515 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Daniel Jasperac043c92014-09-15 11:11:00 +0000516 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000517 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000518 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000519 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000520 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000521 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000522 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000523 return Style;
524}
525
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000526FormatStyle getNoStyle() {
527 FormatStyle NoStyle = getLLVMStyle();
528 NoStyle.DisableFormat = true;
529 return NoStyle;
530}
531
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
533 FormatStyle *Style) {
534 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000535 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000536 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000537 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000538 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000539 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000540 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000541 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000543 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000544 } else if (Name.equals_lower("gnu")) {
545 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000546 } else if (Name.equals_lower("none")) {
547 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000549 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000550 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000551
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000552 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000553 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000554}
555
Rafael Espindolac0809172014-06-12 14:02:15 +0000556std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000557 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 FormatStyle::LanguageKind Language = Style->Language;
559 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000560 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000561 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000562
563 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000564 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000565 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
566 // values for the fields, keys for which are missing from the configuration.
567 // Mapping also uses the context to get the language to find the correct
568 // base style.
569 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000570 Input >> Styles;
571 if (Input.error())
572 return Input.error();
573
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000574 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000575 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000576 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000577 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000578 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000579 for (unsigned j = 0; j < i; ++j) {
580 if (Styles[i].Language == Styles[j].Language) {
581 DEBUG(llvm::dbgs()
582 << "Duplicate languages in the config file on positions " << j
583 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000584 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000585 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000586 }
587 }
588 // Look for a suitable configuration starting from the end, so we can
589 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000590 // configuration (which can only be at slot 0) after it.
591 for (int i = Styles.size() - 1; i >= 0; --i) {
592 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000593 Styles[i].Language == FormatStyle::LK_None) {
594 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000595 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000596 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000597 }
598 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000599 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000600}
601
602std::string configurationAsText(const FormatStyle &Style) {
603 std::string Text;
604 llvm::raw_string_ostream Stream(Text);
605 llvm::yaml::Output Output(Stream);
606 // We use the same mapping method for input and output, so we need a non-const
607 // reference here.
608 FormatStyle NonConstStyle = Style;
609 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000610 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000611}
612
Craig Topperaf35e852013-06-30 22:29:28 +0000613namespace {
614
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000615class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000616public:
Daniel Jasper23376252014-09-09 14:37:39 +0000617 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000618 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000619 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000620 LessStashed(false), Column(0), TrailingWhitespace(0),
621 SourceMgr(SourceMgr), ID(ID), Style(Style),
622 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
623 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +0000624 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
625 getFormattingLangOpts(Style)));
626 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000627
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000628 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000629 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
630 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000631 }
632
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000633 ArrayRef<FormatToken *> lex() {
634 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000635 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000636 do {
637 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000638 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000639 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000640 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000641 } while (Tokens.back()->Tok.isNot(tok::eof));
642 return Tokens;
643 }
644
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000645 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000646
647private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000648 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000649 if (tryMerge_TMacro())
650 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000651 if (tryMergeConflictMarkers())
652 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000653 if (tryMergeLessLess())
654 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000655
656 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000657 if (tryMergeJSRegexLiteral())
658 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000659 if (tryMergeEscapeSequence())
660 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000661 if (tryMergeTemplateString())
662 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000663
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000664 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
665 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
666 tok::equal};
667 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
668 tok::greaterequal};
669 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000670 // FIXME: Investigate what token type gives the correct operator priority.
671 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000672 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000673 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000674 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000675 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000676 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000677 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000678 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000679 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000680 }
681
Jacques Pienaarfc275112015-02-18 23:48:37 +0000682 bool tryMergeLessLess() {
683 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000684 if (Tokens.size() < 3)
685 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000686
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000687 bool FourthTokenIsLess = false;
688 if (Tokens.size() > 3)
689 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000690
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000691 auto First = Tokens.end() - 3;
692 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
693 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000694 return false;
695
696 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000697 if (First[1]->WhitespaceRange.getBegin() !=
698 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000699 return false;
700
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000701 First[0]->Tok.setKind(tok::lessless);
702 First[0]->TokenText = "<<";
703 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000704 Tokens.erase(Tokens.end() - 2);
705 return true;
706 }
707
Manuel Klimek79e06082015-05-21 12:23:34 +0000708 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000709 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000710 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000711
712 SmallVectorImpl<FormatToken *>::const_iterator First =
713 Tokens.end() - Kinds.size();
714 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000715 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000716 unsigned AddLength = 0;
717 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000718 if (!First[i]->is(Kinds[i]) ||
719 First[i]->WhitespaceRange.getBegin() !=
720 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000721 return false;
722 AddLength += First[i]->TokenText.size();
723 }
724 Tokens.resize(Tokens.size() - Kinds.size() + 1);
725 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
726 First[0]->TokenText.size() + AddLength);
727 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000728 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000729 return true;
730 }
731
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000732 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000733 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000734 bool tryMergeEscapeSequence() {
735 if (Tokens.size() < 2)
736 return false;
737 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000738 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000739 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000740 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000741 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000742 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
743 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000744 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000745 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000746 return true;
747 }
748
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000749 // Try to determine whether the current token ends a JavaScript regex literal.
750 // We heuristically assume that this is a regex literal if we find two
751 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000752 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
753 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000754 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000755 if (Tokens.size() < 2)
756 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000757
758 // If this is a string literal with a slash inside, compute the slash's
759 // offset and try to find the beginning of the regex literal.
760 // Also look at tok::unknown, as it can be an unterminated char literal.
761 size_t SlashInStringPos = StringRef::npos;
762 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
763 tok::unknown)) {
764 // Start search from position 1 as otherwise, this is an unknown token
765 // for an unterminated /*-comment which is handled elsewhere.
766 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
767 if (SlashInStringPos == StringRef::npos)
768 return false;
769 }
770
Daniel Jasper23376252014-09-09 14:37:39 +0000771 // If a regex literal ends in "\//", this gets represented by an unknown
772 // token "\" and a comment.
773 bool MightEndWithEscapedSlash =
774 Tokens.back()->is(tok::comment) &&
775 Tokens.back()->TokenText.startswith("//") &&
776 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000777 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000778 (Tokens.back()->isNot(tok::slash) ||
779 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
780 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000781 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000782
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000783 unsigned TokenCount = 0;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000784 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
785 ++TokenCount;
Daniel Jasperf7372152015-07-02 14:14:04 +0000786 auto Prev = I + 1;
787 while (Prev != E && Prev[0]->is(tok::comment))
788 ++Prev;
Daniel Jasperc553ae12015-07-02 13:20:45 +0000789 if (I[0]->isOneOf(tok::slash, tok::slashequal) &&
Daniel Jasperf7372152015-07-02 14:14:04 +0000790 (Prev == E ||
791 ((Prev[0]->isOneOf(tok::l_paren, tok::semi, tok::l_brace,
792 tok::r_brace, tok::exclaim, tok::l_square,
793 tok::colon, tok::comma, tok::question,
794 tok::kw_return) ||
795 Prev[0]->isBinaryOperator())))) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000796 unsigned LastColumn = Tokens.back()->OriginalColumn;
797 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000798 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000799 // This regex literal ends in '\//'. Skip past the '//' of the last
800 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000801 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000802 } else if (SlashInStringPos != StringRef::npos) {
803 // This regex literal ends in a string_literal with a slash inside.
804 // Calculate end column and reset lexer appropriately.
805 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
806 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000807 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000808 Tokens.resize(Tokens.size() - TokenCount);
809 Tokens.back()->Tok.setKind(tok::unknown);
810 Tokens.back()->Type = TT_RegexLiteral;
Daniel Jasperf1446202015-07-02 15:00:44 +0000811 // Treat regex literals like other string_literals.
812 Tokens.back()->Tok.setKind(tok::string_literal);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000813 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
814 return true;
815 }
816
817 // There can't be a newline inside a regex literal.
818 if (I[0]->NewlinesBefore > 0)
819 return false;
820 }
821 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000822 }
823
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000824 bool tryMergeTemplateString() {
825 if (Tokens.size() < 2)
826 return false;
827
828 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000829 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000830 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
831 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000832 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
833 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000834 return false;
835 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
836 // Unknown token that's not actually a backtick, or a comment that doesn't
837 // contain a backtick.
838 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000839 return false;
840
841 unsigned TokenCount = 0;
842 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000843 unsigned EndColumnInFirstLine =
844 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000845 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
846 ++TokenCount;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000847 if (I[0]->IsMultiline)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000848 IsMultiline = true;
849
850 // If there was a preceding template string, this must be the start of a
851 // template string, not the end.
852 if (I[0]->is(TT_TemplateString))
853 return false;
854
855 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
856 // Keep track of the rhs offset of the last token to wrap across lines -
857 // its the rhs offset of the first line of the template string, used to
858 // determine its width.
859 if (I[0]->IsMultiline)
860 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
861 // If the token has newlines, the token before it (if it exists) is the
862 // rhs end of the previous line.
Daniel Jasper553a5b02015-07-02 13:08:28 +0000863 if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000864 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000865 IsMultiline = true;
866 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000867 continue;
868 }
869
870 Tokens.resize(Tokens.size() - TokenCount);
871 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000872 const char *EndOffset =
873 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
874 if (CommentBacktickPos != 0) {
875 // If the backtick was not the first character (e.g. in a comment),
876 // re-lex after the backtick position.
877 SourceLocation Loc = EndBacktick->Tok.getLocation();
878 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
879 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000880 Tokens.back()->TokenText =
881 StringRef(Tokens.back()->TokenText.data(),
882 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000883
884 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
885 if (EndOriginalColumn == 0) {
886 SourceLocation Loc = EndBacktick->Tok.getLocation();
887 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
888 }
889 // If the ` is further down within the token (e.g. in a comment).
890 EndOriginalColumn += CommentBacktickPos;
891
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000892 if (IsMultiline) {
893 // ColumnWidth is from backtick to last token in line.
894 // LastLineColumnWidth is 0 to backtick.
895 // x = `some content
896 // until here`;
897 Tokens.back()->ColumnWidth =
898 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasper553a5b02015-07-02 13:08:28 +0000899 // +1 for the ` itself.
900 Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000901 Tokens.back()->IsMultiline = true;
902 } else {
903 // Token simply spans from start to end, +1 for the ` itself.
904 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000905 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000906 }
907 return true;
908 }
909 return false;
910 }
911
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000912 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000913 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000914 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000915 FormatToken *Last = Tokens.back();
916 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000917 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000918
919 FormatToken *String = Tokens[Tokens.size() - 2];
920 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000921 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000922
923 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000924 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000925
926 FormatToken *Macro = Tokens[Tokens.size() - 4];
927 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000928 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000929
930 const char *Start = Macro->TokenText.data();
931 const char *End = Last->TokenText.data() + Last->TokenText.size();
932 String->TokenText = StringRef(Start, End - Start);
933 String->IsFirst = Macro->IsFirst;
934 String->LastNewlineOffset = Macro->LastNewlineOffset;
935 String->WhitespaceRange = Macro->WhitespaceRange;
936 String->OriginalColumn = Macro->OriginalColumn;
937 String->ColumnWidth = encoding::columnWidthWithTabs(
938 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +0000939 String->NewlinesBefore = Macro->NewlinesBefore;
940 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000941
942 Tokens.pop_back();
943 Tokens.pop_back();
944 Tokens.pop_back();
945 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000946 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000947 }
948
Manuel Klimek68b03042014-04-14 09:14:11 +0000949 bool tryMergeConflictMarkers() {
950 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
951 return false;
952
953 // Conflict lines look like:
954 // <marker> <text from the vcs>
955 // For example:
956 // >>>>>>> /file/in/file/system at revision 1234
957 //
958 // We merge all tokens in a line that starts with a conflict marker
959 // into a single token with a special token type that the unwrapped line
960 // parser will use to correctly rebuild the underlying code.
961
962 FileID ID;
963 // Get the position of the first token in the line.
964 unsigned FirstInLineOffset;
965 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
966 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
967 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
968 // Calculate the offset of the start of the current line.
969 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
970 if (LineOffset == StringRef::npos) {
971 LineOffset = 0;
972 } else {
973 ++LineOffset;
974 }
975
976 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
977 StringRef LineStart;
978 if (FirstSpace == StringRef::npos) {
979 LineStart = Buffer.substr(LineOffset);
980 } else {
981 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
982 }
983
984 TokenType Type = TT_Unknown;
985 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
986 Type = TT_ConflictStart;
987 } else if (LineStart == "|||||||" || LineStart == "=======" ||
988 LineStart == "====") {
989 Type = TT_ConflictAlternative;
990 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
991 Type = TT_ConflictEnd;
992 }
993
994 if (Type != TT_Unknown) {
995 FormatToken *Next = Tokens.back();
996
997 Tokens.resize(FirstInLineIndex + 1);
998 // We do not need to build a complete token here, as we will skip it
999 // during parsing anyway (as we must not touch whitespace around conflict
1000 // markers).
1001 Tokens.back()->Type = Type;
1002 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1003
1004 Tokens.push_back(Next);
1005 return true;
1006 }
1007
1008 return false;
1009 }
1010
Jacques Pienaarfc275112015-02-18 23:48:37 +00001011 FormatToken *getStashedToken() {
1012 // Create a synthesized second '>' or '<' token.
1013 Token Tok = FormatTok->Tok;
1014 StringRef TokenText = FormatTok->TokenText;
1015
1016 unsigned OriginalColumn = FormatTok->OriginalColumn;
1017 FormatTok = new (Allocator.Allocate()) FormatToken;
1018 FormatTok->Tok = Tok;
1019 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +00001020 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1021 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +00001022 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1023 FormatTok->TokenText = TokenText;
1024 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001025 FormatTok->OriginalColumn = OriginalColumn + 1;
1026
Jacques Pienaarfc275112015-02-18 23:48:37 +00001027 return FormatTok;
1028 }
1029
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001030 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001031 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001032 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001033 return getStashedToken();
1034 }
1035 if (LessStashed) {
1036 LessStashed = false;
1037 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001038 }
1039
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001040 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001041 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001042 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001043 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001044 FormatTok->IsFirst = IsFirstToken;
1045 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001046
1047 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001048 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001049 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001050 StringRef Text = FormatTok->TokenText;
1051 auto EscapesNewline = [&](int pos) {
1052 // A '\r' here is just part of '\r\n'. Skip it.
1053 if (pos >= 0 && Text[pos] == '\r')
1054 --pos;
1055 // See whether there is an odd number of '\' before this.
1056 unsigned count = 0;
1057 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001058 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001059 break;
1060 return count & 1;
1061 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001062 // FIXME: This miscounts tok:unknown tokens that are not just
1063 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001064 for (int i = 0, e = Text.size(); i != e; ++i) {
1065 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001066 case '\n':
1067 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001068 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001069 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1070 Column = 0;
1071 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001072 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001073 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1074 Column = 0;
1075 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001076 case '\f':
1077 case '\v':
1078 Column = 0;
1079 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001080 case ' ':
1081 ++Column;
1082 break;
1083 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001084 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001085 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001086 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001087 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001088 FormatTok->Type = TT_ImplicitStringLiteral;
1089 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001090 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001091 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001092 break;
1093 }
1094 }
1095
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001096 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001097 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001098 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001099
Daniel Jasper8369aa52013-07-16 20:28:33 +00001100 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001101 }
Manuel Klimekef920692013-01-07 07:56:50 +00001102
Manuel Klimek1abf7892013-01-04 23:34:14 +00001103 // In case the token starts with escaped newlines, we want to
1104 // take them into account as whitespace - this pattern is quite frequent
1105 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001106 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001107 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1108 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001109 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001110 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001111 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001112 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001113 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001114 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001115
1116 FormatTok->WhitespaceRange = SourceRange(
1117 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1118
Manuel Klimek31c85922013-08-29 15:21:40 +00001119 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001120
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001121 TrailingWhitespace = 0;
1122 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001123 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001124 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001125 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001126 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001127 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001128 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001129 FormatTok->Tok.setIdentifierInfo(&Info);
1130 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001131 if (Style.Language == FormatStyle::LK_Java &&
1132 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1133 FormatTok->Tok.setKind(tok::identifier);
1134 FormatTok->Tok.setIdentifierInfo(nullptr);
1135 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001136 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001137 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001138 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001139 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001140 } else if (FormatTok->Tok.is(tok::lessless)) {
1141 FormatTok->Tok.setKind(tok::less);
1142 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1143 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001144 }
1145
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001146 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001147
Alexander Kornienko39856b72013-09-10 09:38:25 +00001148 StringRef Text = FormatTok->TokenText;
1149 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001150 if (FirstNewlinePos == StringRef::npos) {
1151 // FIXME: ColumnWidth actually depends on the start column, we need to
1152 // take this into account when the token is moved.
1153 FormatTok->ColumnWidth =
1154 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1155 Column += FormatTok->ColumnWidth;
1156 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001157 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001158 // FIXME: ColumnWidth actually depends on the start column, we need to
1159 // take this into account when the token is moved.
1160 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1161 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1162
Alexander Kornienko39856b72013-09-10 09:38:25 +00001163 // The last line of the token always starts in column 0.
1164 // Thus, the length can be precomputed even in the presence of tabs.
1165 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1166 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1167 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001168 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001169 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001170
Daniel Jasper229628b2015-06-11 08:38:19 +00001171 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1172 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1173 tok::pp_define) &&
1174 std::find(ForEachMacros.begin(), ForEachMacros.end(),
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001175 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end())
1176 FormatTok->Type = TT_ForEachMacro;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001177
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001178 return FormatTok;
1179 }
1180
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001181 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001182 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001183 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001184 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001185 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001186 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001187 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001188 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001189 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001190 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001191 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001192 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001193 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001194 // Index (in 'Tokens') of the last token that starts a new line.
1195 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001196 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001197 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001198
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001199 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001200
Daniel Jasper8369aa52013-07-16 20:28:33 +00001201 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001202 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001203 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1204 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001205 // For formatting, treat unterminated string literals like normal string
1206 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001207 if (Tok.is(tok::unknown)) {
1208 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1209 Tok.Tok.setKind(tok::string_literal);
1210 Tok.IsUnterminatedLiteral = true;
1211 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1212 Tok.TokenText == "''") {
1213 Tok.Tok.setKind(tok::char_constant);
1214 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001215 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001216
1217 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1218 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001219 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001220 }
1221
Daniel Jasper471894432014-08-06 13:40:26 +00001222 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001223
1224 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1225 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001226 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001227 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001229
1230 void resetLexer(unsigned Offset) {
1231 StringRef Buffer = SourceMgr.getBufferData(ID);
1232 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1233 getFormattingLangOpts(Style), Buffer.begin(),
1234 Buffer.begin() + Offset, Buffer.end()));
1235 Lex->SetKeepWhitespaceMode(true);
Daniel Jasper55c384e2015-07-02 14:01:34 +00001236 TrailingWhitespace = 0;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001237 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001238};
1239
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001240static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1241 switch (Language) {
1242 case FormatStyle::LK_Cpp:
1243 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001244 case FormatStyle::LK_Java:
1245 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001246 case FormatStyle::LK_JavaScript:
1247 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001248 case FormatStyle::LK_Proto:
1249 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001250 default:
1251 return "Unknown";
1252 }
1253}
1254
Daniel Jasperf7935112012-12-03 18:12:45 +00001255class Formatter : public UnwrappedLineConsumer {
1256public:
Daniel Jasper23376252014-09-09 14:37:39 +00001257 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001258 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001259 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1260 Whitespaces(SourceMgr, Style,
1261 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001262 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001263 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001264 DEBUG(llvm::dbgs() << "File encoding: "
1265 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1266 : "unknown")
1267 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001268 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1269 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001270 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001271
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001272 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001273 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001274 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001275
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001276 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1277 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001278 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001279 assert(UnwrappedLines.rbegin()->empty());
1280 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1281 ++Run) {
1282 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1283 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1284 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1285 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1286 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001287 tooling::Replacements RunResult =
1288 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001289 DEBUG({
1290 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1291 for (tooling::Replacements::iterator I = RunResult.begin(),
1292 E = RunResult.end();
1293 I != E; ++I) {
1294 llvm::dbgs() << I->toString() << "\n";
1295 }
1296 });
1297 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1298 delete AnnotatedLines[i];
1299 }
1300 Result.insert(RunResult.begin(), RunResult.end());
1301 Whitespaces.reset();
1302 }
1303 return Result;
1304 }
1305
1306 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001307 FormatTokenLexer &Tokens,
1308 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001309 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001310 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001311 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001312 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001313 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001314 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001315 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001316 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001317 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001318
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001319 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001320 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1321 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001322 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001323 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1324 IncompleteFormat)
1325 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001326 return Whitespaces.generateReplacements();
1327 }
1328
1329private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001330 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001331 // Returns \c true if at least one line between I and E or one of their
1332 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001333 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1334 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1335 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001336 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001337 while (I != E) {
1338 AnnotatedLine *Line = *I;
1339 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1340
1341 // If a line is part of a preprocessor directive, it needs to be formatted
1342 // if any token within the directive is affected.
1343 if (Line->InPPDirective) {
1344 FormatToken *Last = Line->Last;
1345 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1346 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1347 Last = (*PPEnd)->Last;
1348 ++PPEnd;
1349 }
1350
1351 if (affectsTokenRange(*Line->First, *Last,
1352 /*IncludeLeadingNewlines=*/false)) {
1353 SomeLineAffected = true;
1354 markAllAsAffected(I, PPEnd);
1355 }
1356 I = PPEnd;
1357 continue;
1358 }
1359
Daniel Jasper38c82402013-11-29 09:27:43 +00001360 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001361 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001362
Daniel Jasper38c82402013-11-29 09:27:43 +00001363 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001364 ++I;
1365 }
1366 return SomeLineAffected;
1367 }
1368
Daniel Jasper9c199562013-11-28 15:58:55 +00001369 // Determines whether 'Line' is affected by the SourceRanges given as input.
1370 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001371 bool nonPPLineAffected(AnnotatedLine *Line,
1372 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001373 bool SomeLineAffected = false;
1374 Line->ChildrenAffected =
1375 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1376 if (Line->ChildrenAffected)
1377 SomeLineAffected = true;
1378
1379 // Stores whether one of the line's tokens is directly affected.
1380 bool SomeTokenAffected = false;
1381 // Stores whether we need to look at the leading newlines of the next token
1382 // in order to determine whether it was affected.
1383 bool IncludeLeadingNewlines = false;
1384
1385 // Stores whether the first child line of any of this line's tokens is
1386 // affected.
1387 bool SomeFirstChildAffected = false;
1388
1389 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1390 // Determine whether 'Tok' was affected.
1391 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1392 SomeTokenAffected = true;
1393
1394 // Determine whether the first child of 'Tok' was affected.
1395 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1396 SomeFirstChildAffected = true;
1397
1398 IncludeLeadingNewlines = Tok->Children.empty();
1399 }
1400
1401 // Was this line moved, i.e. has it previously been on the same line as an
1402 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001403 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1404 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001405
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001406 bool IsContinuedComment =
1407 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1408 Line->First->NewlinesBefore < 2 && PreviousLine &&
1409 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001410
1411 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1412 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001413 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001414 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001415 }
1416 return SomeLineAffected;
1417 }
1418
Daniel Jasper5500f612013-11-25 11:08:59 +00001419 // Marks all lines between I and E as well as all their children as affected.
1420 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1421 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1422 while (I != E) {
1423 (*I)->Affected = true;
1424 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1425 ++I;
1426 }
1427 }
1428
1429 // Returns true if the range from 'First' to 'Last' intersects with one of the
1430 // input ranges.
1431 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1432 bool IncludeLeadingNewlines) {
1433 SourceLocation Start = First.WhitespaceRange.getBegin();
1434 if (!IncludeLeadingNewlines)
1435 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001436 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001437 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001438 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1439 return affectsCharSourceRange(Range);
1440 }
1441
1442 // Returns true if one of the input ranges intersect the leading empty lines
1443 // before 'Tok'.
1444 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1445 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1446 Tok.WhitespaceRange.getBegin(),
1447 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1448 return affectsCharSourceRange(EmptyLineRange);
1449 }
1450
1451 // Returns true if 'Range' intersects with one of the input ranges.
1452 bool affectsCharSourceRange(const CharSourceRange &Range) {
1453 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1454 E = Ranges.end();
1455 I != E; ++I) {
1456 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1457 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1458 return true;
1459 }
1460 return false;
1461 }
1462
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001463 static bool inputUsesCRLF(StringRef Text) {
1464 return Text.count('\r') * 2 > Text.count('\n');
1465 }
1466
Manuel Klimek71814b42013-10-11 21:25:45 +00001467 void
1468 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001469 unsigned CountBoundToVariable = 0;
1470 unsigned CountBoundToType = 0;
1471 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001472 bool HasBinPackedFunction = false;
1473 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001474 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001475 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001476 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001477 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001478 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001479 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001480 bool SpacesBefore =
1481 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1482 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1483 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001484 if (SpacesBefore && !SpacesAfter)
1485 ++CountBoundToVariable;
1486 else if (!SpacesBefore && SpacesAfter)
1487 ++CountBoundToType;
1488 }
1489
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001490 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001491 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001492 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001493 if (Tok->is(TT_TemplateCloser) &&
1494 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001495 HasCpp03IncompatibleFormat = true;
1496 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001497
1498 if (Tok->PackingKind == PPK_BinPacked)
1499 HasBinPackedFunction = true;
1500 if (Tok->PackingKind == PPK_OnePerLine)
1501 HasOnePerLineFunction = true;
1502
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001503 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001504 }
1505 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001506 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001507 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001508 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001509 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001510 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001511 }
1512 if (Style.Standard == FormatStyle::LS_Auto) {
1513 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1514 : FormatStyle::LS_Cpp03;
1515 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001516 BinPackInconclusiveFunctions =
1517 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001518 }
1519
Craig Topperfb6b25b2014-03-15 04:29:04 +00001520 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001521 assert(!UnwrappedLines.empty());
1522 UnwrappedLines.back().push_back(TheLine);
1523 }
1524
Craig Topperfb6b25b2014-03-15 04:29:04 +00001525 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001526 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001527 }
1528
1529 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001530 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001531 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001532 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001533 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001534 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001535
1536 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001537 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001538};
1539
Craig Topperaf35e852013-06-30 22:29:28 +00001540} // end anonymous namespace
1541
Daniel Jasper23376252014-09-09 14:37:39 +00001542tooling::Replacements reformat(const FormatStyle &Style,
1543 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001544 ArrayRef<CharSourceRange> Ranges,
1545 bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001546 if (Style.DisableFormat)
1547 return tooling::Replacements();
1548 Formatter formatter(Style, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001549 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001550}
1551
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001552tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001553 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001554 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001555 if (Style.DisableFormat)
1556 return tooling::Replacements();
1557
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001558 FileManager Files((FileSystemOptions()));
1559 DiagnosticsEngine Diagnostics(
1560 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1561 new DiagnosticOptions);
1562 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001563 std::unique_ptr<llvm::MemoryBuffer> Buf =
1564 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001565 const clang::FileEntry *Entry =
1566 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001567 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001568 FileID ID =
1569 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001570 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1571 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001572 for (const tooling::Range &Range : Ranges) {
1573 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1574 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001575 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1576 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001577 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001578}
1579
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001580LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001581 LangOptions LangOpts;
1582 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001583 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1584 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001585 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001586 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001587 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001588 LangOpts.Bool = 1;
1589 LangOpts.ObjC1 = 1;
1590 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001591 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001592 return LangOpts;
1593}
1594
Edwin Vaned544aa72013-09-30 13:31:48 +00001595const char *StyleOptionHelpDescription =
1596 "Coding style, currently supports:\n"
1597 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1598 "Use -style=file to load style configuration from\n"
1599 ".clang-format file located in one of the parent\n"
1600 "directories of the source file (or current\n"
1601 "directory for stdin).\n"
1602 "Use -style=\"{key: value, ...}\" to set specific\n"
1603 "parameters, e.g.:\n"
1604 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1605
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001606static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001607 if (FileName.endswith(".java")) {
1608 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001609 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1610 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001611 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001612 } else if (FileName.endswith_lower(".proto") ||
1613 FileName.endswith_lower(".protodevel")) {
1614 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001615 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001616 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001617}
1618
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001619FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1620 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001621 FormatStyle Style = getLLVMStyle();
1622 Style.Language = getLanguageByFileName(FileName);
1623 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001624 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1625 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001626 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001627 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001628
1629 if (StyleName.startswith("{")) {
1630 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001631 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001632 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1633 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001634 }
1635 return Style;
1636 }
1637
1638 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001639 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001640 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1641 << " style\n";
1642 return Style;
1643 }
1644
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001645 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001646 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001647 SmallString<128> Path(FileName);
1648 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001649 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001650 Directory = llvm::sys::path::parent_path(Directory)) {
1651 if (!llvm::sys::fs::is_directory(Directory))
1652 continue;
1653 SmallString<128> ConfigFile(Directory);
1654
1655 llvm::sys::path::append(ConfigFile, ".clang-format");
1656 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1657 bool IsFile = false;
1658 // Ignore errors from is_regular_file: we only need to know if we can read
1659 // the file or not.
1660 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1661
1662 if (!IsFile) {
1663 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1664 ConfigFile = Directory;
1665 llvm::sys::path::append(ConfigFile, "_clang-format");
1666 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1667 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1668 }
1669
1670 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001671 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1672 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1673 if (std::error_code EC = Text.getError()) {
1674 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001675 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001676 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001677 if (std::error_code ec =
1678 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001679 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001680 if (!UnsuitableConfigFiles.empty())
1681 UnsuitableConfigFiles.append(", ");
1682 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001683 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001684 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001685 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1686 << "\n";
1687 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001688 }
1689 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1690 return Style;
1691 }
1692 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001693 if (!UnsuitableConfigFiles.empty()) {
1694 llvm::errs() << "Configuration file(s) do(es) not support "
1695 << getLanguageName(Style.Language) << ": "
1696 << UnsuitableConfigFiles << "\n";
1697 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001698 return Style;
1699}
1700
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001701} // namespace format
1702} // namespace clang