blob: aec5bb4b59992792f1459863e9790e15331bca94 [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);
Daniel Jaspera44991332015-04-29 13:06:49 +0000177 IO.mapOptional("AlignConsecutiveAssignments", Style.AlignConsecutiveAssignments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000178 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
179 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000180 IO.mapOptional("AllowShortBlocksOnASingleLine",
181 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000182 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
183 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000184 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
185 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000186 IO.mapOptional("AllowShortLoopsOnASingleLine",
187 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000188 IO.mapOptional("AllowShortFunctionsOnASingleLine",
189 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000190 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
191 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000192 IO.mapOptional("AlwaysBreakTemplateDeclarations",
193 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000194 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
195 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000196 IO.mapOptional("BreakBeforeBinaryOperators",
197 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000198 IO.mapOptional("BreakBeforeTernaryOperators",
199 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000200 IO.mapOptional("BreakConstructorInitializersBeforeComma",
201 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000203 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000204 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
205 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
206 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000207 IO.mapOptional("ConstructorInitializerIndentWidth",
208 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000209 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000210 IO.mapOptional("ExperimentalAutoDetectBinPacking",
211 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000212 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000213 IO.mapOptional("IndentWrappedFunctionNames",
214 Style.IndentWrappedFunctionNames);
215 IO.mapOptional("IndentFunctionDeclarationAfterType",
216 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000217 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000218 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
219 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000220 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000221 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000222 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000223 IO.mapOptional("ObjCSpaceBeforeProtocolList",
224 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000225 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
226 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000227 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
228 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000229 IO.mapOptional("PenaltyBreakFirstLessLess",
230 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
232 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
233 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000234 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("SpacesBeforeTrailingComments",
236 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000237 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000238 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000239 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000240 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000241 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000242 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000243 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000244 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000245 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000246 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000247 IO.mapOptional("SpacesInCStyleCastParentheses",
248 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000249 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000250 IO.mapOptional("SpacesInContainerLiterals",
251 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000252 IO.mapOptional("SpaceBeforeAssignmentOperators",
253 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000254 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000255 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000256 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000257
258 // For backward compatibility.
259 if (!IO.outputting()) {
260 IO.mapOptional("SpaceAfterControlStatementKeyword",
261 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000262 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
263 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000264 }
265 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000266 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000267 }
268};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269
270// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000271// IO.getContext() should contain a pointer to the FormatStyle structure, that
272// will be used to get default values for missing keys.
273// If the first element has no Language specified, it will be treated as the
274// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000275template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000276 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
277 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000278 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000279 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000280 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000281 if (Index >= Seq.size()) {
282 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000283 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000284 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000285 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000286 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000287 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000288 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000289 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000290 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000291 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000292 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000293 }
294};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000295}
296}
297
Daniel Jasperf7935112012-12-03 18:12:45 +0000298namespace clang {
299namespace format {
300
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000301const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000302 static ParseErrorCategory C;
303 return C;
304}
305std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000306 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000307}
308
309const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
310 return "clang-format.parse_error";
311}
312
313std::string ParseErrorCategory::message(int EV) const {
314 switch (static_cast<ParseError>(EV)) {
315 case ParseError::Success:
316 return "Success";
317 case ParseError::Error:
318 return "Invalid argument";
319 case ParseError::Unsuitable:
320 return "Unsuitable";
321 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000322 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000323}
324
Daniel Jasperf7935112012-12-03 18:12:45 +0000325FormatStyle getLLVMStyle() {
326 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000327 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000329 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000330 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000331 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000332 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000333 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000334 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000335 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000336 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000337 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000338 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000339 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000340 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000341 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000342 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000343 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000344 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000345 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000346 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000347 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
348 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000349 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000350 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000351 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000352 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000353 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000354 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000355 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000356 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000357 LLVMStyle.ForEachMacros.push_back("foreach");
358 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
359 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000360 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000361 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000362 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000363 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000364 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000365 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000366 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000367 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000368 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000369 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000370 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000371 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000372 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000373 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000374 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000375 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000376 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000377 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000378 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000379 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000380 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000381 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000382 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000383
Daniel Jasper19a541e2013-12-19 16:45:34 +0000384 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000385 LLVMStyle.PenaltyBreakFirstLessLess = 120;
386 LLVMStyle.PenaltyBreakString = 1000;
387 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000388 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000389 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000390
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000391 LLVMStyle.DisableFormat = false;
392
Daniel Jasperf7935112012-12-03 18:12:45 +0000393 return LLVMStyle;
394}
395
Nico Weber514ecc82014-02-02 20:50:45 +0000396FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000397 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000398 GoogleStyle.Language = Language;
399
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000401 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000402 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000403 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000404 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000405 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000406 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000407 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000408 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000409 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000410 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000411 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000412 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000413 GoogleStyle.SpacesBeforeTrailingComments = 2;
414 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000415
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000416 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000417 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000418
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000419 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000420 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000421 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000422 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000423 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000424 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000425 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000426 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
427 GoogleStyle.ColumnLimit = 100;
428 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000429 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000430 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000431 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000432 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000433 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000434 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000435 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000436 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000437 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000438 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000439 }
440
Daniel Jasperf7935112012-12-03 18:12:45 +0000441 return GoogleStyle;
442}
443
Nico Weber514ecc82014-02-02 20:50:45 +0000444FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
445 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000446 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000447 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000448 ChromiumStyle.IndentWidth = 4;
449 ChromiumStyle.ContinuationIndentWidth = 8;
450 } else {
451 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
452 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
453 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
454 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
455 ChromiumStyle.BinPackParameters = false;
456 ChromiumStyle.DerivePointerAlignment = false;
457 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000458 return ChromiumStyle;
459}
460
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000461FormatStyle getMozillaStyle() {
462 FormatStyle MozillaStyle = getLLVMStyle();
463 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000464 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000465 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000466 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000467 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000468 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000469 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
470 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000471 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000472 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000473 return MozillaStyle;
474}
475
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000476FormatStyle getWebKitStyle() {
477 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000478 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000479 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000480 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000481 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000482 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000483 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000484 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000485 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000486 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000487 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000488 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000489 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000490 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000491 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000492 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000493 return Style;
494}
495
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000496FormatStyle getGNUStyle() {
497 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000498 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000499 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000500 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000501 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000502 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000503 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000504 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000505 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000506 return Style;
507}
508
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000509FormatStyle getNoStyle() {
510 FormatStyle NoStyle = getLLVMStyle();
511 NoStyle.DisableFormat = true;
512 return NoStyle;
513}
514
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
516 FormatStyle *Style) {
517 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000518 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000519 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000520 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000522 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000523 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000524 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000525 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000526 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000527 } else if (Name.equals_lower("gnu")) {
528 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000529 } else if (Name.equals_lower("none")) {
530 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000531 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000532 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000533 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000534
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000535 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000536 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000537}
538
Rafael Espindolac0809172014-06-12 14:02:15 +0000539std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000540 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000541 FormatStyle::LanguageKind Language = Style->Language;
542 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000543 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000544 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000545
546 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000547 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
549 // values for the fields, keys for which are missing from the configuration.
550 // Mapping also uses the context to get the language to find the correct
551 // base style.
552 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000553 Input >> Styles;
554 if (Input.error())
555 return Input.error();
556
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000557 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000558 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000559 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000560 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000561 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000562 for (unsigned j = 0; j < i; ++j) {
563 if (Styles[i].Language == Styles[j].Language) {
564 DEBUG(llvm::dbgs()
565 << "Duplicate languages in the config file on positions " << j
566 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000567 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000568 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000569 }
570 }
571 // Look for a suitable configuration starting from the end, so we can
572 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000573 // configuration (which can only be at slot 0) after it.
574 for (int i = Styles.size() - 1; i >= 0; --i) {
575 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000576 Styles[i].Language == FormatStyle::LK_None) {
577 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000578 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000579 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000580 }
581 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000582 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000583}
584
585std::string configurationAsText(const FormatStyle &Style) {
586 std::string Text;
587 llvm::raw_string_ostream Stream(Text);
588 llvm::yaml::Output Output(Stream);
589 // We use the same mapping method for input and output, so we need a non-const
590 // reference here.
591 FormatStyle NonConstStyle = Style;
592 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000593 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000594}
595
Craig Topperaf35e852013-06-30 22:29:28 +0000596namespace {
597
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000598class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000599public:
Daniel Jasper23376252014-09-09 14:37:39 +0000600 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000601 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000602 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000603 LessStashed(false), Column(0), TrailingWhitespace(0),
604 SourceMgr(SourceMgr), ID(ID), Style(Style),
605 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
606 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +0000607 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
608 getFormattingLangOpts(Style)));
609 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000610
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000611 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000612 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
613 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000614 }
615
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000616 ArrayRef<FormatToken *> lex() {
617 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000618 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000619 do {
620 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000621 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000622 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000623 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000624 } while (Tokens.back()->Tok.isNot(tok::eof));
625 return Tokens;
626 }
627
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000628 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000629
630private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000631 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000632 if (tryMerge_TMacro())
633 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000634 if (tryMergeConflictMarkers())
635 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000636 if (tryMergeLessLess())
637 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000638
639 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000640 if (tryMergeJSRegexLiteral())
641 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000642 if (tryMergeEscapeSequence())
643 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000644 if (tryMergeTemplateString())
645 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000646
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000647 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
648 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
649 tok::equal};
650 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
651 tok::greaterequal};
652 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000653 // FIXME: We probably need to change token type to mimic operator with the
654 // correct priority.
655 if (tryMergeTokens(JSIdentity))
656 return;
657 if (tryMergeTokens(JSNotIdentity))
658 return;
659 if (tryMergeTokens(JSShiftEqual))
660 return;
Daniel Jasper78214392014-05-19 07:27:02 +0000661 if (tryMergeTokens(JSRightArrow))
662 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000663 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000664 }
665
Jacques Pienaarfc275112015-02-18 23:48:37 +0000666 bool tryMergeLessLess() {
667 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000668 if (Tokens.size() < 3)
669 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000670
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000671 bool FourthTokenIsLess = false;
672 if (Tokens.size() > 3)
673 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000674
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000675 auto First = Tokens.end() - 3;
676 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
677 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000678 return false;
679
680 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000681 if (First[1]->WhitespaceRange.getBegin() !=
682 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000683 return false;
684
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000685 First[0]->Tok.setKind(tok::lessless);
686 First[0]->TokenText = "<<";
687 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000688 Tokens.erase(Tokens.end() - 2);
689 return true;
690 }
691
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000692 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
693 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000694 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000695
696 SmallVectorImpl<FormatToken *>::const_iterator First =
697 Tokens.end() - Kinds.size();
698 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000699 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000700 unsigned AddLength = 0;
701 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000702 if (!First[i]->is(Kinds[i]) ||
703 First[i]->WhitespaceRange.getBegin() !=
704 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000705 return false;
706 AddLength += First[i]->TokenText.size();
707 }
708 Tokens.resize(Tokens.size() - Kinds.size() + 1);
709 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
710 First[0]->TokenText.size() + AddLength);
711 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000712 return true;
713 }
714
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000715 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000716 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000717 bool tryMergeEscapeSequence() {
718 if (Tokens.size() < 2)
719 return false;
720 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000721 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000722 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000723 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000724 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000725 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
726 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000727 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000728 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000729 return true;
730 }
731
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000732 // Try to determine whether the current token ends a JavaScript regex literal.
733 // We heuristically assume that this is a regex literal if we find two
734 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000735 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
736 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000737 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000738 if (Tokens.size() < 2)
739 return false;
740 // If a regex literal ends in "\//", this gets represented by an unknown
741 // token "\" and a comment.
742 bool MightEndWithEscapedSlash =
743 Tokens.back()->is(tok::comment) &&
744 Tokens.back()->TokenText.startswith("//") &&
745 Tokens[Tokens.size() - 2]->TokenText == "\\";
746 if (!MightEndWithEscapedSlash &&
747 (Tokens.back()->isNot(tok::slash) ||
748 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
749 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000750 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000751 unsigned TokenCount = 0;
752 unsigned LastColumn = Tokens.back()->OriginalColumn;
753 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
754 ++TokenCount;
Daniel Jasper69694b02015-05-08 07:55:13 +0000755 if (I[0]->isOneOf(tok::slash, tok::slashequal) && I + 1 != E &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000756 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
757 tok::exclaim, tok::l_square, tok::colon, tok::comma,
758 tok::question, tok::kw_return) ||
759 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +0000760 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000761 // This regex literal ends in '\//'. Skip past the '//' of the last
762 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000763 SourceLocation Loc = Tokens.back()->Tok.getLocation();
764 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +0000765 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000766 Tokens.resize(Tokens.size() - TokenCount);
767 Tokens.back()->Tok.setKind(tok::unknown);
768 Tokens.back()->Type = TT_RegexLiteral;
769 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
770 return true;
771 }
772
773 // There can't be a newline inside a regex literal.
774 if (I[0]->NewlinesBefore > 0)
775 return false;
776 }
777 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000778 }
779
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000780 bool tryMergeTemplateString() {
781 if (Tokens.size() < 2)
782 return false;
783
784 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000785 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000786 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
787 // unterminated.
788 if (!EndBacktick->isOneOf(tok::comment, tok::unknown))
789 return false;
790 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
791 // Unknown token that's not actually a backtick, or a comment that doesn't
792 // contain a backtick.
793 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000794 return false;
795
796 unsigned TokenCount = 0;
797 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000798 unsigned EndColumnInFirstLine =
799 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000800 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
801 ++TokenCount;
802 if (I[0]->NewlinesBefore > 0 || I[0]->IsMultiline)
803 IsMultiline = true;
804
805 // If there was a preceding template string, this must be the start of a
806 // template string, not the end.
807 if (I[0]->is(TT_TemplateString))
808 return false;
809
810 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
811 // Keep track of the rhs offset of the last token to wrap across lines -
812 // its the rhs offset of the first line of the template string, used to
813 // determine its width.
814 if (I[0]->IsMultiline)
815 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
816 // If the token has newlines, the token before it (if it exists) is the
817 // rhs end of the previous line.
818 if (I[0]->NewlinesBefore > 0 && (I + 1 != E))
819 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
820
821 continue;
822 }
823
824 Tokens.resize(Tokens.size() - TokenCount);
825 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000826 const char *EndOffset =
827 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
828 if (CommentBacktickPos != 0) {
829 // If the backtick was not the first character (e.g. in a comment),
830 // re-lex after the backtick position.
831 SourceLocation Loc = EndBacktick->Tok.getLocation();
832 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
833 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000834 Tokens.back()->TokenText =
835 StringRef(Tokens.back()->TokenText.data(),
836 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000837
838 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
839 if (EndOriginalColumn == 0) {
840 SourceLocation Loc = EndBacktick->Tok.getLocation();
841 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
842 }
843 // If the ` is further down within the token (e.g. in a comment).
844 EndOriginalColumn += CommentBacktickPos;
845
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000846 if (IsMultiline) {
847 // ColumnWidth is from backtick to last token in line.
848 // LastLineColumnWidth is 0 to backtick.
849 // x = `some content
850 // until here`;
851 Tokens.back()->ColumnWidth =
852 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000853 Tokens.back()->LastLineColumnWidth = EndOriginalColumn;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000854 Tokens.back()->IsMultiline = true;
855 } else {
856 // Token simply spans from start to end, +1 for the ` itself.
857 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000858 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000859 }
860 return true;
861 }
862 return false;
863 }
864
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000865 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000866 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000867 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000868 FormatToken *Last = Tokens.back();
869 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000870 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000871
872 FormatToken *String = Tokens[Tokens.size() - 2];
873 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000874 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000875
876 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000877 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000878
879 FormatToken *Macro = Tokens[Tokens.size() - 4];
880 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000881 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000882
883 const char *Start = Macro->TokenText.data();
884 const char *End = Last->TokenText.data() + Last->TokenText.size();
885 String->TokenText = StringRef(Start, End - Start);
886 String->IsFirst = Macro->IsFirst;
887 String->LastNewlineOffset = Macro->LastNewlineOffset;
888 String->WhitespaceRange = Macro->WhitespaceRange;
889 String->OriginalColumn = Macro->OriginalColumn;
890 String->ColumnWidth = encoding::columnWidthWithTabs(
891 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +0000892 String->NewlinesBefore = Macro->NewlinesBefore;
893 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000894
895 Tokens.pop_back();
896 Tokens.pop_back();
897 Tokens.pop_back();
898 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000899 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000900 }
901
Manuel Klimek68b03042014-04-14 09:14:11 +0000902 bool tryMergeConflictMarkers() {
903 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
904 return false;
905
906 // Conflict lines look like:
907 // <marker> <text from the vcs>
908 // For example:
909 // >>>>>>> /file/in/file/system at revision 1234
910 //
911 // We merge all tokens in a line that starts with a conflict marker
912 // into a single token with a special token type that the unwrapped line
913 // parser will use to correctly rebuild the underlying code.
914
915 FileID ID;
916 // Get the position of the first token in the line.
917 unsigned FirstInLineOffset;
918 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
919 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
920 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
921 // Calculate the offset of the start of the current line.
922 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
923 if (LineOffset == StringRef::npos) {
924 LineOffset = 0;
925 } else {
926 ++LineOffset;
927 }
928
929 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
930 StringRef LineStart;
931 if (FirstSpace == StringRef::npos) {
932 LineStart = Buffer.substr(LineOffset);
933 } else {
934 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
935 }
936
937 TokenType Type = TT_Unknown;
938 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
939 Type = TT_ConflictStart;
940 } else if (LineStart == "|||||||" || LineStart == "=======" ||
941 LineStart == "====") {
942 Type = TT_ConflictAlternative;
943 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
944 Type = TT_ConflictEnd;
945 }
946
947 if (Type != TT_Unknown) {
948 FormatToken *Next = Tokens.back();
949
950 Tokens.resize(FirstInLineIndex + 1);
951 // We do not need to build a complete token here, as we will skip it
952 // during parsing anyway (as we must not touch whitespace around conflict
953 // markers).
954 Tokens.back()->Type = Type;
955 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
956
957 Tokens.push_back(Next);
958 return true;
959 }
960
961 return false;
962 }
963
Jacques Pienaarfc275112015-02-18 23:48:37 +0000964 FormatToken *getStashedToken() {
965 // Create a synthesized second '>' or '<' token.
966 Token Tok = FormatTok->Tok;
967 StringRef TokenText = FormatTok->TokenText;
968
969 unsigned OriginalColumn = FormatTok->OriginalColumn;
970 FormatTok = new (Allocator.Allocate()) FormatToken;
971 FormatTok->Tok = Tok;
972 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +0000973 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
974 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000975 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
976 FormatTok->TokenText = TokenText;
977 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +0000978 FormatTok->OriginalColumn = OriginalColumn + 1;
979
Jacques Pienaarfc275112015-02-18 23:48:37 +0000980 return FormatTok;
981 }
982
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000983 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000984 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000985 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000986 return getStashedToken();
987 }
988 if (LessStashed) {
989 LessStashed = false;
990 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000991 }
992
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000993 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000994 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +0000995 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000996 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +0000997 FormatTok->IsFirst = IsFirstToken;
998 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000999
1000 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001001 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001002 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001003 StringRef Text = FormatTok->TokenText;
1004 auto EscapesNewline = [&](int pos) {
1005 // A '\r' here is just part of '\r\n'. Skip it.
1006 if (pos >= 0 && Text[pos] == '\r')
1007 --pos;
1008 // See whether there is an odd number of '\' before this.
1009 unsigned count = 0;
1010 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001011 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001012 break;
1013 return count & 1;
1014 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001015 // FIXME: This miscounts tok:unknown tokens that are not just
1016 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001017 for (int i = 0, e = Text.size(); i != e; ++i) {
1018 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001019 case '\n':
1020 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001021 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001022 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1023 Column = 0;
1024 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001025 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001026 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1027 Column = 0;
1028 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001029 case '\f':
1030 case '\v':
1031 Column = 0;
1032 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001033 case ' ':
1034 ++Column;
1035 break;
1036 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001037 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001038 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001039 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001040 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001041 FormatTok->Type = TT_ImplicitStringLiteral;
1042 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001043 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001044 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001045 ++Column;
1046 break;
1047 }
1048 }
1049
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001050 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001051 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001052 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001053
Daniel Jasper8369aa52013-07-16 20:28:33 +00001054 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001055 }
Manuel Klimekef920692013-01-07 07:56:50 +00001056
Manuel Klimek1abf7892013-01-04 23:34:14 +00001057 // In case the token starts with escaped newlines, we want to
1058 // take them into account as whitespace - this pattern is quite frequent
1059 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001060 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001061 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1062 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001063 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001064 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001065 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001066 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001067 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001068 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001069
1070 FormatTok->WhitespaceRange = SourceRange(
1071 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1072
Manuel Klimek31c85922013-08-29 15:21:40 +00001073 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001074
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001075 TrailingWhitespace = 0;
1076 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001077 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001078 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001079 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001080 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001081 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001082 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001083 FormatTok->Tok.setIdentifierInfo(&Info);
1084 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001085 if (Style.Language == FormatStyle::LK_Java &&
1086 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1087 FormatTok->Tok.setKind(tok::identifier);
1088 FormatTok->Tok.setIdentifierInfo(nullptr);
1089 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001090 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001091 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001092 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001093 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001094 } else if (FormatTok->Tok.is(tok::lessless)) {
1095 FormatTok->Tok.setKind(tok::less);
1096 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1097 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001098 }
1099
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001100 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001101
Alexander Kornienko39856b72013-09-10 09:38:25 +00001102 StringRef Text = FormatTok->TokenText;
1103 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001104 if (FirstNewlinePos == StringRef::npos) {
1105 // FIXME: ColumnWidth actually depends on the start column, we need to
1106 // take this into account when the token is moved.
1107 FormatTok->ColumnWidth =
1108 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1109 Column += FormatTok->ColumnWidth;
1110 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001111 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001112 // FIXME: ColumnWidth actually depends on the start column, we need to
1113 // take this into account when the token is moved.
1114 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1115 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1116
Alexander Kornienko39856b72013-09-10 09:38:25 +00001117 // The last line of the token always starts in column 0.
1118 // Thus, the length can be precomputed even in the presence of tabs.
1119 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1120 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1121 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001122 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001123 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001124
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001125 if (std::find(ForEachMacros.begin(), ForEachMacros.end(),
1126 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end())
1127 FormatTok->Type = TT_ForEachMacro;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001128
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001129 return FormatTok;
1130 }
1131
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001132 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001133 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001134 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001135 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001136 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001137 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001138 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001139 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001140 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001141 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001142 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001143 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001144 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001145 // Index (in 'Tokens') of the last token that starts a new line.
1146 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001147 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001148 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001149
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001150 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001151
Daniel Jasper8369aa52013-07-16 20:28:33 +00001152 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001153 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001154 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1155 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001156 // For formatting, treat unterminated string literals like normal string
1157 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001158 if (Tok.is(tok::unknown)) {
1159 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1160 Tok.Tok.setKind(tok::string_literal);
1161 Tok.IsUnterminatedLiteral = true;
1162 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1163 Tok.TokenText == "''") {
1164 Tok.Tok.setKind(tok::char_constant);
1165 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001166 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001167
1168 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1169 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001170 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001171 }
1172
Daniel Jasper471894432014-08-06 13:40:26 +00001173 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001174
1175 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1176 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001177 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001178 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001179 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001180
1181 void resetLexer(unsigned Offset) {
1182 StringRef Buffer = SourceMgr.getBufferData(ID);
1183 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1184 getFormattingLangOpts(Style), Buffer.begin(),
1185 Buffer.begin() + Offset, Buffer.end()));
1186 Lex->SetKeepWhitespaceMode(true);
1187 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001188};
1189
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001190static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1191 switch (Language) {
1192 case FormatStyle::LK_Cpp:
1193 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001194 case FormatStyle::LK_Java:
1195 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001196 case FormatStyle::LK_JavaScript:
1197 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001198 case FormatStyle::LK_Proto:
1199 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001200 default:
1201 return "Unknown";
1202 }
1203}
1204
Daniel Jasperf7935112012-12-03 18:12:45 +00001205class Formatter : public UnwrappedLineConsumer {
1206public:
Daniel Jasper23376252014-09-09 14:37:39 +00001207 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001208 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001209 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1210 Whitespaces(SourceMgr, Style,
1211 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001212 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001213 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001214 DEBUG(llvm::dbgs() << "File encoding: "
1215 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1216 : "unknown")
1217 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001218 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1219 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001220 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001221
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001222 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001223 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001224 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001225
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001226 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1227 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001228 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001229 assert(UnwrappedLines.rbegin()->empty());
1230 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1231 ++Run) {
1232 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1233 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1234 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1235 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1236 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001237 tooling::Replacements RunResult =
1238 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001239 DEBUG({
1240 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1241 for (tooling::Replacements::iterator I = RunResult.begin(),
1242 E = RunResult.end();
1243 I != E; ++I) {
1244 llvm::dbgs() << I->toString() << "\n";
1245 }
1246 });
1247 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1248 delete AnnotatedLines[i];
1249 }
1250 Result.insert(RunResult.begin(), RunResult.end());
1251 Whitespaces.reset();
1252 }
1253 return Result;
1254 }
1255
1256 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001257 FormatTokenLexer &Tokens, bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001258 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001259 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001260 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001261 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001262 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001263 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001264 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001265 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001266 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001267
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001268 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001269 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1270 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001271 BinPackInconclusiveFunctions);
Nico Weberfac23712015-02-04 15:26:27 +00001272 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001273 Tokens.getKeywords(), IncompleteFormat);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001274 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001275 return Whitespaces.generateReplacements();
1276 }
1277
1278private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001279 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001280 // Returns \c true if at least one line between I and E or one of their
1281 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001282 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1283 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1284 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001285 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001286 while (I != E) {
1287 AnnotatedLine *Line = *I;
1288 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1289
1290 // If a line is part of a preprocessor directive, it needs to be formatted
1291 // if any token within the directive is affected.
1292 if (Line->InPPDirective) {
1293 FormatToken *Last = Line->Last;
1294 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1295 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1296 Last = (*PPEnd)->Last;
1297 ++PPEnd;
1298 }
1299
1300 if (affectsTokenRange(*Line->First, *Last,
1301 /*IncludeLeadingNewlines=*/false)) {
1302 SomeLineAffected = true;
1303 markAllAsAffected(I, PPEnd);
1304 }
1305 I = PPEnd;
1306 continue;
1307 }
1308
Daniel Jasper38c82402013-11-29 09:27:43 +00001309 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001310 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001311
Daniel Jasper38c82402013-11-29 09:27:43 +00001312 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001313 ++I;
1314 }
1315 return SomeLineAffected;
1316 }
1317
Daniel Jasper9c199562013-11-28 15:58:55 +00001318 // Determines whether 'Line' is affected by the SourceRanges given as input.
1319 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001320 bool nonPPLineAffected(AnnotatedLine *Line,
1321 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001322 bool SomeLineAffected = false;
1323 Line->ChildrenAffected =
1324 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1325 if (Line->ChildrenAffected)
1326 SomeLineAffected = true;
1327
1328 // Stores whether one of the line's tokens is directly affected.
1329 bool SomeTokenAffected = false;
1330 // Stores whether we need to look at the leading newlines of the next token
1331 // in order to determine whether it was affected.
1332 bool IncludeLeadingNewlines = false;
1333
1334 // Stores whether the first child line of any of this line's tokens is
1335 // affected.
1336 bool SomeFirstChildAffected = false;
1337
1338 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1339 // Determine whether 'Tok' was affected.
1340 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1341 SomeTokenAffected = true;
1342
1343 // Determine whether the first child of 'Tok' was affected.
1344 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1345 SomeFirstChildAffected = true;
1346
1347 IncludeLeadingNewlines = Tok->Children.empty();
1348 }
1349
1350 // Was this line moved, i.e. has it previously been on the same line as an
1351 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001352 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1353 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001354
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001355 bool IsContinuedComment =
1356 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1357 Line->First->NewlinesBefore < 2 && PreviousLine &&
1358 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001359
1360 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1361 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001362 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001363 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001364 }
1365 return SomeLineAffected;
1366 }
1367
Daniel Jasper5500f612013-11-25 11:08:59 +00001368 // Marks all lines between I and E as well as all their children as affected.
1369 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1370 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1371 while (I != E) {
1372 (*I)->Affected = true;
1373 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1374 ++I;
1375 }
1376 }
1377
1378 // Returns true if the range from 'First' to 'Last' intersects with one of the
1379 // input ranges.
1380 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1381 bool IncludeLeadingNewlines) {
1382 SourceLocation Start = First.WhitespaceRange.getBegin();
1383 if (!IncludeLeadingNewlines)
1384 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001385 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001386 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001387 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1388 return affectsCharSourceRange(Range);
1389 }
1390
1391 // Returns true if one of the input ranges intersect the leading empty lines
1392 // before 'Tok'.
1393 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1394 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1395 Tok.WhitespaceRange.getBegin(),
1396 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1397 return affectsCharSourceRange(EmptyLineRange);
1398 }
1399
1400 // Returns true if 'Range' intersects with one of the input ranges.
1401 bool affectsCharSourceRange(const CharSourceRange &Range) {
1402 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1403 E = Ranges.end();
1404 I != E; ++I) {
1405 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1406 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1407 return true;
1408 }
1409 return false;
1410 }
1411
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001412 static bool inputUsesCRLF(StringRef Text) {
1413 return Text.count('\r') * 2 > Text.count('\n');
1414 }
1415
Manuel Klimek71814b42013-10-11 21:25:45 +00001416 void
1417 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001418 unsigned CountBoundToVariable = 0;
1419 unsigned CountBoundToType = 0;
1420 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001421 bool HasBinPackedFunction = false;
1422 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001423 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001424 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001425 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001426 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001427 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001428 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001429 bool SpacesBefore =
1430 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1431 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1432 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001433 if (SpacesBefore && !SpacesAfter)
1434 ++CountBoundToVariable;
1435 else if (!SpacesBefore && SpacesAfter)
1436 ++CountBoundToType;
1437 }
1438
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001439 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001440 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001441 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001442 if (Tok->is(TT_TemplateCloser) &&
1443 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001444 HasCpp03IncompatibleFormat = true;
1445 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001446
1447 if (Tok->PackingKind == PPK_BinPacked)
1448 HasBinPackedFunction = true;
1449 if (Tok->PackingKind == PPK_OnePerLine)
1450 HasOnePerLineFunction = true;
1451
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001452 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001453 }
1454 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001455 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001456 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001457 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001458 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001459 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001460 }
1461 if (Style.Standard == FormatStyle::LS_Auto) {
1462 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1463 : FormatStyle::LS_Cpp03;
1464 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001465 BinPackInconclusiveFunctions =
1466 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001467 }
1468
Craig Topperfb6b25b2014-03-15 04:29:04 +00001469 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001470 assert(!UnwrappedLines.empty());
1471 UnwrappedLines.back().push_back(TheLine);
1472 }
1473
Craig Topperfb6b25b2014-03-15 04:29:04 +00001474 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001475 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001476 }
1477
1478 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001479 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001480 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001481 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001482 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001483 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001484
1485 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001486 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001487};
1488
Craig Topperaf35e852013-06-30 22:29:28 +00001489} // end anonymous namespace
1490
Daniel Jasper23376252014-09-09 14:37:39 +00001491tooling::Replacements reformat(const FormatStyle &Style,
1492 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001493 ArrayRef<CharSourceRange> Ranges,
1494 bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001495 if (Style.DisableFormat)
1496 return tooling::Replacements();
1497 Formatter formatter(Style, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001498 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001499}
1500
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001501tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001502 ArrayRef<tooling::Range> Ranges,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001503 StringRef FileName,
1504 bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001505 if (Style.DisableFormat)
1506 return tooling::Replacements();
1507
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001508 FileManager Files((FileSystemOptions()));
1509 DiagnosticsEngine Diagnostics(
1510 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1511 new DiagnosticOptions);
1512 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001513 std::unique_ptr<llvm::MemoryBuffer> Buf =
1514 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001515 const clang::FileEntry *Entry =
1516 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001517 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001518 FileID ID =
1519 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001520 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1521 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001522 for (const tooling::Range &Range : Ranges) {
1523 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1524 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001525 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1526 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001527 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001528}
1529
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001530LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001531 LangOptions LangOpts;
1532 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001533 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1534 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001535 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001536 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001537 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001538 LangOpts.Bool = 1;
1539 LangOpts.ObjC1 = 1;
1540 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001541 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001542 return LangOpts;
1543}
1544
Edwin Vaned544aa72013-09-30 13:31:48 +00001545const char *StyleOptionHelpDescription =
1546 "Coding style, currently supports:\n"
1547 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1548 "Use -style=file to load style configuration from\n"
1549 ".clang-format file located in one of the parent\n"
1550 "directories of the source file (or current\n"
1551 "directory for stdin).\n"
1552 "Use -style=\"{key: value, ...}\" to set specific\n"
1553 "parameters, e.g.:\n"
1554 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1555
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001556static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001557 if (FileName.endswith(".java")) {
1558 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001559 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1560 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001561 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001562 } else if (FileName.endswith_lower(".proto") ||
1563 FileName.endswith_lower(".protodevel")) {
1564 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001565 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001566 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001567}
1568
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001569FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1570 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001571 FormatStyle Style = getLLVMStyle();
1572 Style.Language = getLanguageByFileName(FileName);
1573 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001574 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1575 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001576 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001577 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001578
1579 if (StyleName.startswith("{")) {
1580 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001581 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001582 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1583 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001584 }
1585 return Style;
1586 }
1587
1588 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001589 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001590 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1591 << " style\n";
1592 return Style;
1593 }
1594
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001595 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001596 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001597 SmallString<128> Path(FileName);
1598 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001599 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001600 Directory = llvm::sys::path::parent_path(Directory)) {
1601 if (!llvm::sys::fs::is_directory(Directory))
1602 continue;
1603 SmallString<128> ConfigFile(Directory);
1604
1605 llvm::sys::path::append(ConfigFile, ".clang-format");
1606 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1607 bool IsFile = false;
1608 // Ignore errors from is_regular_file: we only need to know if we can read
1609 // the file or not.
1610 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1611
1612 if (!IsFile) {
1613 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1614 ConfigFile = Directory;
1615 llvm::sys::path::append(ConfigFile, "_clang-format");
1616 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1617 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1618 }
1619
1620 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001621 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1622 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1623 if (std::error_code EC = Text.getError()) {
1624 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001625 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001626 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001627 if (std::error_code ec =
1628 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001629 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001630 if (!UnsuitableConfigFiles.empty())
1631 UnsuitableConfigFiles.append(", ");
1632 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001633 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001634 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001635 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1636 << "\n";
1637 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001638 }
1639 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1640 return Style;
1641 }
1642 }
1643 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1644 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001645 if (!UnsuitableConfigFiles.empty()) {
1646 llvm::errs() << "Configuration file(s) do(es) not support "
1647 << getLanguageName(Style.Language) << ": "
1648 << UnsuitableConfigFiles << "\n";
1649 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001650 return Style;
1651}
1652
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001653} // namespace format
1654} // namespace clang