blob: dea2386e0ace35b546e5134dd98f2a783f9d863e [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000045 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 }
47};
48
49template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56 }
57};
58
59template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66 }
67};
68
Daniel Jasperd74cf402014-04-08 12:46:38 +000069template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71 IO.enumCase(Value, "None", FormatStyle::SFS_None);
72 IO.enumCase(Value, "false", FormatStyle::SFS_None);
73 IO.enumCase(Value, "All", FormatStyle::SFS_All);
74 IO.enumCase(Value, "true", FormatStyle::SFS_All);
75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76 }
77};
78
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000085 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086 }
87};
88
Alexander Kornienkod6538332013-05-07 15:32:14 +000089template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000091 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 FormatStyle::NamespaceIndentationKind &Value) {
93 IO.enumCase(Value, "None", FormatStyle::NI_None);
94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000096 }
97};
98
99template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000100struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000101 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102 FormatStyle::SpaceBeforeParensOptions &Value) {
103 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000104 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 FormatStyle::SBPO_ControlStatements);
106 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000107
108 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000109 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
110 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000111 }
112};
113
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000115 static void mapping(IO &IO, FormatStyle &Style) {
116 // When reading, read the language first, we need it for getPredefinedStyle.
117 IO.mapOptional("Language", Style.Language);
118
Alexander Kornienko49149672013-05-10 11:56:10 +0000119 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000120 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000121 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000122 ArrayRef<StringRef> Styles(StylesArray);
123 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
124 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000126 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000127 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000128 IO.mapOptional("# BasedOnStyle", StyleName);
129 break;
130 }
131 }
132 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000133 StringRef BasedOnStyle;
134 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000135 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000136 FormatStyle::LanguageKind OldLanguage = Style.Language;
137 FormatStyle::LanguageKind Language =
138 ((FormatStyle *)IO.getContext())->Language;
139 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000140 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
141 return;
142 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000143 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000144 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000145 }
146
147 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000148 IO.mapOptional("ConstructorInitializerIndentWidth",
149 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000150 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000151 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000152 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
153 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000154 IO.mapOptional("AllowShortBlocksOnASingleLine",
155 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000156 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
157 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000158 IO.mapOptional("AllowShortLoopsOnASingleLine",
159 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000160 IO.mapOptional("AllowShortFunctionsOnASingleLine",
161 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000162 IO.mapOptional("AlwaysBreakTemplateDeclarations",
163 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000164 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
165 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000166 IO.mapOptional("BreakBeforeBinaryOperators",
167 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000168 IO.mapOptional("BreakBeforeTernaryOperators",
169 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000170 IO.mapOptional("BreakConstructorInitializersBeforeComma",
171 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000172 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
173 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
174 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
175 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
176 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000177 IO.mapOptional("ExperimentalAutoDetectBinPacking",
178 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000179 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
180 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000181 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
182 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000183 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000184 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185 IO.mapOptional("ObjCSpaceBeforeProtocolList",
186 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000187 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
188 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000189 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
190 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000191 IO.mapOptional("PenaltyBreakFirstLessLess",
192 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000193 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
194 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
195 Style.PenaltyReturnTypeOnItsOwnLine);
196 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
197 IO.mapOptional("SpacesBeforeTrailingComments",
198 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000199 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000201 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000202 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000203 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000204 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000205 IO.mapOptional("IndentFunctionDeclarationAfterType",
206 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000207 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000208 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000209 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000210 IO.mapOptional("SpacesInCStyleCastParentheses",
211 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000212 IO.mapOptional("SpacesInContainerLiterals",
213 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000214 IO.mapOptional("SpaceBeforeAssignmentOperators",
215 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000216 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000217 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000218 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000219
220 // For backward compatibility.
221 if (!IO.outputting()) {
222 IO.mapOptional("SpaceAfterControlStatementKeyword",
223 Style.SpaceBeforeParens);
224 }
225 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000226 }
227};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000228
229// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000230// IO.getContext() should contain a pointer to the FormatStyle structure, that
231// will be used to get default values for missing keys.
232// If the first element has no Language specified, it will be treated as the
233// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000234template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000235 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
236 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000237 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000238 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000239 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000240 if (Index >= Seq.size()) {
241 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000242 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000243 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000244 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000245 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000246 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000247 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000248 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000249 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000250 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000251 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000252 }
253};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000254}
255}
256
Daniel Jasperf7935112012-12-03 18:12:45 +0000257namespace clang {
258namespace format {
259
Daniel Jasperf7935112012-12-03 18:12:45 +0000260FormatStyle getLLVMStyle() {
261 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000262 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000263 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000264 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000265 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000266 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000267 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000268 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000269 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000270 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000271 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000272 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000273 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000274 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000275 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000276 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
277 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000278 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000279 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000280 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000281 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000282 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000283 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000284 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000285 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000286 LLVMStyle.ForEachMacros.push_back("foreach");
287 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
288 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000289 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000290 LLVMStyle.IndentFunctionDeclarationAfterType = false;
291 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000292 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000293 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000294 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000295 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000296 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000297 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000298 LLVMStyle.PointerBindsToType = false;
299 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000300 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000301 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000302 LLVMStyle.SpacesInParentheses = false;
303 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000304 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000305 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000306 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000307 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000308 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000309
Daniel Jasper19a541e2013-12-19 16:45:34 +0000310 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000311 LLVMStyle.PenaltyBreakFirstLessLess = 120;
312 LLVMStyle.PenaltyBreakString = 1000;
313 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000314 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000315 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000316
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 return LLVMStyle;
318}
319
Nico Weber514ecc82014-02-02 20:50:45 +0000320FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000321 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000322 GoogleStyle.Language = Language;
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000325 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000326 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000327 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000328 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000329 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000330 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
331 GoogleStyle.DerivePointerBinding = true;
332 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000333 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000334 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000335 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000336 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000337 GoogleStyle.PointerBindsToType = true;
338 GoogleStyle.SpacesBeforeTrailingComments = 2;
339 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000340
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000341 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000342 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000343
Nico Weber514ecc82014-02-02 20:50:45 +0000344 if (Language == FormatStyle::LK_JavaScript) {
345 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000346 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000347 GoogleStyle.SpacesInContainerLiterals = false;
348 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000349 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000350 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000351 }
352
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 return GoogleStyle;
354}
355
Nico Weber514ecc82014-02-02 20:50:45 +0000356FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
357 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000358 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000359 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000360 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000361 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000362 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000363 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000364 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000365 return ChromiumStyle;
366}
367
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000368FormatStyle getMozillaStyle() {
369 FormatStyle MozillaStyle = getLLVMStyle();
370 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000371 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000372 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
373 MozillaStyle.DerivePointerBinding = true;
374 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000375 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000376 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
377 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
378 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000379 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000380 return MozillaStyle;
381}
382
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000383FormatStyle getWebKitStyle() {
384 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000385 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000386 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000387 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000388 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000389 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000390 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000391 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000392 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000393 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000394 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000395 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000396 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000397 return Style;
398}
399
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000400FormatStyle getGNUStyle() {
401 FormatStyle Style = getLLVMStyle();
402 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000403 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000404 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000405 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000406 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000407 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000408 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000409 return Style;
410}
411
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000412bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
413 FormatStyle *Style) {
414 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000415 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000416 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000417 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000418 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000419 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000420 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000421 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000422 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000423 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000424 } else if (Name.equals_lower("gnu")) {
425 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000426 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000427 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000428 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000429
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000430 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000431 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000432}
433
434llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000435 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000436 FormatStyle::LanguageKind Language = Style->Language;
437 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000438 if (Text.trim().empty())
439 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000440
441 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000442 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000443 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
444 // values for the fields, keys for which are missing from the configuration.
445 // Mapping also uses the context to get the language to find the correct
446 // base style.
447 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000448 Input >> Styles;
449 if (Input.error())
450 return Input.error();
451
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000452 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000453 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000454 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000455 return llvm::make_error_code(llvm::errc::invalid_argument);
456 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000457 for (unsigned j = 0; j < i; ++j) {
458 if (Styles[i].Language == Styles[j].Language) {
459 DEBUG(llvm::dbgs()
460 << "Duplicate languages in the config file on positions " << j
461 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000462 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000463 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000464 }
465 }
466 // Look for a suitable configuration starting from the end, so we can
467 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000468 // configuration (which can only be at slot 0) after it.
469 for (int i = Styles.size() - 1; i >= 0; --i) {
470 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000471 Styles[i].Language == FormatStyle::LK_None) {
472 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000473 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000474 return llvm::make_error_code(llvm::errc::success);
475 }
476 }
477 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000478}
479
480std::string configurationAsText(const FormatStyle &Style) {
481 std::string Text;
482 llvm::raw_string_ostream Stream(Text);
483 llvm::yaml::Output Output(Stream);
484 // We use the same mapping method for input and output, so we need a non-const
485 // reference here.
486 FormatStyle NonConstStyle = Style;
487 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000488 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000489}
490
Craig Topperaf35e852013-06-30 22:29:28 +0000491namespace {
492
Daniel Jasperde0328a2013-08-16 11:20:30 +0000493class NoColumnLimitFormatter {
494public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000495 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000496
497 /// \brief Formats the line starting at \p State, simply keeping all of the
498 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000499 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000500 LineState State =
501 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000502 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000503 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000504 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000505 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
506 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
507 }
508 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000509
Daniel Jasperde0328a2013-08-16 11:20:30 +0000510private:
511 ContinuationIndenter *Indenter;
512};
513
Daniel Jasper56f8b432013-11-06 23:12:09 +0000514class LineJoiner {
515public:
516 LineJoiner(const FormatStyle &Style) : Style(Style) {}
517
518 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
519 unsigned
520 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000521 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000522 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
523 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000524 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000525 if (TheLine->Last->Type == TT_LineComment)
526 return 0;
527
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000528 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
529 return 0;
530
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000531 unsigned Limit =
532 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000533 // If we already exceed the column limit, we set 'Limit' to 0. The different
534 // tryMerge..() functions can then decide whether to still do merging.
535 Limit = TheLine->Last->TotalLength > Limit
536 ? 0
537 : Limit - TheLine->Last->TotalLength;
538
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000539 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000540 return 0;
541
Daniel Jasperd74cf402014-04-08 12:46:38 +0000542 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
543 // If necessary, change to something smarter.
544 bool MergeShortFunctions =
545 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
546 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
547 TheLine->Level != 0);
548
Daniel Jasper234379f2013-12-24 13:31:25 +0000549 if (TheLine->Last->Type == TT_FunctionLBrace &&
550 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000551 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000552 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000553 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000554 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000555 ? tryMergeSimpleBlock(I, E, Limit)
556 : 0;
557 }
558 if (I[1]->First->Type == TT_FunctionLBrace &&
559 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000560 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000561 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
562 return 0;
563 Limit -= 2;
564
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000565 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000566 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000567 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
568 // If we managed to merge the block, count the function header, which is
569 // on a separate line.
570 if (MergedLines > 0)
571 ++MergedLines;
572 }
573 return MergedLines;
574 }
575 if (TheLine->First->is(tok::kw_if)) {
576 return Style.AllowShortIfStatementsOnASingleLine
577 ? tryMergeSimpleControlStatement(I, E, Limit)
578 : 0;
579 }
580 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
581 return Style.AllowShortLoopsOnASingleLine
582 ? tryMergeSimpleControlStatement(I, E, Limit)
583 : 0;
584 }
585 if (TheLine->InPPDirective &&
586 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000587 return tryMergeSimplePPDirective(I, E, Limit);
588 }
589 return 0;
590 }
591
592private:
593 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000594 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000595 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
596 unsigned Limit) {
597 if (Limit == 0)
598 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000599 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000600 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000601 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000602 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000603 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000604 return 0;
605 return 1;
606 }
607
608 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000609 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000610 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
611 if (Limit == 0)
612 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000613 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
614 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000615 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000617 if (I[1]->InPPDirective != (*I)->InPPDirective ||
618 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000619 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000620 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000621 AnnotatedLine &Line = **I;
622 if (Line.Last->isNot(tok::r_paren))
623 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000624 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000625 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000626 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000627 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000628 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000629 return 0;
630 // Only inline simple if's (no nested if or else).
631 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000632 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000633 return 0;
634 return 1;
635 }
636
637 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000638 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000639 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
640 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000641 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000642
643 // Don't merge ObjC @ keywords and methods.
644 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000645 return 0;
646
Daniel Jasper17605d32014-05-14 09:33:35 +0000647 // Check that the current line allows merging. This depends on whether we
648 // are in a control flow statements as well as several style flags.
649 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
650 return 0;
651 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
652 tok::kw_catch, tok::kw_for, tok::r_brace)) {
653 if (!Style.AllowShortBlocksOnASingleLine)
654 return 0;
655 if (!Style.AllowShortIfStatementsOnASingleLine &&
656 Line.First->is(tok::kw_if))
657 return 0;
658 if (!Style.AllowShortLoopsOnASingleLine &&
659 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
660 return 0;
661 // FIXME: Consider an option to allow short exception handling clauses on
662 // a single line.
663 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
664 return 0;
665 }
666
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000667 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000669 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 Tok->getNextNonComment()->is(tok::semi))) {
671 // We merge empty blocks even if the line exceeds the column limit.
672 Tok->SpacesRequiredBefore = 0;
673 Tok->CanBreakBefore = true;
674 return 1;
675 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000676 // We don't merge short records.
677 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
678 return 0;
679
Daniel Jasper56f8b432013-11-06 23:12:09 +0000680 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000681 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000682 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000683 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000684
685 if (!nextTwoLinesFitInto(I, Limit))
686 return 0;
687
688 // Second, check that the next line does not contain any braces - if it
689 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000690 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000691 return 0;
692 do {
Daniel Jasper17605d32014-05-14 09:33:35 +0000693 if (Tok->isOneOf(tok::l_brace, tok::r_brace) &&
694 !Style.AllowShortBlocksOnASingleLine)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000695 return 0;
696 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000697 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000698
Daniel Jasper79dffb42014-05-07 09:48:30 +0000699 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000701 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000702 return 0;
703
704 return 2;
705 }
706 return 0;
707 }
708
Daniel Jasper64989962014-02-07 13:45:27 +0000709 /// Returns the modified column limit for \p I if it is inside a macro and
710 /// needs a trailing '\'.
711 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000712 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000713 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
714 unsigned Limit) {
715 if (I[0]->InPPDirective && I + 1 != E &&
716 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
717 return Limit < 2 ? 0 : Limit - 2;
718 }
719 return Limit;
720 }
721
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
723 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000724 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
725 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000726 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000727 }
728
Daniel Jasper234379f2013-12-24 13:31:25 +0000729 bool containsMustBreak(const AnnotatedLine *Line) {
730 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
731 if (Tok->MustBreakBefore)
732 return true;
733 }
734 return false;
735 }
736
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 const FormatStyle &Style;
738};
739
Daniel Jasperf7935112012-12-03 18:12:45 +0000740class UnwrappedLineFormatter {
741public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000742 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000743 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000744 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000745 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
746 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000747
Daniel Jasper56f8b432013-11-06 23:12:09 +0000748 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000749 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000750 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000751 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
752 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000753 auto CacheIt = PenaltyCache.find(CacheKey);
754 if (DryRun && CacheIt != PenaltyCache.end())
755 return CacheIt->second;
756
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000757 assert(!Lines.empty());
758 unsigned Penalty = 0;
759 std::vector<int> IndentForLevel;
760 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
761 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000762 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000763 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
764 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000765 I != E; ++I) {
766 const AnnotatedLine &TheLine = **I;
767 const FormatToken *FirstTok = TheLine.First;
768 int Offset = getIndentOffset(*FirstTok);
769
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000770 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000771 unsigned Indent;
772 if (TheLine.InPPDirective) {
773 Indent = TheLine.Level * Style.IndentWidth;
774 } else {
775 while (IndentForLevel.size() <= TheLine.Level)
776 IndentForLevel.push_back(-1);
777 IndentForLevel.resize(TheLine.Level + 1);
778 Indent = getIndent(IndentForLevel, TheLine.Level);
779 }
780 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000781 if (static_cast<int>(Indent) + Offset >= 0)
782 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000783
784 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000785 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000786 if (MergedLines > 0 && Style.ColumnLimit == 0) {
787 // Disallow line merging if there is a break at the start of one of the
788 // input lines.
789 for (unsigned i = 0; i < MergedLines; ++i) {
790 if (I[i + 1]->First->NewlinesBefore > 0)
791 MergedLines = 0;
792 }
793 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000794 if (!DryRun) {
795 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000796 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000797 }
798 }
799 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000800
Daniel Jasper9c199562013-11-28 15:58:55 +0000801 bool FixIndentation =
802 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000803 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000804 if (PreviousLine && PreviousLine->Affected && !DryRun) {
805 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000806 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
807 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
808 /*IndentLevel=*/0, /*Spaces=*/0,
809 /*TargetColumn=*/0);
810 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000811 } else if (TheLine.Type != LT_Invalid &&
812 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000813 if (FirstTok->WhitespaceRange.isValid()) {
814 if (!DryRun)
815 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
816 Indent, TheLine.InPPDirective);
817 } else {
818 Indent = LevelIndent = FirstTok->OriginalColumn;
819 }
820
821 // If everything fits on a single line, just put it there.
822 unsigned ColumnLimit = Style.ColumnLimit;
823 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000824 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000825 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
826 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
827 }
828
829 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
830 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Craig Topper2145bc02014-05-09 08:15:10 +0000831 while (State.NextToken)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000832 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
833 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000834 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000835 NoColumnLimitFormatter Formatter(Indenter);
836 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000837 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000838 } else {
839 Penalty += format(TheLine, Indent, DryRun);
840 }
841
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000842 if (!TheLine.InPPDirective)
843 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000844 } else if (TheLine.ChildrenAffected) {
845 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000846 } else {
847 // Format the first token if necessary, and notify the WhitespaceManager
848 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000849 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000850 if (Tok == TheLine.First &&
851 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
852 unsigned LevelIndent = Tok->OriginalColumn;
853 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000854 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000855 if ((PreviousLine && PreviousLine->Affected) ||
856 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000857 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
858 TheLine.InPPDirective);
859 } else {
860 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
861 }
862 }
863
864 if (static_cast<int>(LevelIndent) - Offset >= 0)
865 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000866 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000867 IndentForLevel[TheLine.Level] = LevelIndent;
868 } else if (!DryRun) {
869 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
870 }
871 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000872 }
873 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000874 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000875 Tok->Finalized = true;
876 }
877 }
878 PreviousLine = *I;
879 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000880 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000881 return Penalty;
882 }
883
884private:
885 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000886 ///
887 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000888 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
889 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000890 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000891
Daniel Jasperacc33662013-02-08 08:22:00 +0000892 // If the ObjC method declaration does not fit on a line, we should format
893 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000894 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000895 State.Stack.back().BreakBeforeParameter = true;
896
Daniel Jasper4b866272013-02-01 11:00:45 +0000897 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000898 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000899 }
900
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000901 /// \brief An edge in the solution space from \c Previous->State to \c State,
902 /// inserting a newline dependent on the \c NewLine.
903 struct StateNode {
904 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000905 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 LineState State;
907 bool NewLine;
908 StateNode *Previous;
909 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000910
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000911 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
912 ///
913 /// In case of equal penalties, we want to prefer states that were inserted
914 /// first. During state generation we make sure that we insert states first
915 /// that break the line as late as possible.
916 typedef std::pair<unsigned, unsigned> OrderedPenalty;
917
918 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
919 /// \c State has the given \c OrderedPenalty.
920 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
921
922 /// \brief The BFS queue type.
923 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
924 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000925
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000926 /// \brief Get the offset of the line relatively to the level.
927 ///
928 /// For example, 'public:' labels in classes are offset by 1 or 2
929 /// characters to the left from their level.
930 int getIndentOffset(const FormatToken &RootToken) {
931 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
932 return Style.AccessModifierOffset;
933 return 0;
934 }
935
936 /// \brief Add a new line and the required indent before the first Token
937 /// of the \c UnwrappedLine if there was no structural parsing error.
938 void formatFirstToken(FormatToken &RootToken,
939 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
940 unsigned Indent, bool InPPDirective) {
941 unsigned Newlines =
942 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
943 // Remove empty lines before "}" where applicable.
944 if (RootToken.is(tok::r_brace) &&
945 (!RootToken.Next ||
946 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
947 Newlines = std::min(Newlines, 1u);
948 if (Newlines == 0 && !RootToken.IsFirst)
949 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000950 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
951 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000952
Daniel Jasper11164bd2014-03-21 12:58:53 +0000953 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000954 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
955 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000956 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000957 Newlines = 1;
958
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000959 // Insert extra new line before access specifiers.
960 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
961 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
962 ++Newlines;
963
964 // Remove empty lines after access specifiers.
965 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
966 Newlines = std::min(1u, Newlines);
967
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000968 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
969 Indent, InPPDirective &&
970 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000971 }
972
973 /// \brief Get the indent of \p Level from \p IndentForLevel.
974 ///
975 /// \p IndentForLevel must contain the indent for the level \c l
976 /// at \p IndentForLevel[l], or a value < 0 if the indent for
977 /// that level is unknown.
978 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
979 if (IndentForLevel[Level] != -1)
980 return IndentForLevel[Level];
981 if (Level == 0)
982 return 0;
983 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
984 }
985
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000986 void join(AnnotatedLine &A, const AnnotatedLine &B) {
987 assert(!A.Last->Next);
988 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000989 if (B.Affected)
990 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000991 A.Last->Next = B.First;
992 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000993 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000994 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
995 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
996 Tok->TotalLength += LengthA;
997 A.Last = Tok;
998 }
999 }
1000
1001 unsigned getColumnLimit(bool InPPDirective) const {
1002 // In preprocessor directives reserve two chars for trailing " \"
1003 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1004 }
1005
Daniel Jasper4b866272013-02-01 11:00:45 +00001006 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001008 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1009 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1010 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001011 /// to a state where all tokens are placed. Returns the penalty.
1012 ///
1013 /// If \p DryRun is \c false, directly applies the changes.
1014 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001015 std::set<LineState> Seen;
1016
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001017 // Increasing count of \c StateNode items we have created. This is used to
1018 // create a deterministic order independent of the container.
1019 unsigned Count = 0;
1020 QueueType Queue;
1021
Daniel Jasper4b866272013-02-01 11:00:45 +00001022 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001023 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001024 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001025 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1026 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001027
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001028 unsigned Penalty = 0;
1029
Daniel Jasper4b866272013-02-01 11:00:45 +00001030 // While not empty, take first element and follow edges.
1031 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001032 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001033 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001034 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001035 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001036 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001037 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001038 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001039
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001040 // Cut off the analysis of certain solutions if the analysis gets too
1041 // complex. See description of IgnoreStackForComparison.
1042 if (Count > 10000)
1043 Node->State.IgnoreStackForComparison = true;
1044
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001045 if (!Seen.insert(Node->State).second)
1046 // State already examined with lower penalty.
1047 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001048
Manuel Klimek71814b42013-10-11 21:25:45 +00001049 FormatDecision LastFormat = Node->State.NextToken->Decision;
1050 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001051 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001052 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001053 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001054 }
1055
Manuel Klimek71814b42013-10-11 21:25:45 +00001056 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001057 // We were unable to find a solution, do nothing.
1058 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001059 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001060 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001061 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001062
Daniel Jasper4b866272013-02-01 11:00:45 +00001063 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001064 if (!DryRun)
1065 reconstructPath(InitialState, Queue.top().second);
1066
Alexander Kornienko49149672013-05-10 11:56:10 +00001067 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1068 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001069
1070 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001071 }
1072
1073 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001074 std::deque<StateNode *> Path;
1075 // We do not need a break before the initial token.
1076 while (Current->Previous) {
1077 Path.push_front(Current);
1078 Current = Current->Previous;
1079 }
1080 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1081 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001082 unsigned Penalty = 0;
1083 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1084 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1085
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001086 DEBUG({
1087 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001088 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001089 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001090 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001091 }
1092 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001093 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001094 }
1095
Manuel Klimekaf491072013-02-13 10:54:19 +00001096 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001097 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001098 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001099 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001100 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001101 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001102 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001103 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001104 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001105 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001106
1107 StateNode *Node = new (Allocator.Allocate())
1108 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001109 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1110 return;
1111
Daniel Jasperde0328a2013-08-16 11:20:30 +00001112 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001113
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001114 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1115 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001116 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001117
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001118 /// \brief If the \p State's next token is an r_brace closing a nested block,
1119 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001120 ///
1121 /// Returns \c true if all children could be placed successfully and adapts
1122 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1123 /// creates changes using \c Whitespaces.
1124 ///
1125 /// The crucial idea here is that children always get formatted upon
1126 /// encountering the closing brace right after the nested block. Now, if we
1127 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1128 /// \c false), the entire block has to be kept on the same line (which is only
1129 /// possible if it fits on the line, only contains a single statement, etc.
1130 ///
1131 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1132 /// break after the "{", format all lines with correct indentation and the put
1133 /// the closing "}" on yet another new line.
1134 ///
1135 /// This enables us to keep the simple structure of the
1136 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1137 /// break or don't break.
1138 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1139 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001140 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001141 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1142 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1143 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001144 // The previous token does not open a block. Nothing to do. We don't
1145 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001146 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001147
1148 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001149 int AdditionalIndent = State.Stack.back().Indent -
1150 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001151 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1152 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001153 return true;
1154 }
1155
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001156 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001157 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001158 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001159
Daniel Jasper21397a32014-04-09 12:21:48 +00001160 // Cannot merge into one line if this line ends on a comment.
1161 if (Previous.is(tok::comment))
1162 return false;
1163
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001164 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001165 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001166 return false;
1167
Daniel Jasper98583d52014-04-15 08:28:06 +00001168 // If the child line exceeds the column limit, we wouldn't want to merge it.
1169 // We add +2 for the trailing " }".
1170 if (Style.ColumnLimit > 0 &&
1171 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1172 Style.ColumnLimit)
1173 return false;
1174
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001175 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001176 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001177 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001178 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001179 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001180 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001181 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001182
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001183 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001184 return true;
1185 }
1186
Daniel Jasperde0328a2013-08-16 11:20:30 +00001187 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001188 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001189 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001190 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001191
1192 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001193
1194 // Cache to store the penalty of formatting a vector of AnnotatedLines
1195 // starting from a specific additional offset. Improves performance if there
1196 // are many nested blocks.
1197 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1198 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001199};
1200
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001201class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001202public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001203 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001204 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001205 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1206 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1207 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001208 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001209 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001210
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001211 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001212 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1213 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001214 }
1215
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001216 ArrayRef<FormatToken *> lex() {
1217 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001218 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001219 do {
1220 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001221 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001222 if (Tokens.back()->NewlinesBefore > 0)
1223 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001224 } while (Tokens.back()->Tok.isNot(tok::eof));
1225 return Tokens;
1226 }
1227
1228 IdentifierTable &getIdentTable() { return IdentTable; }
1229
1230private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001231 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001232 if (tryMerge_TMacro())
1233 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001234 if (tryMergeConflictMarkers())
1235 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001236
1237 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001238 if (tryMergeEscapeSequence())
1239 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001240 if (tryMergeJSRegexLiteral())
1241 return;
1242
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001243 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1244 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1245 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1246 tok::greaterequal };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001247 // FIXME: We probably need to change token type to mimic operator with the
1248 // correct priority.
1249 if (tryMergeTokens(JSIdentity))
1250 return;
1251 if (tryMergeTokens(JSNotIdentity))
1252 return;
1253 if (tryMergeTokens(JSShiftEqual))
1254 return;
1255 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001256 }
1257
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001258 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1259 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001260 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001261
1262 SmallVectorImpl<FormatToken *>::const_iterator First =
1263 Tokens.end() - Kinds.size();
1264 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001265 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001266 unsigned AddLength = 0;
1267 for (unsigned i = 1; i < Kinds.size(); ++i) {
1268 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1269 First[i]->WhitespaceRange.getEnd())
1270 return false;
1271 AddLength += First[i]->TokenText.size();
1272 }
1273 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1274 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1275 First[0]->TokenText.size() + AddLength);
1276 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001277 return true;
1278 }
1279
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001280 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001281 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001282 bool tryMergeEscapeSequence() {
1283 if (Tokens.size() < 2)
1284 return false;
1285 FormatToken *Previous = Tokens[Tokens.size() - 2];
1286 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1287 Tokens.back()->NewlinesBefore != 0)
1288 return false;
1289 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1290 StringRef Text = Previous->TokenText;
1291 Previous->TokenText =
1292 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1293 Tokens.resize(Tokens.size() - 1);
1294 return true;
1295 }
1296
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001297 // Try to determine whether the current token ends a JavaScript regex literal.
1298 // We heuristically assume that this is a regex literal if we find two
1299 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001300 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1301 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001302 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001303 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001304 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1305 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001306 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001307 unsigned TokenCount = 0;
1308 unsigned LastColumn = Tokens.back()->OriginalColumn;
1309 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1310 ++TokenCount;
1311 if (I[0]->is(tok::slash) && I + 1 != E &&
1312 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1313 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1314 tok::question, tok::kw_return) ||
1315 I[1]->isBinaryOperator())) {
1316 Tokens.resize(Tokens.size() - TokenCount);
1317 Tokens.back()->Tok.setKind(tok::unknown);
1318 Tokens.back()->Type = TT_RegexLiteral;
1319 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1320 return true;
1321 }
1322
1323 // There can't be a newline inside a regex literal.
1324 if (I[0]->NewlinesBefore > 0)
1325 return false;
1326 }
1327 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001328 }
1329
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001330 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001331 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001332 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001333 FormatToken *Last = Tokens.back();
1334 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001335 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001336
1337 FormatToken *String = Tokens[Tokens.size() - 2];
1338 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001339 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001340
1341 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001342 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001343
1344 FormatToken *Macro = Tokens[Tokens.size() - 4];
1345 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001346 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001347
1348 const char *Start = Macro->TokenText.data();
1349 const char *End = Last->TokenText.data() + Last->TokenText.size();
1350 String->TokenText = StringRef(Start, End - Start);
1351 String->IsFirst = Macro->IsFirst;
1352 String->LastNewlineOffset = Macro->LastNewlineOffset;
1353 String->WhitespaceRange = Macro->WhitespaceRange;
1354 String->OriginalColumn = Macro->OriginalColumn;
1355 String->ColumnWidth = encoding::columnWidthWithTabs(
1356 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1357
1358 Tokens.pop_back();
1359 Tokens.pop_back();
1360 Tokens.pop_back();
1361 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001362 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001363 }
1364
Manuel Klimek68b03042014-04-14 09:14:11 +00001365 bool tryMergeConflictMarkers() {
1366 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1367 return false;
1368
1369 // Conflict lines look like:
1370 // <marker> <text from the vcs>
1371 // For example:
1372 // >>>>>>> /file/in/file/system at revision 1234
1373 //
1374 // We merge all tokens in a line that starts with a conflict marker
1375 // into a single token with a special token type that the unwrapped line
1376 // parser will use to correctly rebuild the underlying code.
1377
1378 FileID ID;
1379 // Get the position of the first token in the line.
1380 unsigned FirstInLineOffset;
1381 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1382 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1383 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1384 // Calculate the offset of the start of the current line.
1385 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1386 if (LineOffset == StringRef::npos) {
1387 LineOffset = 0;
1388 } else {
1389 ++LineOffset;
1390 }
1391
1392 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1393 StringRef LineStart;
1394 if (FirstSpace == StringRef::npos) {
1395 LineStart = Buffer.substr(LineOffset);
1396 } else {
1397 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1398 }
1399
1400 TokenType Type = TT_Unknown;
1401 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1402 Type = TT_ConflictStart;
1403 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1404 LineStart == "====") {
1405 Type = TT_ConflictAlternative;
1406 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1407 Type = TT_ConflictEnd;
1408 }
1409
1410 if (Type != TT_Unknown) {
1411 FormatToken *Next = Tokens.back();
1412
1413 Tokens.resize(FirstInLineIndex + 1);
1414 // We do not need to build a complete token here, as we will skip it
1415 // during parsing anyway (as we must not touch whitespace around conflict
1416 // markers).
1417 Tokens.back()->Type = Type;
1418 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1419
1420 Tokens.push_back(Next);
1421 return true;
1422 }
1423
1424 return false;
1425 }
1426
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001427 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001428 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001429 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001430 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001431 Token Greater = FormatTok->Tok;
1432 FormatTok = new (Allocator.Allocate()) FormatToken;
1433 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001434 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001435 FormatTok->Tok.getLocation().getLocWithOffset(1);
1436 FormatTok->WhitespaceRange =
1437 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001438 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001439 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001440 GreaterStashed = false;
1441 return FormatTok;
1442 }
1443
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001444 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001445 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001446 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001447 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001448 FormatTok->IsFirst = IsFirstToken;
1449 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001450
1451 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001452 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001453 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001454 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1455 switch (FormatTok->TokenText[i]) {
1456 case '\n':
1457 ++FormatTok->NewlinesBefore;
1458 // FIXME: This is technically incorrect, as it could also
1459 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001460 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1461 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1462 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001463 FormatTok->HasUnescapedNewline = true;
1464 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1465 Column = 0;
1466 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001467 case '\r':
1468 case '\f':
1469 case '\v':
1470 Column = 0;
1471 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001472 case ' ':
1473 ++Column;
1474 break;
1475 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001476 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001477 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001478 case '\\':
1479 ++Column;
1480 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1481 FormatTok->TokenText[i + 1] != '\n'))
1482 FormatTok->Type = TT_ImplicitStringLiteral;
1483 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001484 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001485 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001486 ++Column;
1487 break;
1488 }
1489 }
1490
Daniel Jasper877615c2013-10-11 19:45:02 +00001491 if (FormatTok->Type == TT_ImplicitStringLiteral)
1492 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001493 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001494
Daniel Jasper8369aa52013-07-16 20:28:33 +00001495 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001496 }
Manuel Klimekef920692013-01-07 07:56:50 +00001497
Manuel Klimek1abf7892013-01-04 23:34:14 +00001498 // In case the token starts with escaped newlines, we want to
1499 // take them into account as whitespace - this pattern is quite frequent
1500 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001501 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001502 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1503 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001504 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001505 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001506 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001507 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001508 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001509
1510 FormatTok->WhitespaceRange = SourceRange(
1511 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1512
Manuel Klimek31c85922013-08-29 15:21:40 +00001513 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001514
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001515 TrailingWhitespace = 0;
1516 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001517 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001518 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001519 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001520 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001521 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001522 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001523 FormatTok->Tok.setIdentifierInfo(&Info);
1524 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001525 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001526 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001527 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001528 GreaterStashed = true;
1529 }
1530
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001531 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001532
Alexander Kornienko39856b72013-09-10 09:38:25 +00001533 StringRef Text = FormatTok->TokenText;
1534 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001535 if (FirstNewlinePos == StringRef::npos) {
1536 // FIXME: ColumnWidth actually depends on the start column, we need to
1537 // take this into account when the token is moved.
1538 FormatTok->ColumnWidth =
1539 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1540 Column += FormatTok->ColumnWidth;
1541 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001542 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001543 // FIXME: ColumnWidth actually depends on the start column, we need to
1544 // take this into account when the token is moved.
1545 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1546 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1547
Alexander Kornienko39856b72013-09-10 09:38:25 +00001548 // The last line of the token always starts in column 0.
1549 // Thus, the length can be precomputed even in the presence of tabs.
1550 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1551 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1552 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001553 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001554 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001555
Daniel Jaspere1e43192014-04-01 12:55:11 +00001556 FormatTok->IsForEachMacro =
1557 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1558 FormatTok->Tok.getIdentifierInfo());
1559
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001560 return FormatTok;
1561 }
1562
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001563 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001564 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001565 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001566 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001567 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001568 Lexer &Lex;
1569 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001570 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001571 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001572 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001573 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001574 // Index (in 'Tokens') of the last token that starts a new line.
1575 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001576 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001577 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001578
Daniel Jasper8369aa52013-07-16 20:28:33 +00001579 void readRawToken(FormatToken &Tok) {
1580 Lex.LexFromRawLexer(Tok.Tok);
1581 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1582 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001583 // For formatting, treat unterminated string literals like normal string
1584 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001585 if (Tok.is(tok::unknown)) {
1586 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1587 Tok.Tok.setKind(tok::string_literal);
1588 Tok.IsUnterminatedLiteral = true;
1589 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1590 Tok.TokenText == "''") {
1591 Tok.Tok.setKind(tok::char_constant);
1592 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001593 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001594 }
1595};
1596
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001597static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1598 switch (Language) {
1599 case FormatStyle::LK_Cpp:
1600 return "C++";
1601 case FormatStyle::LK_JavaScript:
1602 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001603 case FormatStyle::LK_Proto:
1604 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001605 default:
1606 return "Unknown";
1607 }
1608}
1609
Daniel Jasperf7935112012-12-03 18:12:45 +00001610class Formatter : public UnwrappedLineConsumer {
1611public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001612 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001613 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001614 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001615 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001616 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001617 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001618 DEBUG(llvm::dbgs() << "File encoding: "
1619 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1620 : "unknown")
1621 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001622 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1623 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001624 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001625
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001626 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001627 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001628 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001629
1630 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001631 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001632 assert(UnwrappedLines.rbegin()->empty());
1633 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1634 ++Run) {
1635 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1636 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1637 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1638 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1639 }
1640 tooling::Replacements RunResult =
1641 format(AnnotatedLines, StructuralError, Tokens);
1642 DEBUG({
1643 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1644 for (tooling::Replacements::iterator I = RunResult.begin(),
1645 E = RunResult.end();
1646 I != E; ++I) {
1647 llvm::dbgs() << I->toString() << "\n";
1648 }
1649 });
1650 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1651 delete AnnotatedLines[i];
1652 }
1653 Result.insert(RunResult.begin(), RunResult.end());
1654 Whitespaces.reset();
1655 }
1656 return Result;
1657 }
1658
1659 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1660 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001661 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001662 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001663 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001664 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001665 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001666 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001667 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001668 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001669 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001670
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001671 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001672 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1673 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001674 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001675 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001676 return Whitespaces.generateReplacements();
1677 }
1678
1679private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001680 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001681 // Returns \c true if at least one line between I and E or one of their
1682 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001683 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1684 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1685 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001686 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001687 while (I != E) {
1688 AnnotatedLine *Line = *I;
1689 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1690
1691 // If a line is part of a preprocessor directive, it needs to be formatted
1692 // if any token within the directive is affected.
1693 if (Line->InPPDirective) {
1694 FormatToken *Last = Line->Last;
1695 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1696 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1697 Last = (*PPEnd)->Last;
1698 ++PPEnd;
1699 }
1700
1701 if (affectsTokenRange(*Line->First, *Last,
1702 /*IncludeLeadingNewlines=*/false)) {
1703 SomeLineAffected = true;
1704 markAllAsAffected(I, PPEnd);
1705 }
1706 I = PPEnd;
1707 continue;
1708 }
1709
Daniel Jasper38c82402013-11-29 09:27:43 +00001710 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001711 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001712
Daniel Jasper38c82402013-11-29 09:27:43 +00001713 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001714 ++I;
1715 }
1716 return SomeLineAffected;
1717 }
1718
Daniel Jasper9c199562013-11-28 15:58:55 +00001719 // Determines whether 'Line' is affected by the SourceRanges given as input.
1720 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001721 bool nonPPLineAffected(AnnotatedLine *Line,
1722 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001723 bool SomeLineAffected = false;
1724 Line->ChildrenAffected =
1725 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1726 if (Line->ChildrenAffected)
1727 SomeLineAffected = true;
1728
1729 // Stores whether one of the line's tokens is directly affected.
1730 bool SomeTokenAffected = false;
1731 // Stores whether we need to look at the leading newlines of the next token
1732 // in order to determine whether it was affected.
1733 bool IncludeLeadingNewlines = false;
1734
1735 // Stores whether the first child line of any of this line's tokens is
1736 // affected.
1737 bool SomeFirstChildAffected = false;
1738
1739 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1740 // Determine whether 'Tok' was affected.
1741 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1742 SomeTokenAffected = true;
1743
1744 // Determine whether the first child of 'Tok' was affected.
1745 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1746 SomeFirstChildAffected = true;
1747
1748 IncludeLeadingNewlines = Tok->Children.empty();
1749 }
1750
1751 // Was this line moved, i.e. has it previously been on the same line as an
1752 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001753 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1754 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001755
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001756 bool IsContinuedComment =
1757 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1758 Line->First->NewlinesBefore < 2 && PreviousLine &&
1759 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001760
1761 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1762 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001763 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001764 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001765 }
1766 return SomeLineAffected;
1767 }
1768
Daniel Jasper5500f612013-11-25 11:08:59 +00001769 // Marks all lines between I and E as well as all their children as affected.
1770 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1771 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1772 while (I != E) {
1773 (*I)->Affected = true;
1774 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1775 ++I;
1776 }
1777 }
1778
1779 // Returns true if the range from 'First' to 'Last' intersects with one of the
1780 // input ranges.
1781 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1782 bool IncludeLeadingNewlines) {
1783 SourceLocation Start = First.WhitespaceRange.getBegin();
1784 if (!IncludeLeadingNewlines)
1785 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001786 SourceLocation End = Last.getStartOfNonWhitespace();
1787 if (Last.TokenText.size() > 0)
1788 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001789 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1790 return affectsCharSourceRange(Range);
1791 }
1792
1793 // Returns true if one of the input ranges intersect the leading empty lines
1794 // before 'Tok'.
1795 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1796 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1797 Tok.WhitespaceRange.getBegin(),
1798 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1799 return affectsCharSourceRange(EmptyLineRange);
1800 }
1801
1802 // Returns true if 'Range' intersects with one of the input ranges.
1803 bool affectsCharSourceRange(const CharSourceRange &Range) {
1804 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1805 E = Ranges.end();
1806 I != E; ++I) {
1807 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1808 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1809 return true;
1810 }
1811 return false;
1812 }
1813
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001814 static bool inputUsesCRLF(StringRef Text) {
1815 return Text.count('\r') * 2 > Text.count('\n');
1816 }
1817
Manuel Klimek71814b42013-10-11 21:25:45 +00001818 void
1819 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001820 unsigned CountBoundToVariable = 0;
1821 unsigned CountBoundToType = 0;
1822 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001823 bool HasBinPackedFunction = false;
1824 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001825 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001826 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001827 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001828 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001829 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001830 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001831 bool SpacesBefore =
1832 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1833 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1834 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001835 if (SpacesBefore && !SpacesAfter)
1836 ++CountBoundToVariable;
1837 else if (!SpacesBefore && SpacesAfter)
1838 ++CountBoundToType;
1839 }
1840
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001841 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1842 if (Tok->is(tok::coloncolon) &&
1843 Tok->Previous->Type == TT_TemplateOpener)
1844 HasCpp03IncompatibleFormat = true;
1845 if (Tok->Type == TT_TemplateCloser &&
1846 Tok->Previous->Type == TT_TemplateCloser)
1847 HasCpp03IncompatibleFormat = true;
1848 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001849
1850 if (Tok->PackingKind == PPK_BinPacked)
1851 HasBinPackedFunction = true;
1852 if (Tok->PackingKind == PPK_OnePerLine)
1853 HasOnePerLineFunction = true;
1854
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001855 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001856 }
1857 }
1858 if (Style.DerivePointerBinding) {
1859 if (CountBoundToType > CountBoundToVariable)
1860 Style.PointerBindsToType = true;
1861 else if (CountBoundToType < CountBoundToVariable)
1862 Style.PointerBindsToType = false;
1863 }
1864 if (Style.Standard == FormatStyle::LS_Auto) {
1865 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1866 : FormatStyle::LS_Cpp03;
1867 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001868 BinPackInconclusiveFunctions =
1869 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001870 }
1871
Craig Topperfb6b25b2014-03-15 04:29:04 +00001872 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001873 assert(!UnwrappedLines.empty());
1874 UnwrappedLines.back().push_back(TheLine);
1875 }
1876
Craig Topperfb6b25b2014-03-15 04:29:04 +00001877 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001878 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001879 }
1880
1881 FormatStyle Style;
1882 Lexer &Lex;
1883 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001884 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001885 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001886 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001887
1888 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001889 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001890};
1891
Craig Topperaf35e852013-06-30 22:29:28 +00001892} // end anonymous namespace
1893
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001894tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1895 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001896 std::vector<CharSourceRange> Ranges) {
1897 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001898 return formatter.format();
1899}
1900
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001901tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1902 std::vector<tooling::Range> Ranges,
1903 StringRef FileName) {
1904 FileManager Files((FileSystemOptions()));
1905 DiagnosticsEngine Diagnostics(
1906 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1907 new DiagnosticOptions);
1908 SourceManager SourceMgr(Diagnostics, Files);
1909 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1910 const clang::FileEntry *Entry =
1911 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1912 SourceMgr.overrideFileContents(Entry, Buf);
1913 FileID ID =
1914 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001915 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1916 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001917 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1918 std::vector<CharSourceRange> CharRanges;
1919 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1920 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1921 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1922 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1923 }
1924 return reformat(Style, Lex, SourceMgr, CharRanges);
1925}
1926
Alexander Kornienko1e808872013-06-28 12:51:24 +00001927LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001928 LangOptions LangOpts;
1929 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001930 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001931 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001932 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00001933 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001934 LangOpts.Bool = 1;
1935 LangOpts.ObjC1 = 1;
1936 LangOpts.ObjC2 = 1;
1937 return LangOpts;
1938}
1939
Edwin Vaned544aa72013-09-30 13:31:48 +00001940const char *StyleOptionHelpDescription =
1941 "Coding style, currently supports:\n"
1942 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1943 "Use -style=file to load style configuration from\n"
1944 ".clang-format file located in one of the parent\n"
1945 "directories of the source file (or current\n"
1946 "directory for stdin).\n"
1947 "Use -style=\"{key: value, ...}\" to set specific\n"
1948 "parameters, e.g.:\n"
1949 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1950
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001951static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001952 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001953 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001954 } else if (FileName.endswith_lower(".proto") ||
1955 FileName.endswith_lower(".protodevel")) {
1956 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001957 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001958 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001959}
1960
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001961FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1962 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001963 FormatStyle Style = getLLVMStyle();
1964 Style.Language = getLanguageByFileName(FileName);
1965 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001966 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1967 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001968 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001969 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001970
1971 if (StyleName.startswith("{")) {
1972 // Parse YAML/JSON style from the command line.
1973 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001974 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1975 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001976 }
1977 return Style;
1978 }
1979
1980 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001981 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001982 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1983 << " style\n";
1984 return Style;
1985 }
1986
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001987 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001988 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001989 SmallString<128> Path(FileName);
1990 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001991 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001992 Directory = llvm::sys::path::parent_path(Directory)) {
1993 if (!llvm::sys::fs::is_directory(Directory))
1994 continue;
1995 SmallString<128> ConfigFile(Directory);
1996
1997 llvm::sys::path::append(ConfigFile, ".clang-format");
1998 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1999 bool IsFile = false;
2000 // Ignore errors from is_regular_file: we only need to know if we can read
2001 // the file or not.
2002 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2003
2004 if (!IsFile) {
2005 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2006 ConfigFile = Directory;
2007 llvm::sys::path::append(ConfigFile, "_clang-format");
2008 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2009 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2010 }
2011
2012 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002013 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00002014 if (llvm::error_code ec =
2015 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002016 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002017 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002018 }
2019 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002020 if (ec == llvm::errc::not_supported) {
2021 if (!UnsuitableConfigFiles.empty())
2022 UnsuitableConfigFiles.append(", ");
2023 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002024 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002025 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002026 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2027 << "\n";
2028 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002029 }
2030 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2031 return Style;
2032 }
2033 }
2034 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2035 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002036 if (!UnsuitableConfigFiles.empty()) {
2037 llvm::errs() << "Configuration file(s) do(es) not support "
2038 << getLanguageName(Style.Language) << ": "
2039 << UnsuitableConfigFiles << "\n";
2040 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002041 return Style;
2042}
2043
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002044} // namespace format
2045} // namespace clang