blob: 56af0cdfb84c355ea5eea146a031fdc127d91607 [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"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000021#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000022#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000024#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000025#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000027#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000028#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000030#include <string>
31
Chandler Carruth10346662014-04-22 03:17:02 +000032#define DEBUG_TYPE "format-formatter"
33
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000034using clang::format::FormatStyle;
35
Daniel Jaspere1e43192014-04-01 12:55:11 +000036LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
37
Alexander Kornienkod6538332013-05-07 15:32:14 +000038namespace llvm {
39namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000040template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
41 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
42 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
43 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000044 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045 }
46};
47
48template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
49 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
50 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
51 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
53 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
55 }
56};
57
58template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
59 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
60 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
61 IO.enumCase(Value, "false", FormatStyle::UT_Never);
62 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
63 IO.enumCase(Value, "true", FormatStyle::UT_Always);
64 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
65 }
66};
67
Daniel Jasperd74cf402014-04-08 12:46:38 +000068template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
69 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
70 IO.enumCase(Value, "None", FormatStyle::SFS_None);
71 IO.enumCase(Value, "false", FormatStyle::SFS_None);
72 IO.enumCase(Value, "All", FormatStyle::SFS_All);
73 IO.enumCase(Value, "true", FormatStyle::SFS_All);
74 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
75 }
76};
77
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000078template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
79 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
80 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
81 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
82 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
83 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000084 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000085 }
86};
87
Alexander Kornienkod6538332013-05-07 15:32:14 +000088template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000089struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000090 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000091 FormatStyle::NamespaceIndentationKind &Value) {
92 IO.enumCase(Value, "None", FormatStyle::NI_None);
93 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
94 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000095 }
96};
97
98template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000100 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000101 FormatStyle::SpaceBeforeParensOptions &Value) {
102 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000103 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 FormatStyle::SBPO_ControlStatements);
105 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000106
107 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000108 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
109 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000110 }
111};
112
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000113template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000114 static void mapping(IO &IO, FormatStyle &Style) {
115 // When reading, read the language first, we need it for getPredefinedStyle.
116 IO.mapOptional("Language", Style.Language);
117
Alexander Kornienko49149672013-05-10 11:56:10 +0000118 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000119 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000120 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000121 ArrayRef<StringRef> Styles(StylesArray);
122 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
123 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000124 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000125 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000126 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000127 IO.mapOptional("# BasedOnStyle", StyleName);
128 break;
129 }
130 }
131 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000132 StringRef BasedOnStyle;
133 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000134 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000135 FormatStyle::LanguageKind OldLanguage = Style.Language;
136 FormatStyle::LanguageKind Language =
137 ((FormatStyle *)IO.getContext())->Language;
138 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000139 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
140 return;
141 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000142 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000143 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000144 }
145
146 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000147 IO.mapOptional("ConstructorInitializerIndentWidth",
148 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000149 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000150 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000151 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
152 Style.AllowAllParametersOfDeclarationOnNextLine);
153 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
154 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000155 IO.mapOptional("AllowShortLoopsOnASingleLine",
156 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000157 IO.mapOptional("AllowShortFunctionsOnASingleLine",
158 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000159 IO.mapOptional("AlwaysBreakTemplateDeclarations",
160 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000161 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
162 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000163 IO.mapOptional("BreakBeforeBinaryOperators",
164 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000165 IO.mapOptional("BreakBeforeTernaryOperators",
166 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000167 IO.mapOptional("BreakConstructorInitializersBeforeComma",
168 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000169 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
170 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
171 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
172 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
173 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000174 IO.mapOptional("ExperimentalAutoDetectBinPacking",
175 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000176 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
177 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000178 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
179 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000180 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000181 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000182 IO.mapOptional("ObjCSpaceBeforeProtocolList",
183 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000184 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
185 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000186 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
187 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000188 IO.mapOptional("PenaltyBreakFirstLessLess",
189 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000190 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
191 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
192 Style.PenaltyReturnTypeOnItsOwnLine);
193 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
194 IO.mapOptional("SpacesBeforeTrailingComments",
195 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000196 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000197 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000198 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000199 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000200 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000201 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000202 IO.mapOptional("IndentFunctionDeclarationAfterType",
203 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000204 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000205 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000206 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000207 IO.mapOptional("SpacesInCStyleCastParentheses",
208 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000209 IO.mapOptional("SpacesInContainerLiterals",
210 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000211 IO.mapOptional("SpaceBeforeAssignmentOperators",
212 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000213 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000214 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000215 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000216
217 // For backward compatibility.
218 if (!IO.outputting()) {
219 IO.mapOptional("SpaceAfterControlStatementKeyword",
220 Style.SpaceBeforeParens);
221 }
222 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000223 }
224};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000225
226// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000227// IO.getContext() should contain a pointer to the FormatStyle structure, that
228// will be used to get default values for missing keys.
229// If the first element has no Language specified, it will be treated as the
230// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000231template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000232 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
233 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000234 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000235 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000236 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000237 if (Index >= Seq.size()) {
238 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000239 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000240 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000241 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000242 } else {
243 Template = *((const FormatStyle*)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000244 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000245 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000246 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000247 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000248 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000249 }
250};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000251}
252}
253
Daniel Jasperf7935112012-12-03 18:12:45 +0000254namespace clang {
255namespace format {
256
Daniel Jasperf7935112012-12-03 18:12:45 +0000257FormatStyle getLLVMStyle() {
258 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000259 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000260 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000261 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000262 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000263 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000264 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000265 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000266 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000267 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000268 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000269 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000270 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000271 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000272 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
273 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000274 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000275 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000276 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000277 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000278 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000279 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000280 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000281 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000282 LLVMStyle.ForEachMacros.push_back("foreach");
283 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
284 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000285 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000286 LLVMStyle.IndentFunctionDeclarationAfterType = false;
287 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000288 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000289 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000290 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000291 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000292 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000293 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000294 LLVMStyle.PointerBindsToType = false;
295 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000296 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000297 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000298 LLVMStyle.SpacesInParentheses = false;
299 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000300 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000301 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000302 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000303 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000304 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000305
Daniel Jasper19a541e2013-12-19 16:45:34 +0000306 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000307 LLVMStyle.PenaltyBreakFirstLessLess = 120;
308 LLVMStyle.PenaltyBreakString = 1000;
309 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000310 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000311 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000312
Daniel Jasperf7935112012-12-03 18:12:45 +0000313 return LLVMStyle;
314}
315
Nico Weber514ecc82014-02-02 20:50:45 +0000316FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000317 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000318 GoogleStyle.Language = Language;
319
Daniel Jasperf7935112012-12-03 18:12:45 +0000320 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000321 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000322 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000323 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000324 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000325 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000326 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
327 GoogleStyle.DerivePointerBinding = true;
328 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000329 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000330 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000331 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000332 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000333 GoogleStyle.PointerBindsToType = true;
334 GoogleStyle.SpacesBeforeTrailingComments = 2;
335 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000336
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000337 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000338 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000339
Nico Weber514ecc82014-02-02 20:50:45 +0000340 if (Language == FormatStyle::LK_JavaScript) {
341 GoogleStyle.BreakBeforeTernaryOperators = false;
342 GoogleStyle.MaxEmptyLinesToKeep = 2;
343 GoogleStyle.SpacesInContainerLiterals = false;
344 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000345 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000346 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000347 }
348
Daniel Jasperf7935112012-12-03 18:12:45 +0000349 return GoogleStyle;
350}
351
Nico Weber514ecc82014-02-02 20:50:45 +0000352FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
353 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000354 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000355 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000356 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000357 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000358 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000359 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000360 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000361 return ChromiumStyle;
362}
363
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000364FormatStyle getMozillaStyle() {
365 FormatStyle MozillaStyle = getLLVMStyle();
366 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000367 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000368 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
369 MozillaStyle.DerivePointerBinding = true;
370 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000371 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000372 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
373 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
374 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000375 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000376 return MozillaStyle;
377}
378
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000379FormatStyle getWebKitStyle() {
380 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000381 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000382 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000383 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000384 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000385 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000386 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000387 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000388 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000389 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000390 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000391 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000392 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000393 return Style;
394}
395
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000396FormatStyle getGNUStyle() {
397 FormatStyle Style = getLLVMStyle();
398 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000399 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000400 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000401 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000402 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000403 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000404 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000405 return Style;
406}
407
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000408bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
409 FormatStyle *Style) {
410 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000411 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000412 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000413 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000414 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000415 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000416 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000417 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000418 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000419 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000420 } else if (Name.equals_lower("gnu")) {
421 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000422 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000423 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000424 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000425
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000426 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000427 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000428}
429
430llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000431 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000432 FormatStyle::LanguageKind Language = Style->Language;
433 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000434 if (Text.trim().empty())
435 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000436
437 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000438 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000439 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
440 // values for the fields, keys for which are missing from the configuration.
441 // Mapping also uses the context to get the language to find the correct
442 // base style.
443 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000444 Input >> Styles;
445 if (Input.error())
446 return Input.error();
447
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000448 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000449 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000450 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000451 return llvm::make_error_code(llvm::errc::invalid_argument);
452 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000453 for (unsigned j = 0; j < i; ++j) {
454 if (Styles[i].Language == Styles[j].Language) {
455 DEBUG(llvm::dbgs()
456 << "Duplicate languages in the config file on positions " << j
457 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000458 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000459 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000460 }
461 }
462 // Look for a suitable configuration starting from the end, so we can
463 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000464 // configuration (which can only be at slot 0) after it.
465 for (int i = Styles.size() - 1; i >= 0; --i) {
466 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000467 Styles[i].Language == FormatStyle::LK_None) {
468 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000469 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000470 return llvm::make_error_code(llvm::errc::success);
471 }
472 }
473 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000474}
475
476std::string configurationAsText(const FormatStyle &Style) {
477 std::string Text;
478 llvm::raw_string_ostream Stream(Text);
479 llvm::yaml::Output Output(Stream);
480 // We use the same mapping method for input and output, so we need a non-const
481 // reference here.
482 FormatStyle NonConstStyle = Style;
483 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000484 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000485}
486
Craig Topperaf35e852013-06-30 22:29:28 +0000487namespace {
488
Daniel Jasperde0328a2013-08-16 11:20:30 +0000489class NoColumnLimitFormatter {
490public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000491 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000492
493 /// \brief Formats the line starting at \p State, simply keeping all of the
494 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000495 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000496 LineState State =
497 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000498 while (State.NextToken != NULL) {
499 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000500 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000501 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
502 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
503 }
504 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000505
Daniel Jasperde0328a2013-08-16 11:20:30 +0000506private:
507 ContinuationIndenter *Indenter;
508};
509
Daniel Jasper56f8b432013-11-06 23:12:09 +0000510class LineJoiner {
511public:
512 LineJoiner(const FormatStyle &Style) : Style(Style) {}
513
514 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
515 unsigned
516 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000517 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000518 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
519 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000520 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000521 if (TheLine->Last->Type == TT_LineComment)
522 return 0;
523
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000524 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
525 return 0;
526
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000527 unsigned Limit =
528 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000529 // If we already exceed the column limit, we set 'Limit' to 0. The different
530 // tryMerge..() functions can then decide whether to still do merging.
531 Limit = TheLine->Last->TotalLength > Limit
532 ? 0
533 : Limit - TheLine->Last->TotalLength;
534
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000535 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000536 return 0;
537
Daniel Jasperd74cf402014-04-08 12:46:38 +0000538 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
539 // If necessary, change to something smarter.
540 bool MergeShortFunctions =
541 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
542 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
543 TheLine->Level != 0);
544
Daniel Jasper234379f2013-12-24 13:31:25 +0000545 if (TheLine->Last->Type == TT_FunctionLBrace &&
546 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000547 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000548 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000549 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000550 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000551 ? tryMergeSimpleBlock(I, E, Limit)
552 : 0;
553 }
554 if (I[1]->First->Type == TT_FunctionLBrace &&
555 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000556 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000557 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
558 return 0;
559 Limit -= 2;
560
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000561 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000562 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000563 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
564 // If we managed to merge the block, count the function header, which is
565 // on a separate line.
566 if (MergedLines > 0)
567 ++MergedLines;
568 }
569 return MergedLines;
570 }
571 if (TheLine->First->is(tok::kw_if)) {
572 return Style.AllowShortIfStatementsOnASingleLine
573 ? tryMergeSimpleControlStatement(I, E, Limit)
574 : 0;
575 }
576 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
577 return Style.AllowShortLoopsOnASingleLine
578 ? tryMergeSimpleControlStatement(I, E, Limit)
579 : 0;
580 }
581 if (TheLine->InPPDirective &&
582 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000583 return tryMergeSimplePPDirective(I, E, Limit);
584 }
585 return 0;
586 }
587
588private:
589 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000590 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000591 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
592 unsigned Limit) {
593 if (Limit == 0)
594 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000595 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000596 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000597 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000598 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000599 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000600 return 0;
601 return 1;
602 }
603
604 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000605 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000606 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
607 if (Limit == 0)
608 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000609 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
610 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000611 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000612 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000613 if (I[1]->InPPDirective != (*I)->InPPDirective ||
614 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000615 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000616 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000617 AnnotatedLine &Line = **I;
618 if (Line.Last->isNot(tok::r_paren))
619 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000620 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000621 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000622 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000623 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000624 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000625 return 0;
626 // Only inline simple if's (no nested if or else).
627 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000628 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000629 return 0;
630 return 1;
631 }
632
633 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000634 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000635 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
636 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000637 // First, check that the current line allows merging. This is the case if
638 // we're not in a control flow statement and the last token is an opening
639 // brace.
640 AnnotatedLine &Line = **I;
641 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
642 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper922349c2014-04-04 06:46:23 +0000643 tok::kw_for, tok::kw_case,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000644 // This gets rid of all ObjC @ keywords and methods.
645 tok::at, tok::minus, tok::plus))
646 return 0;
647
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000648 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000649 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
650 (Tok->getNextNonComment() == NULL ||
651 Tok->getNextNonComment()->is(tok::semi))) {
652 // We merge empty blocks even if the line exceeds the column limit.
653 Tok->SpacesRequiredBefore = 0;
654 Tok->CanBreakBefore = true;
655 return 1;
656 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000657 // We don't merge short records.
658 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
659 return 0;
660
Daniel Jasper56f8b432013-11-06 23:12:09 +0000661 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000662 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000663 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000664 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000665
666 if (!nextTwoLinesFitInto(I, Limit))
667 return 0;
668
669 // Second, check that the next line does not contain any braces - if it
670 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000671 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000672 return 0;
673 do {
674 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
675 return 0;
676 Tok = Tok->Next;
677 } while (Tok != NULL);
678
Daniel Jasper79dffb42014-05-07 09:48:30 +0000679 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000680 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000681 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000682 return 0;
683
684 return 2;
685 }
686 return 0;
687 }
688
Daniel Jasper64989962014-02-07 13:45:27 +0000689 /// Returns the modified column limit for \p I if it is inside a macro and
690 /// needs a trailing '\'.
691 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000692 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000693 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
694 unsigned Limit) {
695 if (I[0]->InPPDirective && I + 1 != E &&
696 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
697 return Limit < 2 ? 0 : Limit - 2;
698 }
699 return Limit;
700 }
701
Daniel Jasper56f8b432013-11-06 23:12:09 +0000702 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
703 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000704 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
705 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000706 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000707 }
708
Daniel Jasper234379f2013-12-24 13:31:25 +0000709 bool containsMustBreak(const AnnotatedLine *Line) {
710 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
711 if (Tok->MustBreakBefore)
712 return true;
713 }
714 return false;
715 }
716
Daniel Jasper56f8b432013-11-06 23:12:09 +0000717 const FormatStyle &Style;
718};
719
Daniel Jasperf7935112012-12-03 18:12:45 +0000720class UnwrappedLineFormatter {
721public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000722 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000723 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000724 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000725 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
726 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000727
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000729 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000730 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000731 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
732 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000733 auto CacheIt = PenaltyCache.find(CacheKey);
734 if (DryRun && CacheIt != PenaltyCache.end())
735 return CacheIt->second;
736
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000737 assert(!Lines.empty());
738 unsigned Penalty = 0;
739 std::vector<int> IndentForLevel;
740 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
741 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000742 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000743 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
744 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000745 I != E; ++I) {
746 const AnnotatedLine &TheLine = **I;
747 const FormatToken *FirstTok = TheLine.First;
748 int Offset = getIndentOffset(*FirstTok);
749
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000750 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000751 unsigned Indent;
752 if (TheLine.InPPDirective) {
753 Indent = TheLine.Level * Style.IndentWidth;
754 } else {
755 while (IndentForLevel.size() <= TheLine.Level)
756 IndentForLevel.push_back(-1);
757 IndentForLevel.resize(TheLine.Level + 1);
758 Indent = getIndent(IndentForLevel, TheLine.Level);
759 }
760 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000761 if (static_cast<int>(Indent) + Offset >= 0)
762 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000763
764 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000765 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000766 if (MergedLines > 0 && Style.ColumnLimit == 0) {
767 // Disallow line merging if there is a break at the start of one of the
768 // input lines.
769 for (unsigned i = 0; i < MergedLines; ++i) {
770 if (I[i + 1]->First->NewlinesBefore > 0)
771 MergedLines = 0;
772 }
773 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000774 if (!DryRun) {
775 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000776 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000777 }
778 }
779 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000780
Daniel Jasper9c199562013-11-28 15:58:55 +0000781 bool FixIndentation =
782 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000783 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000784 if (PreviousLine && PreviousLine->Affected && !DryRun) {
785 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000786 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
787 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
788 /*IndentLevel=*/0, /*Spaces=*/0,
789 /*TargetColumn=*/0);
790 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000791 } else if (TheLine.Type != LT_Invalid &&
792 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000793 if (FirstTok->WhitespaceRange.isValid()) {
794 if (!DryRun)
795 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
796 Indent, TheLine.InPPDirective);
797 } else {
798 Indent = LevelIndent = FirstTok->OriginalColumn;
799 }
800
801 // If everything fits on a single line, just put it there.
802 unsigned ColumnLimit = Style.ColumnLimit;
803 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000804 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000805 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
806 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
807 }
808
809 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
810 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
811 while (State.NextToken != NULL)
812 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
813 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000814 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000815 NoColumnLimitFormatter Formatter(Indenter);
816 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000817 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000818 } else {
819 Penalty += format(TheLine, Indent, DryRun);
820 }
821
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000822 if (!TheLine.InPPDirective)
823 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000824 } else if (TheLine.ChildrenAffected) {
825 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000826 } else {
827 // Format the first token if necessary, and notify the WhitespaceManager
828 // about the unchanged whitespace.
829 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
830 if (Tok == TheLine.First &&
831 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
832 unsigned LevelIndent = Tok->OriginalColumn;
833 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000834 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000835 if ((PreviousLine && PreviousLine->Affected) ||
836 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000837 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
838 TheLine.InPPDirective);
839 } else {
840 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
841 }
842 }
843
844 if (static_cast<int>(LevelIndent) - Offset >= 0)
845 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000846 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000847 IndentForLevel[TheLine.Level] = LevelIndent;
848 } else if (!DryRun) {
849 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
850 }
851 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000852 }
853 if (!DryRun) {
854 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
855 Tok->Finalized = true;
856 }
857 }
858 PreviousLine = *I;
859 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000860 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000861 return Penalty;
862 }
863
864private:
865 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000866 ///
867 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000868 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
869 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000870 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000871
Daniel Jasperacc33662013-02-08 08:22:00 +0000872 // If the ObjC method declaration does not fit on a line, we should format
873 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000874 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000875 State.Stack.back().BreakBeforeParameter = true;
876
Daniel Jasper4b866272013-02-01 11:00:45 +0000877 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000878 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000879 }
880
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000881 /// \brief An edge in the solution space from \c Previous->State to \c State,
882 /// inserting a newline dependent on the \c NewLine.
883 struct StateNode {
884 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000885 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000886 LineState State;
887 bool NewLine;
888 StateNode *Previous;
889 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000890
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000891 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
892 ///
893 /// In case of equal penalties, we want to prefer states that were inserted
894 /// first. During state generation we make sure that we insert states first
895 /// that break the line as late as possible.
896 typedef std::pair<unsigned, unsigned> OrderedPenalty;
897
898 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
899 /// \c State has the given \c OrderedPenalty.
900 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
901
902 /// \brief The BFS queue type.
903 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
904 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000905
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000906 /// \brief Get the offset of the line relatively to the level.
907 ///
908 /// For example, 'public:' labels in classes are offset by 1 or 2
909 /// characters to the left from their level.
910 int getIndentOffset(const FormatToken &RootToken) {
911 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
912 return Style.AccessModifierOffset;
913 return 0;
914 }
915
916 /// \brief Add a new line and the required indent before the first Token
917 /// of the \c UnwrappedLine if there was no structural parsing error.
918 void formatFirstToken(FormatToken &RootToken,
919 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
920 unsigned Indent, bool InPPDirective) {
921 unsigned Newlines =
922 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
923 // Remove empty lines before "}" where applicable.
924 if (RootToken.is(tok::r_brace) &&
925 (!RootToken.Next ||
926 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
927 Newlines = std::min(Newlines, 1u);
928 if (Newlines == 0 && !RootToken.IsFirst)
929 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000930 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
931 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000932
Daniel Jasper11164bd2014-03-21 12:58:53 +0000933 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000934 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
935 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000936 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000937 Newlines = 1;
938
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000939 // Insert extra new line before access specifiers.
940 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
941 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
942 ++Newlines;
943
944 // Remove empty lines after access specifiers.
945 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
946 Newlines = std::min(1u, Newlines);
947
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000948 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
949 Indent, InPPDirective &&
950 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000951 }
952
953 /// \brief Get the indent of \p Level from \p IndentForLevel.
954 ///
955 /// \p IndentForLevel must contain the indent for the level \c l
956 /// at \p IndentForLevel[l], or a value < 0 if the indent for
957 /// that level is unknown.
958 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
959 if (IndentForLevel[Level] != -1)
960 return IndentForLevel[Level];
961 if (Level == 0)
962 return 0;
963 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
964 }
965
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000966 void join(AnnotatedLine &A, const AnnotatedLine &B) {
967 assert(!A.Last->Next);
968 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000969 if (B.Affected)
970 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000971 A.Last->Next = B.First;
972 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000973 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000974 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
975 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
976 Tok->TotalLength += LengthA;
977 A.Last = Tok;
978 }
979 }
980
981 unsigned getColumnLimit(bool InPPDirective) const {
982 // In preprocessor directives reserve two chars for trailing " \"
983 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
984 }
985
Daniel Jasper4b866272013-02-01 11:00:45 +0000986 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000987 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000988 /// This implements a variant of Dijkstra's algorithm on the graph that spans
989 /// the solution space (\c LineStates are the nodes). The algorithm tries to
990 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000991 /// to a state where all tokens are placed. Returns the penalty.
992 ///
993 /// If \p DryRun is \c false, directly applies the changes.
994 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000995 std::set<LineState> Seen;
996
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000997 // Increasing count of \c StateNode items we have created. This is used to
998 // create a deterministic order independent of the container.
999 unsigned Count = 0;
1000 QueueType Queue;
1001
Daniel Jasper4b866272013-02-01 11:00:45 +00001002 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001003 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001004 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1005 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1006 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001007
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001008 unsigned Penalty = 0;
1009
Daniel Jasper4b866272013-02-01 11:00:45 +00001010 // While not empty, take first element and follow edges.
1011 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001012 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001013 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001014 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001015 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001016 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001017 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001018 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001019
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001020 // Cut off the analysis of certain solutions if the analysis gets too
1021 // complex. See description of IgnoreStackForComparison.
1022 if (Count > 10000)
1023 Node->State.IgnoreStackForComparison = true;
1024
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001025 if (!Seen.insert(Node->State).second)
1026 // State already examined with lower penalty.
1027 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001028
Manuel Klimek71814b42013-10-11 21:25:45 +00001029 FormatDecision LastFormat = Node->State.NextToken->Decision;
1030 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001031 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001032 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001033 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001034 }
1035
Manuel Klimek71814b42013-10-11 21:25:45 +00001036 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001037 // We were unable to find a solution, do nothing.
1038 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001039 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001040 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001041 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001042
Daniel Jasper4b866272013-02-01 11:00:45 +00001043 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001044 if (!DryRun)
1045 reconstructPath(InitialState, Queue.top().second);
1046
Alexander Kornienko49149672013-05-10 11:56:10 +00001047 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1048 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001049
1050 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001051 }
1052
1053 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001054 std::deque<StateNode *> Path;
1055 // We do not need a break before the initial token.
1056 while (Current->Previous) {
1057 Path.push_front(Current);
1058 Current = Current->Previous;
1059 }
1060 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1061 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001062 unsigned Penalty = 0;
1063 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1064 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1065
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001066 DEBUG({
1067 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001068 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001069 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001070 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001071 }
1072 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001073 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001074 }
1075
Manuel Klimekaf491072013-02-13 10:54:19 +00001076 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001077 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001078 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001079 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001080 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001081 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001082 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001083 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001084 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001085 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001086
1087 StateNode *Node = new (Allocator.Allocate())
1088 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001089 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1090 return;
1091
Daniel Jasperde0328a2013-08-16 11:20:30 +00001092 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001093
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001094 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1095 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001096 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001097
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001098 /// \brief If the \p State's next token is an r_brace closing a nested block,
1099 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001100 ///
1101 /// Returns \c true if all children could be placed successfully and adapts
1102 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1103 /// creates changes using \c Whitespaces.
1104 ///
1105 /// The crucial idea here is that children always get formatted upon
1106 /// encountering the closing brace right after the nested block. Now, if we
1107 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1108 /// \c false), the entire block has to be kept on the same line (which is only
1109 /// possible if it fits on the line, only contains a single statement, etc.
1110 ///
1111 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1112 /// break after the "{", format all lines with correct indentation and the put
1113 /// the closing "}" on yet another new line.
1114 ///
1115 /// This enables us to keep the simple structure of the
1116 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1117 /// break or don't break.
1118 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1119 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001120 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001121 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1122 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1123 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001124 // The previous token does not open a block. Nothing to do. We don't
1125 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001126 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127
1128 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001129 int AdditionalIndent = State.Stack.back().Indent -
1130 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001131 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1132 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001133 return true;
1134 }
1135
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001136 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001137 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001138 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001139
Daniel Jasper21397a32014-04-09 12:21:48 +00001140 // Cannot merge into one line if this line ends on a comment.
1141 if (Previous.is(tok::comment))
1142 return false;
1143
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001144 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001145 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001146 return false;
1147
Daniel Jasper98583d52014-04-15 08:28:06 +00001148 // If the child line exceeds the column limit, we wouldn't want to merge it.
1149 // We add +2 for the trailing " }".
1150 if (Style.ColumnLimit > 0 &&
1151 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1152 Style.ColumnLimit)
1153 return false;
1154
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001155 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001156 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001157 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001158 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001159 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001160 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001161 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001162
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001163 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001164 return true;
1165 }
1166
Daniel Jasperde0328a2013-08-16 11:20:30 +00001167 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001168 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001169 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001170 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001171
1172 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001173
1174 // Cache to store the penalty of formatting a vector of AnnotatedLines
1175 // starting from a specific additional offset. Improves performance if there
1176 // are many nested blocks.
1177 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1178 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001179};
1180
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001181class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001182public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001183 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001184 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001185 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001186 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
Manuel Klimek68b03042014-04-14 09:14:11 +00001187 IdentTable(getFormattingLangOpts()), Encoding(Encoding),
1188 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001189 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001190
1191 for (const std::string& ForEachMacro : Style.ForEachMacros)
1192 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1193 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001194 }
1195
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001196 ArrayRef<FormatToken *> lex() {
1197 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001198 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001199 do {
1200 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001201 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001202 if (Tokens.back()->NewlinesBefore > 0)
1203 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001204 } while (Tokens.back()->Tok.isNot(tok::eof));
1205 return Tokens;
1206 }
1207
1208 IdentifierTable &getIdentTable() { return IdentTable; }
1209
1210private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001211 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001212 if (tryMerge_TMacro())
1213 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001214 if (tryMergeConflictMarkers())
1215 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001216
1217 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001218 if (tryMergeJSRegexLiteral())
1219 return;
1220
1221 static tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
1222 static tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, tok::equal};
1223 static tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
1224 tok::greaterequal};
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001225 // FIXME: We probably need to change token type to mimic operator with the
1226 // correct priority.
1227 if (tryMergeTokens(JSIdentity))
1228 return;
1229 if (tryMergeTokens(JSNotIdentity))
1230 return;
1231 if (tryMergeTokens(JSShiftEqual))
1232 return;
1233 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001234 }
1235
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001236 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1237 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001238 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001239
1240 SmallVectorImpl<FormatToken *>::const_iterator First =
1241 Tokens.end() - Kinds.size();
1242 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001243 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001244 unsigned AddLength = 0;
1245 for (unsigned i = 1; i < Kinds.size(); ++i) {
1246 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1247 First[i]->WhitespaceRange.getEnd())
1248 return false;
1249 AddLength += First[i]->TokenText.size();
1250 }
1251 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1252 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1253 First[0]->TokenText.size() + AddLength);
1254 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001255 return true;
1256 }
1257
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001258 // Try to determine whether the current token ends a JavaScript regex literal.
1259 // We heuristically assume that this is a regex literal if we find two
1260 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001261 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1262 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001263 bool tryMergeJSRegexLiteral() {
1264 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
1265 Tokens[Tokens.size() - 2]->is(tok::unknown))
1266 return false;
1267 unsigned TokenCount = 0;
1268 unsigned LastColumn = Tokens.back()->OriginalColumn;
1269 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1270 ++TokenCount;
1271 if (I[0]->is(tok::slash) && I + 1 != E &&
Daniel Jasperf7405c12014-05-08 07:45:18 +00001272 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1273 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1274 tok::question, tok::kw_return) ||
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001275 I[1]->isBinaryOperator())) {
1276 Tokens.resize(Tokens.size() - TokenCount);
1277 Tokens.back()->Tok.setKind(tok::unknown);
1278 Tokens.back()->Type = TT_RegexLiteral;
1279 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1280 return true;
1281 }
1282
1283 // There can't be a newline inside a regex literal.
1284 if (I[0]->NewlinesBefore > 0)
1285 return false;
1286 }
1287 return false;
1288 }
1289
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001290 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001291 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001292 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001293 FormatToken *Last = Tokens.back();
1294 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001295 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001296
1297 FormatToken *String = Tokens[Tokens.size() - 2];
1298 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001299 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001300
1301 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001302 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001303
1304 FormatToken *Macro = Tokens[Tokens.size() - 4];
1305 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001306 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001307
1308 const char *Start = Macro->TokenText.data();
1309 const char *End = Last->TokenText.data() + Last->TokenText.size();
1310 String->TokenText = StringRef(Start, End - Start);
1311 String->IsFirst = Macro->IsFirst;
1312 String->LastNewlineOffset = Macro->LastNewlineOffset;
1313 String->WhitespaceRange = Macro->WhitespaceRange;
1314 String->OriginalColumn = Macro->OriginalColumn;
1315 String->ColumnWidth = encoding::columnWidthWithTabs(
1316 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1317
1318 Tokens.pop_back();
1319 Tokens.pop_back();
1320 Tokens.pop_back();
1321 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001322 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001323 }
1324
Manuel Klimek68b03042014-04-14 09:14:11 +00001325 bool tryMergeConflictMarkers() {
1326 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1327 return false;
1328
1329 // Conflict lines look like:
1330 // <marker> <text from the vcs>
1331 // For example:
1332 // >>>>>>> /file/in/file/system at revision 1234
1333 //
1334 // We merge all tokens in a line that starts with a conflict marker
1335 // into a single token with a special token type that the unwrapped line
1336 // parser will use to correctly rebuild the underlying code.
1337
1338 FileID ID;
1339 // Get the position of the first token in the line.
1340 unsigned FirstInLineOffset;
1341 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1342 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1343 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1344 // Calculate the offset of the start of the current line.
1345 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1346 if (LineOffset == StringRef::npos) {
1347 LineOffset = 0;
1348 } else {
1349 ++LineOffset;
1350 }
1351
1352 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1353 StringRef LineStart;
1354 if (FirstSpace == StringRef::npos) {
1355 LineStart = Buffer.substr(LineOffset);
1356 } else {
1357 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1358 }
1359
1360 TokenType Type = TT_Unknown;
1361 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1362 Type = TT_ConflictStart;
1363 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1364 LineStart == "====") {
1365 Type = TT_ConflictAlternative;
1366 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1367 Type = TT_ConflictEnd;
1368 }
1369
1370 if (Type != TT_Unknown) {
1371 FormatToken *Next = Tokens.back();
1372
1373 Tokens.resize(FirstInLineIndex + 1);
1374 // We do not need to build a complete token here, as we will skip it
1375 // during parsing anyway (as we must not touch whitespace around conflict
1376 // markers).
1377 Tokens.back()->Type = Type;
1378 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1379
1380 Tokens.push_back(Next);
1381 return true;
1382 }
1383
1384 return false;
1385 }
1386
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001387 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001388 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001389 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001390 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001391 Token Greater = FormatTok->Tok;
1392 FormatTok = new (Allocator.Allocate()) FormatToken;
1393 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001394 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001395 FormatTok->Tok.getLocation().getLocWithOffset(1);
1396 FormatTok->WhitespaceRange =
1397 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001398 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001399 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001400 GreaterStashed = false;
1401 return FormatTok;
1402 }
1403
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001404 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001405 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001406 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001407 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001408 FormatTok->IsFirst = IsFirstToken;
1409 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001410
1411 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001412 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001413 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001414 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1415 switch (FormatTok->TokenText[i]) {
1416 case '\n':
1417 ++FormatTok->NewlinesBefore;
1418 // FIXME: This is technically incorrect, as it could also
1419 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001420 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1421 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1422 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001423 FormatTok->HasUnescapedNewline = true;
1424 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1425 Column = 0;
1426 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001427 case '\r':
1428 case '\f':
1429 case '\v':
1430 Column = 0;
1431 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001432 case ' ':
1433 ++Column;
1434 break;
1435 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001436 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001437 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001438 case '\\':
1439 ++Column;
1440 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1441 FormatTok->TokenText[i + 1] != '\n'))
1442 FormatTok->Type = TT_ImplicitStringLiteral;
1443 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001444 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001445 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001446 ++Column;
1447 break;
1448 }
1449 }
1450
Daniel Jasper877615c2013-10-11 19:45:02 +00001451 if (FormatTok->Type == TT_ImplicitStringLiteral)
1452 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001453 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001454
Daniel Jasper8369aa52013-07-16 20:28:33 +00001455 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001456 }
Manuel Klimekef920692013-01-07 07:56:50 +00001457
Manuel Klimek1abf7892013-01-04 23:34:14 +00001458 // In case the token starts with escaped newlines, we want to
1459 // take them into account as whitespace - this pattern is quite frequent
1460 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001461 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001462 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1463 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001464 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001465 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001466 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001467 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001468 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001469
1470 FormatTok->WhitespaceRange = SourceRange(
1471 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1472
Manuel Klimek31c85922013-08-29 15:21:40 +00001473 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001474
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001475 TrailingWhitespace = 0;
1476 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001477 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001478 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001479 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001480 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001481 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001482 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001483 FormatTok->Tok.setIdentifierInfo(&Info);
1484 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001485 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001486 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001487 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001488 GreaterStashed = true;
1489 }
1490
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001491 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001492
Alexander Kornienko39856b72013-09-10 09:38:25 +00001493 StringRef Text = FormatTok->TokenText;
1494 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001495 if (FirstNewlinePos == StringRef::npos) {
1496 // FIXME: ColumnWidth actually depends on the start column, we need to
1497 // take this into account when the token is moved.
1498 FormatTok->ColumnWidth =
1499 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1500 Column += FormatTok->ColumnWidth;
1501 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001502 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001503 // FIXME: ColumnWidth actually depends on the start column, we need to
1504 // take this into account when the token is moved.
1505 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1506 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1507
Alexander Kornienko39856b72013-09-10 09:38:25 +00001508 // The last line of the token always starts in column 0.
1509 // Thus, the length can be precomputed even in the presence of tabs.
1510 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1511 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1512 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001513 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001514 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001515
Daniel Jaspere1e43192014-04-01 12:55:11 +00001516 FormatTok->IsForEachMacro =
1517 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1518 FormatTok->Tok.getIdentifierInfo());
1519
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001520 return FormatTok;
1521 }
1522
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001523 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001524 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001525 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001526 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001527 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001528 Lexer &Lex;
1529 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001530 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001531 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001532 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001533 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001534 // Index (in 'Tokens') of the last token that starts a new line.
1535 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001536 SmallVector<FormatToken *, 16> Tokens;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001537 SmallVector<IdentifierInfo*, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001538
Daniel Jasper8369aa52013-07-16 20:28:33 +00001539 void readRawToken(FormatToken &Tok) {
1540 Lex.LexFromRawLexer(Tok.Tok);
1541 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1542 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001543 // For formatting, treat unterminated string literals like normal string
1544 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001545 if (Tok.is(tok::unknown)) {
1546 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1547 Tok.Tok.setKind(tok::string_literal);
1548 Tok.IsUnterminatedLiteral = true;
1549 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1550 Tok.TokenText == "''") {
1551 Tok.Tok.setKind(tok::char_constant);
1552 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001553 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001554 }
1555};
1556
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001557static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1558 switch (Language) {
1559 case FormatStyle::LK_Cpp:
1560 return "C++";
1561 case FormatStyle::LK_JavaScript:
1562 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001563 case FormatStyle::LK_Proto:
1564 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001565 default:
1566 return "Unknown";
1567 }
1568}
1569
Daniel Jasperf7935112012-12-03 18:12:45 +00001570class Formatter : public UnwrappedLineConsumer {
1571public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001572 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001573 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001574 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001575 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001576 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001577 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001578 DEBUG(llvm::dbgs() << "File encoding: "
1579 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1580 : "unknown")
1581 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001582 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1583 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001584 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001585
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001586 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001587 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001588 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001589
1590 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001591 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001592 assert(UnwrappedLines.rbegin()->empty());
1593 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1594 ++Run) {
1595 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1596 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1597 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1598 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1599 }
1600 tooling::Replacements RunResult =
1601 format(AnnotatedLines, StructuralError, Tokens);
1602 DEBUG({
1603 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1604 for (tooling::Replacements::iterator I = RunResult.begin(),
1605 E = RunResult.end();
1606 I != E; ++I) {
1607 llvm::dbgs() << I->toString() << "\n";
1608 }
1609 });
1610 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1611 delete AnnotatedLines[i];
1612 }
1613 Result.insert(RunResult.begin(), RunResult.end());
1614 Whitespaces.reset();
1615 }
1616 return Result;
1617 }
1618
1619 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1620 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001621 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001622 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001623 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001624 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001625 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001626 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001627 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001628 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001629 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001630
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001631 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001632 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1633 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001634 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001635 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001636 return Whitespaces.generateReplacements();
1637 }
1638
1639private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001640 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001641 // Returns \c true if at least one line between I and E or one of their
1642 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001643 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1644 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1645 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001646 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001647 while (I != E) {
1648 AnnotatedLine *Line = *I;
1649 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1650
1651 // If a line is part of a preprocessor directive, it needs to be formatted
1652 // if any token within the directive is affected.
1653 if (Line->InPPDirective) {
1654 FormatToken *Last = Line->Last;
1655 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1656 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1657 Last = (*PPEnd)->Last;
1658 ++PPEnd;
1659 }
1660
1661 if (affectsTokenRange(*Line->First, *Last,
1662 /*IncludeLeadingNewlines=*/false)) {
1663 SomeLineAffected = true;
1664 markAllAsAffected(I, PPEnd);
1665 }
1666 I = PPEnd;
1667 continue;
1668 }
1669
Daniel Jasper38c82402013-11-29 09:27:43 +00001670 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001671 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001672
Daniel Jasper38c82402013-11-29 09:27:43 +00001673 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001674 ++I;
1675 }
1676 return SomeLineAffected;
1677 }
1678
Daniel Jasper9c199562013-11-28 15:58:55 +00001679 // Determines whether 'Line' is affected by the SourceRanges given as input.
1680 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001681 bool nonPPLineAffected(AnnotatedLine *Line,
1682 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001683 bool SomeLineAffected = false;
1684 Line->ChildrenAffected =
1685 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1686 if (Line->ChildrenAffected)
1687 SomeLineAffected = true;
1688
1689 // Stores whether one of the line's tokens is directly affected.
1690 bool SomeTokenAffected = false;
1691 // Stores whether we need to look at the leading newlines of the next token
1692 // in order to determine whether it was affected.
1693 bool IncludeLeadingNewlines = false;
1694
1695 // Stores whether the first child line of any of this line's tokens is
1696 // affected.
1697 bool SomeFirstChildAffected = false;
1698
1699 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1700 // Determine whether 'Tok' was affected.
1701 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1702 SomeTokenAffected = true;
1703
1704 // Determine whether the first child of 'Tok' was affected.
1705 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1706 SomeFirstChildAffected = true;
1707
1708 IncludeLeadingNewlines = Tok->Children.empty();
1709 }
1710
1711 // Was this line moved, i.e. has it previously been on the same line as an
1712 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001713 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1714 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001715
Daniel Jasper38c82402013-11-29 09:27:43 +00001716 bool IsContinuedComment = Line->First->is(tok::comment) &&
1717 Line->First->Next == NULL &&
1718 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001719 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001720 PreviousLine->Last->is(tok::comment);
1721
1722 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1723 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001724 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001725 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001726 }
1727 return SomeLineAffected;
1728 }
1729
Daniel Jasper5500f612013-11-25 11:08:59 +00001730 // Marks all lines between I and E as well as all their children as affected.
1731 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1732 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1733 while (I != E) {
1734 (*I)->Affected = true;
1735 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1736 ++I;
1737 }
1738 }
1739
1740 // Returns true if the range from 'First' to 'Last' intersects with one of the
1741 // input ranges.
1742 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1743 bool IncludeLeadingNewlines) {
1744 SourceLocation Start = First.WhitespaceRange.getBegin();
1745 if (!IncludeLeadingNewlines)
1746 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001747 SourceLocation End = Last.getStartOfNonWhitespace();
1748 if (Last.TokenText.size() > 0)
1749 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001750 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1751 return affectsCharSourceRange(Range);
1752 }
1753
1754 // Returns true if one of the input ranges intersect the leading empty lines
1755 // before 'Tok'.
1756 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1757 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1758 Tok.WhitespaceRange.getBegin(),
1759 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1760 return affectsCharSourceRange(EmptyLineRange);
1761 }
1762
1763 // Returns true if 'Range' intersects with one of the input ranges.
1764 bool affectsCharSourceRange(const CharSourceRange &Range) {
1765 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1766 E = Ranges.end();
1767 I != E; ++I) {
1768 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1769 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1770 return true;
1771 }
1772 return false;
1773 }
1774
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001775 static bool inputUsesCRLF(StringRef Text) {
1776 return Text.count('\r') * 2 > Text.count('\n');
1777 }
1778
Manuel Klimek71814b42013-10-11 21:25:45 +00001779 void
1780 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001781 unsigned CountBoundToVariable = 0;
1782 unsigned CountBoundToType = 0;
1783 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001784 bool HasBinPackedFunction = false;
1785 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001786 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001787 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001788 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001789 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001790 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001791 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001792 bool SpacesBefore =
1793 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1794 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1795 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001796 if (SpacesBefore && !SpacesAfter)
1797 ++CountBoundToVariable;
1798 else if (!SpacesBefore && SpacesAfter)
1799 ++CountBoundToType;
1800 }
1801
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001802 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1803 if (Tok->is(tok::coloncolon) &&
1804 Tok->Previous->Type == TT_TemplateOpener)
1805 HasCpp03IncompatibleFormat = true;
1806 if (Tok->Type == TT_TemplateCloser &&
1807 Tok->Previous->Type == TT_TemplateCloser)
1808 HasCpp03IncompatibleFormat = true;
1809 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001810
1811 if (Tok->PackingKind == PPK_BinPacked)
1812 HasBinPackedFunction = true;
1813 if (Tok->PackingKind == PPK_OnePerLine)
1814 HasOnePerLineFunction = true;
1815
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001816 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001817 }
1818 }
1819 if (Style.DerivePointerBinding) {
1820 if (CountBoundToType > CountBoundToVariable)
1821 Style.PointerBindsToType = true;
1822 else if (CountBoundToType < CountBoundToVariable)
1823 Style.PointerBindsToType = false;
1824 }
1825 if (Style.Standard == FormatStyle::LS_Auto) {
1826 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1827 : FormatStyle::LS_Cpp03;
1828 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001829 BinPackInconclusiveFunctions =
1830 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001831 }
1832
Craig Topperfb6b25b2014-03-15 04:29:04 +00001833 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001834 assert(!UnwrappedLines.empty());
1835 UnwrappedLines.back().push_back(TheLine);
1836 }
1837
Craig Topperfb6b25b2014-03-15 04:29:04 +00001838 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001839 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001840 }
1841
1842 FormatStyle Style;
1843 Lexer &Lex;
1844 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001845 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001846 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001847 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001848
1849 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001850 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001851};
1852
Craig Topperaf35e852013-06-30 22:29:28 +00001853} // end anonymous namespace
1854
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001855tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1856 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001857 std::vector<CharSourceRange> Ranges) {
1858 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001859 return formatter.format();
1860}
1861
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001862tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1863 std::vector<tooling::Range> Ranges,
1864 StringRef FileName) {
1865 FileManager Files((FileSystemOptions()));
1866 DiagnosticsEngine Diagnostics(
1867 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1868 new DiagnosticOptions);
1869 SourceManager SourceMgr(Diagnostics, Files);
1870 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1871 const clang::FileEntry *Entry =
1872 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1873 SourceMgr.overrideFileContents(Entry, Buf);
1874 FileID ID =
1875 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001876 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1877 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001878 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1879 std::vector<CharSourceRange> CharRanges;
1880 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1881 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1882 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1883 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1884 }
1885 return reformat(Style, Lex, SourceMgr, CharRanges);
1886}
1887
Alexander Kornienko1e808872013-06-28 12:51:24 +00001888LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001889 LangOptions LangOpts;
1890 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001891 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001892 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001893 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00001894 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001895 LangOpts.Bool = 1;
1896 LangOpts.ObjC1 = 1;
1897 LangOpts.ObjC2 = 1;
1898 return LangOpts;
1899}
1900
Edwin Vaned544aa72013-09-30 13:31:48 +00001901const char *StyleOptionHelpDescription =
1902 "Coding style, currently supports:\n"
1903 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1904 "Use -style=file to load style configuration from\n"
1905 ".clang-format file located in one of the parent\n"
1906 "directories of the source file (or current\n"
1907 "directory for stdin).\n"
1908 "Use -style=\"{key: value, ...}\" to set specific\n"
1909 "parameters, e.g.:\n"
1910 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1911
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001912static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001913 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001914 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001915 } else if (FileName.endswith_lower(".proto") ||
1916 FileName.endswith_lower(".protodevel")) {
1917 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001918 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001919 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001920}
1921
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001922FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1923 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001924 FormatStyle Style = getLLVMStyle();
1925 Style.Language = getLanguageByFileName(FileName);
1926 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001927 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1928 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001929 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001930 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001931
1932 if (StyleName.startswith("{")) {
1933 // Parse YAML/JSON style from the command line.
1934 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001935 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1936 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001937 }
1938 return Style;
1939 }
1940
1941 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001942 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001943 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1944 << " style\n";
1945 return Style;
1946 }
1947
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001948 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001949 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001950 SmallString<128> Path(FileName);
1951 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001952 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001953 Directory = llvm::sys::path::parent_path(Directory)) {
1954 if (!llvm::sys::fs::is_directory(Directory))
1955 continue;
1956 SmallString<128> ConfigFile(Directory);
1957
1958 llvm::sys::path::append(ConfigFile, ".clang-format");
1959 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1960 bool IsFile = false;
1961 // Ignore errors from is_regular_file: we only need to know if we can read
1962 // the file or not.
1963 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1964
1965 if (!IsFile) {
1966 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1967 ConfigFile = Directory;
1968 llvm::sys::path::append(ConfigFile, "_clang-format");
1969 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1970 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1971 }
1972
1973 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001974 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001975 if (llvm::error_code ec =
1976 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001977 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001978 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001979 }
1980 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001981 if (ec == llvm::errc::not_supported) {
1982 if (!UnsuitableConfigFiles.empty())
1983 UnsuitableConfigFiles.append(", ");
1984 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001985 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001986 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001987 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1988 << "\n";
1989 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001990 }
1991 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1992 return Style;
1993 }
1994 }
1995 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1996 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001997 if (!UnsuitableConfigFiles.empty()) {
1998 llvm::errs() << "Configuration file(s) do(es) not support "
1999 << getLanguageName(Style.Language) << ": "
2000 << UnsuitableConfigFiles << "\n";
2001 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002002 return Style;
2003}
2004
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002005} // namespace format
2006} // namespace clang