blob: 035dc735d93e402c1f91e6cd3f8762739965cc9e [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
Alexander Kornienkod6538332013-05-07 15:32:14 +0000102template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000104 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 FormatStyle::NamespaceIndentationKind &Value) {
106 IO.enumCase(Value, "None", FormatStyle::NI_None);
107 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
108 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000109 }
110};
111
Jacques Pienaarfc275112015-02-18 23:48:37 +0000112template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Alp Toker958027b2014-07-14 19:42:55 +0000118 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000126 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000129 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000132
133 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000136 }
137};
138
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
143
Alexander Kornienko49149672013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000145 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
146 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000160 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000168 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000169 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000174 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000175 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000176 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
178 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000179 IO.mapOptional("AllowShortBlocksOnASingleLine",
180 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000181 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
182 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000183 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
184 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000185 IO.mapOptional("AllowShortLoopsOnASingleLine",
186 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000187 IO.mapOptional("AllowShortFunctionsOnASingleLine",
188 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000189 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
190 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000191 IO.mapOptional("AlwaysBreakTemplateDeclarations",
192 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000193 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
194 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000195 IO.mapOptional("BreakBeforeBinaryOperators",
196 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000197 IO.mapOptional("BreakBeforeTernaryOperators",
198 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000199 IO.mapOptional("BreakConstructorInitializersBeforeComma",
200 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000202 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
204 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
205 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000206 IO.mapOptional("ConstructorInitializerIndentWidth",
207 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000208 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000209 IO.mapOptional("ExperimentalAutoDetectBinPacking",
210 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000211 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000212 IO.mapOptional("IndentWrappedFunctionNames",
213 Style.IndentWrappedFunctionNames);
214 IO.mapOptional("IndentFunctionDeclarationAfterType",
215 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000216 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000217 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
218 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000219 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000220 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000221 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000222 IO.mapOptional("ObjCSpaceBeforeProtocolList",
223 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000224 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
225 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000226 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
227 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000228 IO.mapOptional("PenaltyBreakFirstLessLess",
229 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000230 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
231 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
232 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000233 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000234 IO.mapOptional("SpacesBeforeTrailingComments",
235 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000236 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000237 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000238 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000239 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000240 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000241 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000242 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000243 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000244 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000245 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000246 IO.mapOptional("SpacesInCStyleCastParentheses",
247 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000248 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000249 IO.mapOptional("SpacesInContainerLiterals",
250 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000251 IO.mapOptional("SpaceBeforeAssignmentOperators",
252 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000253 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000254 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000255 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000256
257 // For backward compatibility.
258 if (!IO.outputting()) {
259 IO.mapOptional("SpaceAfterControlStatementKeyword",
260 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000261 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
262 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000263 }
264 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000265 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000266 }
267};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000268
269// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270// IO.getContext() should contain a pointer to the FormatStyle structure, that
271// will be used to get default values for missing keys.
272// If the first element has no Language specified, it will be treated as the
273// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000274template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000275 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
276 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000277 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000278 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000279 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000280 if (Index >= Seq.size()) {
281 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000282 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000283 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000284 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000285 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000286 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000287 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000288 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000289 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000290 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000291 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000292 }
293};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000294}
295}
296
Daniel Jasperf7935112012-12-03 18:12:45 +0000297namespace clang {
298namespace format {
299
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000300const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000301 static ParseErrorCategory C;
302 return C;
303}
304std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000305 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000306}
307
308const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
309 return "clang-format.parse_error";
310}
311
312std::string ParseErrorCategory::message(int EV) const {
313 switch (static_cast<ParseError>(EV)) {
314 case ParseError::Success:
315 return "Success";
316 case ParseError::Error:
317 return "Invalid argument";
318 case ParseError::Unsuitable:
319 return "Unsuitable";
320 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000321 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000322}
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324FormatStyle getLLVMStyle() {
325 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000326 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000328 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000329 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000330 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000331 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000332 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000333 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000334 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000335 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000336 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000337 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000338 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000339 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000340 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000341 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000342 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000343 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000344 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000345 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
346 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000347 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000348 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000349 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000350 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000351 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000352 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000353 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000354 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000355 LLVMStyle.ForEachMacros.push_back("foreach");
356 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
357 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000358 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000359 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000360 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000361 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000362 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000363 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000364 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000365 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000366 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000367 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000368 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000369 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000370 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000371 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000372 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000373 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000374 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000375 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000376 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000377 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000378 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000379 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000380 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000381
Daniel Jasper19a541e2013-12-19 16:45:34 +0000382 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000383 LLVMStyle.PenaltyBreakFirstLessLess = 120;
384 LLVMStyle.PenaltyBreakString = 1000;
385 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000386 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000387 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000388
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000389 LLVMStyle.DisableFormat = false;
390
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 return LLVMStyle;
392}
393
Nico Weber514ecc82014-02-02 20:50:45 +0000394FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000395 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000396 GoogleStyle.Language = Language;
397
Daniel Jasperf7935112012-12-03 18:12:45 +0000398 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000399 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000400 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000401 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000402 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000403 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000404 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000405 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000406 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000407 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000408 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000409 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000410 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000411 GoogleStyle.SpacesBeforeTrailingComments = 2;
412 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000413
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000414 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000415 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000416
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000417 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000418 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000419 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000420 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000421 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000422 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000423 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000424 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
425 GoogleStyle.ColumnLimit = 100;
426 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000427 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000428 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000429 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000430 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000431 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000432 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000433 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000434 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000435 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000436 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000437 }
438
Daniel Jasperf7935112012-12-03 18:12:45 +0000439 return GoogleStyle;
440}
441
Nico Weber514ecc82014-02-02 20:50:45 +0000442FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
443 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000444 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000445 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000446 ChromiumStyle.IndentWidth = 4;
447 ChromiumStyle.ContinuationIndentWidth = 8;
448 } else {
449 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
450 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
451 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
452 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
453 ChromiumStyle.BinPackParameters = false;
454 ChromiumStyle.DerivePointerAlignment = false;
455 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000456 return ChromiumStyle;
457}
458
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000459FormatStyle getMozillaStyle() {
460 FormatStyle MozillaStyle = getLLVMStyle();
461 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000462 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000463 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000464 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000465 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000466 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000467 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
468 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000469 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000470 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000471 return MozillaStyle;
472}
473
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000474FormatStyle getWebKitStyle() {
475 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000476 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000477 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000478 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000479 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000480 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000481 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000482 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000483 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000484 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000485 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000486 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000487 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000488 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000489 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000490 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000491 return Style;
492}
493
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000494FormatStyle getGNUStyle() {
495 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000496 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000497 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000498 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000499 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000500 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000501 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000502 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000503 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000504 return Style;
505}
506
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000507FormatStyle getNoStyle() {
508 FormatStyle NoStyle = getLLVMStyle();
509 NoStyle.DisableFormat = true;
510 return NoStyle;
511}
512
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000513bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
514 FormatStyle *Style) {
515 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000516 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000517 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000518 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000519 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000520 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000522 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000523 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000524 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000525 } else if (Name.equals_lower("gnu")) {
526 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000527 } else if (Name.equals_lower("none")) {
528 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000529 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000530 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000531 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000532
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000533 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000534 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000535}
536
Rafael Espindolac0809172014-06-12 14:02:15 +0000537std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000538 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000539 FormatStyle::LanguageKind Language = Style->Language;
540 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000541 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000542 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000543
544 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000545 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000546 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
547 // values for the fields, keys for which are missing from the configuration.
548 // Mapping also uses the context to get the language to find the correct
549 // base style.
550 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000551 Input >> Styles;
552 if (Input.error())
553 return Input.error();
554
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000555 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000556 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000557 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000558 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000559 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000560 for (unsigned j = 0; j < i; ++j) {
561 if (Styles[i].Language == Styles[j].Language) {
562 DEBUG(llvm::dbgs()
563 << "Duplicate languages in the config file on positions " << j
564 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000565 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000566 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000567 }
568 }
569 // Look for a suitable configuration starting from the end, so we can
570 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000571 // configuration (which can only be at slot 0) after it.
572 for (int i = Styles.size() - 1; i >= 0; --i) {
573 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000574 Styles[i].Language == FormatStyle::LK_None) {
575 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000576 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000577 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000578 }
579 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000580 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000581}
582
583std::string configurationAsText(const FormatStyle &Style) {
584 std::string Text;
585 llvm::raw_string_ostream Stream(Text);
586 llvm::yaml::Output Output(Stream);
587 // We use the same mapping method for input and output, so we need a non-const
588 // reference here.
589 FormatStyle NonConstStyle = Style;
590 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000591 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000592}
593
Craig Topperaf35e852013-06-30 22:29:28 +0000594namespace {
595
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000596class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000597public:
Daniel Jasper23376252014-09-09 14:37:39 +0000598 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000599 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000600 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000601 LessStashed(false), Column(0), TrailingWhitespace(0),
602 SourceMgr(SourceMgr), ID(ID), Style(Style),
603 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
604 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +0000605 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
606 getFormattingLangOpts(Style)));
607 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000608
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000609 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000610 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
611 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000612 }
613
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000614 ArrayRef<FormatToken *> lex() {
615 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000616 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000617 do {
618 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000619 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000620 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000621 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000622 } while (Tokens.back()->Tok.isNot(tok::eof));
623 return Tokens;
624 }
625
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000626 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000627
628private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000629 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000630 if (tryMerge_TMacro())
631 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000632 if (tryMergeConflictMarkers())
633 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000634 if (tryMergeLessLess())
635 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000636
637 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000638 if (tryMergeJSRegexLiteral())
639 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000640 if (tryMergeEscapeSequence())
641 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000642 if (tryMergeTemplateString())
643 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000644
Jacques Pienaarfc275112015-02-18 23:48:37 +0000645 static tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
646 static tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, tok::equal};
647 static tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
648 tok::greaterequal};
649 static tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000650 // FIXME: We probably need to change token type to mimic operator with the
651 // correct priority.
652 if (tryMergeTokens(JSIdentity))
653 return;
654 if (tryMergeTokens(JSNotIdentity))
655 return;
656 if (tryMergeTokens(JSShiftEqual))
657 return;
Daniel Jasper78214392014-05-19 07:27:02 +0000658 if (tryMergeTokens(JSRightArrow))
659 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000660 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000661 }
662
Jacques Pienaarfc275112015-02-18 23:48:37 +0000663 bool tryMergeLessLess() {
664 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000665 if (Tokens.size() < 3)
666 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000667
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000668 bool FourthTokenIsLess = false;
669 if (Tokens.size() > 3)
670 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000671
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000672 auto First = Tokens.end() - 3;
673 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
674 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000675 return false;
676
677 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000678 if (First[1]->WhitespaceRange.getBegin() !=
679 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000680 return false;
681
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000682 First[0]->Tok.setKind(tok::lessless);
683 First[0]->TokenText = "<<";
684 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000685 Tokens.erase(Tokens.end() - 2);
686 return true;
687 }
688
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000689 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
690 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000691 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000692
693 SmallVectorImpl<FormatToken *>::const_iterator First =
694 Tokens.end() - Kinds.size();
695 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000696 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000697 unsigned AddLength = 0;
698 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000699 if (!First[i]->is(Kinds[i]) ||
700 First[i]->WhitespaceRange.getBegin() !=
701 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000702 return false;
703 AddLength += First[i]->TokenText.size();
704 }
705 Tokens.resize(Tokens.size() - Kinds.size() + 1);
706 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
707 First[0]->TokenText.size() + AddLength);
708 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000709 return true;
710 }
711
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000712 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000713 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000714 bool tryMergeEscapeSequence() {
715 if (Tokens.size() < 2)
716 return false;
717 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000718 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000719 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000720 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000721 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000722 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
723 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000724 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000725 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000726 return true;
727 }
728
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000729 // Try to determine whether the current token ends a JavaScript regex literal.
730 // We heuristically assume that this is a regex literal if we find two
731 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000732 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
733 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000734 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000735 if (Tokens.size() < 2)
736 return false;
737 // If a regex literal ends in "\//", this gets represented by an unknown
738 // token "\" and a comment.
739 bool MightEndWithEscapedSlash =
740 Tokens.back()->is(tok::comment) &&
741 Tokens.back()->TokenText.startswith("//") &&
742 Tokens[Tokens.size() - 2]->TokenText == "\\";
743 if (!MightEndWithEscapedSlash &&
744 (Tokens.back()->isNot(tok::slash) ||
745 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
746 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000747 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000748 unsigned TokenCount = 0;
749 unsigned LastColumn = Tokens.back()->OriginalColumn;
750 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
751 ++TokenCount;
752 if (I[0]->is(tok::slash) && I + 1 != E &&
753 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
754 tok::exclaim, tok::l_square, tok::colon, tok::comma,
755 tok::question, tok::kw_return) ||
756 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +0000757 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000758 // This regex literal ends in '\//'. Skip past the '//' of the last
759 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000760 SourceLocation Loc = Tokens.back()->Tok.getLocation();
761 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +0000762 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000763 Tokens.resize(Tokens.size() - TokenCount);
764 Tokens.back()->Tok.setKind(tok::unknown);
765 Tokens.back()->Type = TT_RegexLiteral;
766 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
767 return true;
768 }
769
770 // There can't be a newline inside a regex literal.
771 if (I[0]->NewlinesBefore > 0)
772 return false;
773 }
774 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000775 }
776
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000777 bool tryMergeTemplateString() {
778 if (Tokens.size() < 2)
779 return false;
780
781 FormatToken *EndBacktick = Tokens.back();
782 if (!(EndBacktick->is(tok::unknown) && EndBacktick->TokenText == "`"))
783 return false;
784
785 unsigned TokenCount = 0;
786 bool IsMultiline = false;
787 unsigned EndColumnInFirstLine = 0;
788 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
789 ++TokenCount;
790 if (I[0]->NewlinesBefore > 0 || I[0]->IsMultiline)
791 IsMultiline = true;
792
793 // If there was a preceding template string, this must be the start of a
794 // template string, not the end.
795 if (I[0]->is(TT_TemplateString))
796 return false;
797
798 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
799 // Keep track of the rhs offset of the last token to wrap across lines -
800 // its the rhs offset of the first line of the template string, used to
801 // determine its width.
802 if (I[0]->IsMultiline)
803 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
804 // If the token has newlines, the token before it (if it exists) is the
805 // rhs end of the previous line.
806 if (I[0]->NewlinesBefore > 0 && (I + 1 != E))
807 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
808
809 continue;
810 }
811
812 Tokens.resize(Tokens.size() - TokenCount);
813 Tokens.back()->Type = TT_TemplateString;
814 const char *EndOffset = EndBacktick->TokenText.data() + 1;
815 Tokens.back()->TokenText =
816 StringRef(Tokens.back()->TokenText.data(),
817 EndOffset - Tokens.back()->TokenText.data());
818 if (IsMultiline) {
819 // ColumnWidth is from backtick to last token in line.
820 // LastLineColumnWidth is 0 to backtick.
821 // x = `some content
822 // until here`;
823 Tokens.back()->ColumnWidth =
824 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
825 Tokens.back()->LastLineColumnWidth = EndBacktick->OriginalColumn;
826 Tokens.back()->IsMultiline = true;
827 } else {
828 // Token simply spans from start to end, +1 for the ` itself.
829 Tokens.back()->ColumnWidth =
830 EndBacktick->OriginalColumn - Tokens.back()->OriginalColumn + 1;
831 }
832 return true;
833 }
834 return false;
835 }
836
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000837 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000838 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000839 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000840 FormatToken *Last = Tokens.back();
841 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000842 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000843
844 FormatToken *String = Tokens[Tokens.size() - 2];
845 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000846 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000847
848 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000849 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000850
851 FormatToken *Macro = Tokens[Tokens.size() - 4];
852 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000853 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000854
855 const char *Start = Macro->TokenText.data();
856 const char *End = Last->TokenText.data() + Last->TokenText.size();
857 String->TokenText = StringRef(Start, End - Start);
858 String->IsFirst = Macro->IsFirst;
859 String->LastNewlineOffset = Macro->LastNewlineOffset;
860 String->WhitespaceRange = Macro->WhitespaceRange;
861 String->OriginalColumn = Macro->OriginalColumn;
862 String->ColumnWidth = encoding::columnWidthWithTabs(
863 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
864
865 Tokens.pop_back();
866 Tokens.pop_back();
867 Tokens.pop_back();
868 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000869 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000870 }
871
Manuel Klimek68b03042014-04-14 09:14:11 +0000872 bool tryMergeConflictMarkers() {
873 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
874 return false;
875
876 // Conflict lines look like:
877 // <marker> <text from the vcs>
878 // For example:
879 // >>>>>>> /file/in/file/system at revision 1234
880 //
881 // We merge all tokens in a line that starts with a conflict marker
882 // into a single token with a special token type that the unwrapped line
883 // parser will use to correctly rebuild the underlying code.
884
885 FileID ID;
886 // Get the position of the first token in the line.
887 unsigned FirstInLineOffset;
888 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
889 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
890 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
891 // Calculate the offset of the start of the current line.
892 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
893 if (LineOffset == StringRef::npos) {
894 LineOffset = 0;
895 } else {
896 ++LineOffset;
897 }
898
899 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
900 StringRef LineStart;
901 if (FirstSpace == StringRef::npos) {
902 LineStart = Buffer.substr(LineOffset);
903 } else {
904 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
905 }
906
907 TokenType Type = TT_Unknown;
908 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
909 Type = TT_ConflictStart;
910 } else if (LineStart == "|||||||" || LineStart == "=======" ||
911 LineStart == "====") {
912 Type = TT_ConflictAlternative;
913 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
914 Type = TT_ConflictEnd;
915 }
916
917 if (Type != TT_Unknown) {
918 FormatToken *Next = Tokens.back();
919
920 Tokens.resize(FirstInLineIndex + 1);
921 // We do not need to build a complete token here, as we will skip it
922 // during parsing anyway (as we must not touch whitespace around conflict
923 // markers).
924 Tokens.back()->Type = Type;
925 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
926
927 Tokens.push_back(Next);
928 return true;
929 }
930
931 return false;
932 }
933
Jacques Pienaarfc275112015-02-18 23:48:37 +0000934 FormatToken *getStashedToken() {
935 // Create a synthesized second '>' or '<' token.
936 Token Tok = FormatTok->Tok;
937 StringRef TokenText = FormatTok->TokenText;
938
939 unsigned OriginalColumn = FormatTok->OriginalColumn;
940 FormatTok = new (Allocator.Allocate()) FormatToken;
941 FormatTok->Tok = Tok;
942 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +0000943 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
944 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000945 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
946 FormatTok->TokenText = TokenText;
947 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +0000948 FormatTok->OriginalColumn = OriginalColumn + 1;
949
Jacques Pienaarfc275112015-02-18 23:48:37 +0000950 return FormatTok;
951 }
952
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000953 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000954 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000955 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000956 return getStashedToken();
957 }
958 if (LessStashed) {
959 LessStashed = false;
960 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000961 }
962
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000963 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000964 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +0000965 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000966 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +0000967 FormatTok->IsFirst = IsFirstToken;
968 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000969
970 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +0000971 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000972 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000973 // FIXME: This miscounts tok:unknown tokens that are not just
974 // whitespace, e.g. a '`' character.
Manuel Klimek31c85922013-08-29 15:21:40 +0000975 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
976 switch (FormatTok->TokenText[i]) {
977 case '\n':
978 ++FormatTok->NewlinesBefore;
979 // FIXME: This is technically incorrect, as it could also
980 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +0000981 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
982 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
983 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +0000984 FormatTok->HasUnescapedNewline = true;
985 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
986 Column = 0;
987 break;
Daniel Jasper877615c2013-10-11 19:45:02 +0000988 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +0000989 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
990 Column = 0;
991 break;
Daniel Jasper877615c2013-10-11 19:45:02 +0000992 case '\f':
993 case '\v':
994 Column = 0;
995 break;
Manuel Klimek31c85922013-08-29 15:21:40 +0000996 case ' ':
997 ++Column;
998 break;
999 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001000 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001001 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001002 case '\\':
Daniel Jasper877615c2013-10-11 19:45:02 +00001003 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1004 FormatTok->TokenText[i + 1] != '\n'))
1005 FormatTok->Type = TT_ImplicitStringLiteral;
1006 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001007 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001008 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001009 ++Column;
1010 break;
1011 }
1012 }
1013
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001014 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001015 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001016 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001017
Daniel Jasper8369aa52013-07-16 20:28:33 +00001018 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001019 }
Manuel Klimekef920692013-01-07 07:56:50 +00001020
Manuel Klimek1abf7892013-01-04 23:34:14 +00001021 // In case the token starts with escaped newlines, we want to
1022 // take them into account as whitespace - this pattern is quite frequent
1023 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001024 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001025 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1026 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001027 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001028 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001029 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001030 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001031 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001032
1033 FormatTok->WhitespaceRange = SourceRange(
1034 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1035
Manuel Klimek31c85922013-08-29 15:21:40 +00001036 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001037
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001038 TrailingWhitespace = 0;
1039 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001040 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001041 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001042 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001043 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001044 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001045 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001046 FormatTok->Tok.setIdentifierInfo(&Info);
1047 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001048 if (Style.Language == FormatStyle::LK_Java &&
1049 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1050 FormatTok->Tok.setKind(tok::identifier);
1051 FormatTok->Tok.setIdentifierInfo(nullptr);
1052 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001053 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001054 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001055 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001056 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001057 } else if (FormatTok->Tok.is(tok::lessless)) {
1058 FormatTok->Tok.setKind(tok::less);
1059 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1060 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001061 }
1062
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001063 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001064
Alexander Kornienko39856b72013-09-10 09:38:25 +00001065 StringRef Text = FormatTok->TokenText;
1066 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001067 if (FirstNewlinePos == StringRef::npos) {
1068 // FIXME: ColumnWidth actually depends on the start column, we need to
1069 // take this into account when the token is moved.
1070 FormatTok->ColumnWidth =
1071 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1072 Column += FormatTok->ColumnWidth;
1073 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001074 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001075 // FIXME: ColumnWidth actually depends on the start column, we need to
1076 // take this into account when the token is moved.
1077 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1078 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1079
Alexander Kornienko39856b72013-09-10 09:38:25 +00001080 // The last line of the token always starts in column 0.
1081 // Thus, the length can be precomputed even in the presence of tabs.
1082 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1083 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1084 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001085 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001086 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001087
Daniel Jaspere1e43192014-04-01 12:55:11 +00001088 FormatTok->IsForEachMacro =
1089 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1090 FormatTok->Tok.getIdentifierInfo());
1091
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001092 return FormatTok;
1093 }
1094
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001095 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001096 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001097 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001098 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001099 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001100 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001101 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001102 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001103 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001104 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001105 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001106 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001107 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001108 // Index (in 'Tokens') of the last token that starts a new line.
1109 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001110 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001111 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001112
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001113 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001114
Daniel Jasper8369aa52013-07-16 20:28:33 +00001115 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001116 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001117 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1118 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001119 // For formatting, treat unterminated string literals like normal string
1120 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001121 if (Tok.is(tok::unknown)) {
1122 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1123 Tok.Tok.setKind(tok::string_literal);
1124 Tok.IsUnterminatedLiteral = true;
1125 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1126 Tok.TokenText == "''") {
1127 Tok.Tok.setKind(tok::char_constant);
1128 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001129 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001130
1131 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1132 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001133 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001134 }
1135
Daniel Jasper471894432014-08-06 13:40:26 +00001136 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001137
1138 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1139 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001140 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001141 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001142 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001143
1144 void resetLexer(unsigned Offset) {
1145 StringRef Buffer = SourceMgr.getBufferData(ID);
1146 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1147 getFormattingLangOpts(Style), Buffer.begin(),
1148 Buffer.begin() + Offset, Buffer.end()));
1149 Lex->SetKeepWhitespaceMode(true);
1150 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001151};
1152
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001153static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1154 switch (Language) {
1155 case FormatStyle::LK_Cpp:
1156 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001157 case FormatStyle::LK_Java:
1158 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001159 case FormatStyle::LK_JavaScript:
1160 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001161 case FormatStyle::LK_Proto:
1162 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001163 default:
1164 return "Unknown";
1165 }
1166}
1167
Daniel Jasperf7935112012-12-03 18:12:45 +00001168class Formatter : public UnwrappedLineConsumer {
1169public:
Daniel Jasper23376252014-09-09 14:37:39 +00001170 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001171 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001172 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1173 Whitespaces(SourceMgr, Style,
1174 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001175 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001176 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001177 DEBUG(llvm::dbgs() << "File encoding: "
1178 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1179 : "unknown")
1180 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001181 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1182 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001183 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001184
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001185 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001186 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001187 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001188
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001189 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1190 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001191 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001192 assert(UnwrappedLines.rbegin()->empty());
1193 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1194 ++Run) {
1195 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1196 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1197 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1198 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1199 }
1200 tooling::Replacements RunResult =
1201 format(AnnotatedLines, StructuralError, Tokens);
1202 DEBUG({
1203 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1204 for (tooling::Replacements::iterator I = RunResult.begin(),
1205 E = RunResult.end();
1206 I != E; ++I) {
1207 llvm::dbgs() << I->toString() << "\n";
1208 }
1209 });
1210 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1211 delete AnnotatedLines[i];
1212 }
1213 Result.insert(RunResult.begin(), RunResult.end());
1214 Whitespaces.reset();
1215 }
1216 return Result;
1217 }
1218
1219 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1220 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001221 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001222 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001223 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001224 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001225 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001226 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001227 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001228 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001229 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001230
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001231 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001232 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1233 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001234 BinPackInconclusiveFunctions);
Nico Weberfac23712015-02-04 15:26:27 +00001235 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
1236 Tokens.getKeywords());
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001237 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001238 return Whitespaces.generateReplacements();
1239 }
1240
1241private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001242 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001243 // Returns \c true if at least one line between I and E or one of their
1244 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001245 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1246 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1247 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001248 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001249 while (I != E) {
1250 AnnotatedLine *Line = *I;
1251 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1252
1253 // If a line is part of a preprocessor directive, it needs to be formatted
1254 // if any token within the directive is affected.
1255 if (Line->InPPDirective) {
1256 FormatToken *Last = Line->Last;
1257 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1258 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1259 Last = (*PPEnd)->Last;
1260 ++PPEnd;
1261 }
1262
1263 if (affectsTokenRange(*Line->First, *Last,
1264 /*IncludeLeadingNewlines=*/false)) {
1265 SomeLineAffected = true;
1266 markAllAsAffected(I, PPEnd);
1267 }
1268 I = PPEnd;
1269 continue;
1270 }
1271
Daniel Jasper38c82402013-11-29 09:27:43 +00001272 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001273 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001274
Daniel Jasper38c82402013-11-29 09:27:43 +00001275 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001276 ++I;
1277 }
1278 return SomeLineAffected;
1279 }
1280
Daniel Jasper9c199562013-11-28 15:58:55 +00001281 // Determines whether 'Line' is affected by the SourceRanges given as input.
1282 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001283 bool nonPPLineAffected(AnnotatedLine *Line,
1284 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001285 bool SomeLineAffected = false;
1286 Line->ChildrenAffected =
1287 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1288 if (Line->ChildrenAffected)
1289 SomeLineAffected = true;
1290
1291 // Stores whether one of the line's tokens is directly affected.
1292 bool SomeTokenAffected = false;
1293 // Stores whether we need to look at the leading newlines of the next token
1294 // in order to determine whether it was affected.
1295 bool IncludeLeadingNewlines = false;
1296
1297 // Stores whether the first child line of any of this line's tokens is
1298 // affected.
1299 bool SomeFirstChildAffected = false;
1300
1301 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1302 // Determine whether 'Tok' was affected.
1303 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1304 SomeTokenAffected = true;
1305
1306 // Determine whether the first child of 'Tok' was affected.
1307 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1308 SomeFirstChildAffected = true;
1309
1310 IncludeLeadingNewlines = Tok->Children.empty();
1311 }
1312
1313 // Was this line moved, i.e. has it previously been on the same line as an
1314 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001315 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1316 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001317
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001318 bool IsContinuedComment =
1319 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1320 Line->First->NewlinesBefore < 2 && PreviousLine &&
1321 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001322
1323 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1324 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001325 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001326 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001327 }
1328 return SomeLineAffected;
1329 }
1330
Daniel Jasper5500f612013-11-25 11:08:59 +00001331 // Marks all lines between I and E as well as all their children as affected.
1332 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1333 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1334 while (I != E) {
1335 (*I)->Affected = true;
1336 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1337 ++I;
1338 }
1339 }
1340
1341 // Returns true if the range from 'First' to 'Last' intersects with one of the
1342 // input ranges.
1343 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1344 bool IncludeLeadingNewlines) {
1345 SourceLocation Start = First.WhitespaceRange.getBegin();
1346 if (!IncludeLeadingNewlines)
1347 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001348 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001349 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001350 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1351 return affectsCharSourceRange(Range);
1352 }
1353
1354 // Returns true if one of the input ranges intersect the leading empty lines
1355 // before 'Tok'.
1356 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1357 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1358 Tok.WhitespaceRange.getBegin(),
1359 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1360 return affectsCharSourceRange(EmptyLineRange);
1361 }
1362
1363 // Returns true if 'Range' intersects with one of the input ranges.
1364 bool affectsCharSourceRange(const CharSourceRange &Range) {
1365 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1366 E = Ranges.end();
1367 I != E; ++I) {
1368 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1369 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1370 return true;
1371 }
1372 return false;
1373 }
1374
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001375 static bool inputUsesCRLF(StringRef Text) {
1376 return Text.count('\r') * 2 > Text.count('\n');
1377 }
1378
Manuel Klimek71814b42013-10-11 21:25:45 +00001379 void
1380 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001381 unsigned CountBoundToVariable = 0;
1382 unsigned CountBoundToType = 0;
1383 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001384 bool HasBinPackedFunction = false;
1385 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001386 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001387 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001388 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001389 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001390 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001391 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001392 bool SpacesBefore =
1393 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1394 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1395 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001396 if (SpacesBefore && !SpacesAfter)
1397 ++CountBoundToVariable;
1398 else if (!SpacesBefore && SpacesAfter)
1399 ++CountBoundToType;
1400 }
1401
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001402 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001403 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001404 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001405 if (Tok->is(TT_TemplateCloser) &&
1406 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001407 HasCpp03IncompatibleFormat = true;
1408 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001409
1410 if (Tok->PackingKind == PPK_BinPacked)
1411 HasBinPackedFunction = true;
1412 if (Tok->PackingKind == PPK_OnePerLine)
1413 HasOnePerLineFunction = true;
1414
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001415 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001416 }
1417 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001418 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001419 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001420 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001421 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001422 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001423 }
1424 if (Style.Standard == FormatStyle::LS_Auto) {
1425 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1426 : FormatStyle::LS_Cpp03;
1427 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001428 BinPackInconclusiveFunctions =
1429 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001430 }
1431
Craig Topperfb6b25b2014-03-15 04:29:04 +00001432 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001433 assert(!UnwrappedLines.empty());
1434 UnwrappedLines.back().push_back(TheLine);
1435 }
1436
Craig Topperfb6b25b2014-03-15 04:29:04 +00001437 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001438 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001439 }
1440
1441 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001442 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001443 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001444 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001445 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001446 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001447
1448 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001449 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001450};
1451
Craig Topperaf35e852013-06-30 22:29:28 +00001452} // end anonymous namespace
1453
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001454tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1455 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001456 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00001457 if (Style.DisableFormat)
1458 return tooling::Replacements();
1459 return reformat(Style, SourceMgr,
1460 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
1461}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001462
Daniel Jasper23376252014-09-09 14:37:39 +00001463tooling::Replacements reformat(const FormatStyle &Style,
1464 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001465 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00001466 if (Style.DisableFormat)
1467 return tooling::Replacements();
1468 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001469 return formatter.format();
1470}
1471
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001472tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001473 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001474 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00001475 if (Style.DisableFormat)
1476 return tooling::Replacements();
1477
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001478 FileManager Files((FileSystemOptions()));
1479 DiagnosticsEngine Diagnostics(
1480 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1481 new DiagnosticOptions);
1482 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001483 std::unique_ptr<llvm::MemoryBuffer> Buf =
1484 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001485 const clang::FileEntry *Entry =
1486 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001487 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001488 FileID ID =
1489 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001490 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1491 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001492 for (const tooling::Range &Range : Ranges) {
1493 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1494 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001495 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1496 }
Daniel Jasper23376252014-09-09 14:37:39 +00001497 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001498}
1499
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001500LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001501 LangOptions LangOpts;
1502 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001503 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1504 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001505 LangOpts.LineComment = 1;
Daniel Jasper30a24062014-11-14 09:02:28 +00001506 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
1507 Style.Language != FormatStyle::LK_Java;
1508 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001509 LangOpts.Bool = 1;
1510 LangOpts.ObjC1 = 1;
1511 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001512 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001513 return LangOpts;
1514}
1515
Edwin Vaned544aa72013-09-30 13:31:48 +00001516const char *StyleOptionHelpDescription =
1517 "Coding style, currently supports:\n"
1518 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1519 "Use -style=file to load style configuration from\n"
1520 ".clang-format file located in one of the parent\n"
1521 "directories of the source file (or current\n"
1522 "directory for stdin).\n"
1523 "Use -style=\"{key: value, ...}\" to set specific\n"
1524 "parameters, e.g.:\n"
1525 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1526
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001527static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001528 if (FileName.endswith(".java")) {
1529 return FormatStyle::LK_Java;
1530 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001531 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001532 } else if (FileName.endswith_lower(".proto") ||
1533 FileName.endswith_lower(".protodevel")) {
1534 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001535 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001536 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001537}
1538
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001539FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1540 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001541 FormatStyle Style = getLLVMStyle();
1542 Style.Language = getLanguageByFileName(FileName);
1543 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001544 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1545 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001546 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001547 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001548
1549 if (StyleName.startswith("{")) {
1550 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001551 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001552 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1553 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001554 }
1555 return Style;
1556 }
1557
1558 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001559 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001560 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1561 << " style\n";
1562 return Style;
1563 }
1564
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001565 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001566 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001567 SmallString<128> Path(FileName);
1568 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001569 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001570 Directory = llvm::sys::path::parent_path(Directory)) {
1571 if (!llvm::sys::fs::is_directory(Directory))
1572 continue;
1573 SmallString<128> ConfigFile(Directory);
1574
1575 llvm::sys::path::append(ConfigFile, ".clang-format");
1576 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1577 bool IsFile = false;
1578 // Ignore errors from is_regular_file: we only need to know if we can read
1579 // the file or not.
1580 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1581
1582 if (!IsFile) {
1583 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1584 ConfigFile = Directory;
1585 llvm::sys::path::append(ConfigFile, "_clang-format");
1586 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1587 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1588 }
1589
1590 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001591 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1592 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1593 if (std::error_code EC = Text.getError()) {
1594 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001595 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001596 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001597 if (std::error_code ec =
1598 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001599 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001600 if (!UnsuitableConfigFiles.empty())
1601 UnsuitableConfigFiles.append(", ");
1602 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001603 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001604 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001605 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1606 << "\n";
1607 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001608 }
1609 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1610 return Style;
1611 }
1612 }
1613 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1614 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001615 if (!UnsuitableConfigFiles.empty()) {
1616 llvm::errs() << "Configuration file(s) do(es) not support "
1617 << getLanguageName(Style.Language) << ": "
1618 << UnsuitableConfigFiles << "\n";
1619 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001620 return Style;
1621}
1622
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001623} // namespace format
1624} // namespace clang