blob: 21334ad9c80520c019c774055e50a352a3b4cb24 [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)) {
657 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000658 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000659 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000660 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000661
662 if (!nextTwoLinesFitInto(I, Limit))
663 return 0;
664
665 // Second, check that the next line does not contain any braces - if it
666 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000667 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 return 0;
669 do {
670 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
671 return 0;
672 Tok = Tok->Next;
673 } while (Tok != NULL);
674
675 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000676 Tok = I[2]->First;
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000677 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000678 return 0;
679
680 return 2;
681 }
682 return 0;
683 }
684
Daniel Jasper64989962014-02-07 13:45:27 +0000685 /// Returns the modified column limit for \p I if it is inside a macro and
686 /// needs a trailing '\'.
687 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000688 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000689 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
690 unsigned Limit) {
691 if (I[0]->InPPDirective && I + 1 != E &&
692 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
693 return Limit < 2 ? 0 : Limit - 2;
694 }
695 return Limit;
696 }
697
Daniel Jasper56f8b432013-11-06 23:12:09 +0000698 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
699 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000700 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
701 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000702 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000703 }
704
Daniel Jasper234379f2013-12-24 13:31:25 +0000705 bool containsMustBreak(const AnnotatedLine *Line) {
706 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
707 if (Tok->MustBreakBefore)
708 return true;
709 }
710 return false;
711 }
712
Daniel Jasper56f8b432013-11-06 23:12:09 +0000713 const FormatStyle &Style;
714};
715
Daniel Jasperf7935112012-12-03 18:12:45 +0000716class UnwrappedLineFormatter {
717public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000718 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000719 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000720 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000721 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
722 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000723
Daniel Jasper56f8b432013-11-06 23:12:09 +0000724 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000725 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000726 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000727 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
728 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000729 auto CacheIt = PenaltyCache.find(CacheKey);
730 if (DryRun && CacheIt != PenaltyCache.end())
731 return CacheIt->second;
732
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000733 assert(!Lines.empty());
734 unsigned Penalty = 0;
735 std::vector<int> IndentForLevel;
736 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
737 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000738 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000739 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
740 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000741 I != E; ++I) {
742 const AnnotatedLine &TheLine = **I;
743 const FormatToken *FirstTok = TheLine.First;
744 int Offset = getIndentOffset(*FirstTok);
745
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000746 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000747 unsigned Indent;
748 if (TheLine.InPPDirective) {
749 Indent = TheLine.Level * Style.IndentWidth;
750 } else {
751 while (IndentForLevel.size() <= TheLine.Level)
752 IndentForLevel.push_back(-1);
753 IndentForLevel.resize(TheLine.Level + 1);
754 Indent = getIndent(IndentForLevel, TheLine.Level);
755 }
756 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000757 if (static_cast<int>(Indent) + Offset >= 0)
758 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000759
760 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000761 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000762 if (MergedLines > 0 && Style.ColumnLimit == 0) {
763 // Disallow line merging if there is a break at the start of one of the
764 // input lines.
765 for (unsigned i = 0; i < MergedLines; ++i) {
766 if (I[i + 1]->First->NewlinesBefore > 0)
767 MergedLines = 0;
768 }
769 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000770 if (!DryRun) {
771 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000772 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000773 }
774 }
775 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000776
Daniel Jasper9c199562013-11-28 15:58:55 +0000777 bool FixIndentation =
778 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000779 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000780 if (PreviousLine && PreviousLine->Affected && !DryRun) {
781 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000782 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
783 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
784 /*IndentLevel=*/0, /*Spaces=*/0,
785 /*TargetColumn=*/0);
786 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000787 } else if (TheLine.Type != LT_Invalid &&
788 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000789 if (FirstTok->WhitespaceRange.isValid()) {
790 if (!DryRun)
791 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
792 Indent, TheLine.InPPDirective);
793 } else {
794 Indent = LevelIndent = FirstTok->OriginalColumn;
795 }
796
797 // If everything fits on a single line, just put it there.
798 unsigned ColumnLimit = Style.ColumnLimit;
799 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000800 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000801 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
802 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
803 }
804
805 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
806 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
807 while (State.NextToken != NULL)
808 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
809 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000810 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000811 NoColumnLimitFormatter Formatter(Indenter);
812 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000813 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000814 } else {
815 Penalty += format(TheLine, Indent, DryRun);
816 }
817
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000818 if (!TheLine.InPPDirective)
819 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000820 } else if (TheLine.ChildrenAffected) {
821 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000822 } else {
823 // Format the first token if necessary, and notify the WhitespaceManager
824 // about the unchanged whitespace.
825 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
826 if (Tok == TheLine.First &&
827 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
828 unsigned LevelIndent = Tok->OriginalColumn;
829 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000830 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000831 if ((PreviousLine && PreviousLine->Affected) ||
832 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000833 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
834 TheLine.InPPDirective);
835 } else {
836 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
837 }
838 }
839
840 if (static_cast<int>(LevelIndent) - Offset >= 0)
841 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000842 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000843 IndentForLevel[TheLine.Level] = LevelIndent;
844 } else if (!DryRun) {
845 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
846 }
847 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000848 }
849 if (!DryRun) {
850 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
851 Tok->Finalized = true;
852 }
853 }
854 PreviousLine = *I;
855 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000856 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000857 return Penalty;
858 }
859
860private:
861 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000862 ///
863 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000864 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
865 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000866 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000867
Daniel Jasperacc33662013-02-08 08:22:00 +0000868 // If the ObjC method declaration does not fit on a line, we should format
869 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000870 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000871 State.Stack.back().BreakBeforeParameter = true;
872
Daniel Jasper4b866272013-02-01 11:00:45 +0000873 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000874 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 }
876
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000877 /// \brief An edge in the solution space from \c Previous->State to \c State,
878 /// inserting a newline dependent on the \c NewLine.
879 struct StateNode {
880 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000881 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 LineState State;
883 bool NewLine;
884 StateNode *Previous;
885 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000886
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000887 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
888 ///
889 /// In case of equal penalties, we want to prefer states that were inserted
890 /// first. During state generation we make sure that we insert states first
891 /// that break the line as late as possible.
892 typedef std::pair<unsigned, unsigned> OrderedPenalty;
893
894 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
895 /// \c State has the given \c OrderedPenalty.
896 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
897
898 /// \brief The BFS queue type.
899 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
900 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000901
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000902 /// \brief Get the offset of the line relatively to the level.
903 ///
904 /// For example, 'public:' labels in classes are offset by 1 or 2
905 /// characters to the left from their level.
906 int getIndentOffset(const FormatToken &RootToken) {
907 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
908 return Style.AccessModifierOffset;
909 return 0;
910 }
911
912 /// \brief Add a new line and the required indent before the first Token
913 /// of the \c UnwrappedLine if there was no structural parsing error.
914 void formatFirstToken(FormatToken &RootToken,
915 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
916 unsigned Indent, bool InPPDirective) {
917 unsigned Newlines =
918 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
919 // Remove empty lines before "}" where applicable.
920 if (RootToken.is(tok::r_brace) &&
921 (!RootToken.Next ||
922 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
923 Newlines = std::min(Newlines, 1u);
924 if (Newlines == 0 && !RootToken.IsFirst)
925 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000926 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
927 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000928
Daniel Jasper11164bd2014-03-21 12:58:53 +0000929 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000930 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
931 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000932 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000933 Newlines = 1;
934
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000935 // Insert extra new line before access specifiers.
936 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
937 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
938 ++Newlines;
939
940 // Remove empty lines after access specifiers.
941 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
942 Newlines = std::min(1u, Newlines);
943
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000944 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
945 Indent, InPPDirective &&
946 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000947 }
948
949 /// \brief Get the indent of \p Level from \p IndentForLevel.
950 ///
951 /// \p IndentForLevel must contain the indent for the level \c l
952 /// at \p IndentForLevel[l], or a value < 0 if the indent for
953 /// that level is unknown.
954 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
955 if (IndentForLevel[Level] != -1)
956 return IndentForLevel[Level];
957 if (Level == 0)
958 return 0;
959 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
960 }
961
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000962 void join(AnnotatedLine &A, const AnnotatedLine &B) {
963 assert(!A.Last->Next);
964 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000965 if (B.Affected)
966 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000967 A.Last->Next = B.First;
968 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000969 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000970 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
971 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
972 Tok->TotalLength += LengthA;
973 A.Last = Tok;
974 }
975 }
976
977 unsigned getColumnLimit(bool InPPDirective) const {
978 // In preprocessor directives reserve two chars for trailing " \"
979 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
980 }
981
Daniel Jasper4b866272013-02-01 11:00:45 +0000982 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000983 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000984 /// This implements a variant of Dijkstra's algorithm on the graph that spans
985 /// the solution space (\c LineStates are the nodes). The algorithm tries to
986 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000987 /// to a state where all tokens are placed. Returns the penalty.
988 ///
989 /// If \p DryRun is \c false, directly applies the changes.
990 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000991 std::set<LineState> Seen;
992
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000993 // Increasing count of \c StateNode items we have created. This is used to
994 // create a deterministic order independent of the container.
995 unsigned Count = 0;
996 QueueType Queue;
997
Daniel Jasper4b866272013-02-01 11:00:45 +0000998 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000999 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001000 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1001 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1002 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001003
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001004 unsigned Penalty = 0;
1005
Daniel Jasper4b866272013-02-01 11:00:45 +00001006 // While not empty, take first element and follow edges.
1007 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001008 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001009 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001010 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001011 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001012 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001013 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001014 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001015
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001016 // Cut off the analysis of certain solutions if the analysis gets too
1017 // complex. See description of IgnoreStackForComparison.
1018 if (Count > 10000)
1019 Node->State.IgnoreStackForComparison = true;
1020
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001021 if (!Seen.insert(Node->State).second)
1022 // State already examined with lower penalty.
1023 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001024
Manuel Klimek71814b42013-10-11 21:25:45 +00001025 FormatDecision LastFormat = Node->State.NextToken->Decision;
1026 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001027 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001028 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001029 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001030 }
1031
Manuel Klimek71814b42013-10-11 21:25:45 +00001032 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001033 // We were unable to find a solution, do nothing.
1034 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001035 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001036 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001037 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001038
Daniel Jasper4b866272013-02-01 11:00:45 +00001039 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001040 if (!DryRun)
1041 reconstructPath(InitialState, Queue.top().second);
1042
Alexander Kornienko49149672013-05-10 11:56:10 +00001043 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1044 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001045
1046 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001047 }
1048
1049 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001050 std::deque<StateNode *> Path;
1051 // We do not need a break before the initial token.
1052 while (Current->Previous) {
1053 Path.push_front(Current);
1054 Current = Current->Previous;
1055 }
1056 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1057 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001058 unsigned Penalty = 0;
1059 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1060 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1061
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001062 DEBUG({
1063 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001064 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001065 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001066 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001067 }
1068 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001069 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001070 }
1071
Manuel Klimekaf491072013-02-13 10:54:19 +00001072 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001073 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001074 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001075 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001076 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001077 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001078 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001079 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001080 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001081 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001082
1083 StateNode *Node = new (Allocator.Allocate())
1084 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001085 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1086 return;
1087
Daniel Jasperde0328a2013-08-16 11:20:30 +00001088 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001089
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001090 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1091 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001092 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001093
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001094 /// \brief If the \p State's next token is an r_brace closing a nested block,
1095 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001096 ///
1097 /// Returns \c true if all children could be placed successfully and adapts
1098 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1099 /// creates changes using \c Whitespaces.
1100 ///
1101 /// The crucial idea here is that children always get formatted upon
1102 /// encountering the closing brace right after the nested block. Now, if we
1103 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1104 /// \c false), the entire block has to be kept on the same line (which is only
1105 /// possible if it fits on the line, only contains a single statement, etc.
1106 ///
1107 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1108 /// break after the "{", format all lines with correct indentation and the put
1109 /// the closing "}" on yet another new line.
1110 ///
1111 /// This enables us to keep the simple structure of the
1112 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1113 /// break or don't break.
1114 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1115 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001116 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001117 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1118 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1119 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001120 // The previous token does not open a block. Nothing to do. We don't
1121 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001122 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001123
1124 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001125 int AdditionalIndent = State.Stack.back().Indent -
1126 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001127 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1128 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001129 return true;
1130 }
1131
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001132 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001133 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001134 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001135
Daniel Jasper21397a32014-04-09 12:21:48 +00001136 // Cannot merge into one line if this line ends on a comment.
1137 if (Previous.is(tok::comment))
1138 return false;
1139
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001140 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001141 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001142 return false;
1143
Daniel Jasper98583d52014-04-15 08:28:06 +00001144 // If the child line exceeds the column limit, we wouldn't want to merge it.
1145 // We add +2 for the trailing " }".
1146 if (Style.ColumnLimit > 0 &&
1147 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1148 Style.ColumnLimit)
1149 return false;
1150
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001151 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001152 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001153 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001154 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001155 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001156 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001157 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001158
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001159 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001160 return true;
1161 }
1162
Daniel Jasperde0328a2013-08-16 11:20:30 +00001163 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001164 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001165 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001166 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001167
1168 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001169
1170 // Cache to store the penalty of formatting a vector of AnnotatedLines
1171 // starting from a specific additional offset. Improves performance if there
1172 // are many nested blocks.
1173 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1174 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001175};
1176
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001177class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001178public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001179 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001180 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001181 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001182 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
Manuel Klimek68b03042014-04-14 09:14:11 +00001183 IdentTable(getFormattingLangOpts()), Encoding(Encoding),
1184 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001185 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001186
1187 for (const std::string& ForEachMacro : Style.ForEachMacros)
1188 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1189 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001190 }
1191
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001192 ArrayRef<FormatToken *> lex() {
1193 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001194 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001195 do {
1196 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001197 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001198 if (Tokens.back()->NewlinesBefore > 0)
1199 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001200 } while (Tokens.back()->Tok.isNot(tok::eof));
1201 return Tokens;
1202 }
1203
1204 IdentifierTable &getIdentTable() { return IdentTable; }
1205
1206private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001207 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001208 if (tryMerge_TMacro())
1209 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001210 if (tryMergeConflictMarkers())
1211 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001212
1213 if (Style.Language == FormatStyle::LK_JavaScript) {
1214 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1215 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1216 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1217 tok::greaterequal };
1218 // FIXME: We probably need to change token type to mimic operator with the
1219 // correct priority.
1220 if (tryMergeTokens(JSIdentity))
1221 return;
1222 if (tryMergeTokens(JSNotIdentity))
1223 return;
1224 if (tryMergeTokens(JSShiftEqual))
1225 return;
1226 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001227 }
1228
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001229 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1230 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001231 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001232
1233 SmallVectorImpl<FormatToken *>::const_iterator First =
1234 Tokens.end() - Kinds.size();
1235 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001236 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001237 unsigned AddLength = 0;
1238 for (unsigned i = 1; i < Kinds.size(); ++i) {
1239 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1240 First[i]->WhitespaceRange.getEnd())
1241 return false;
1242 AddLength += First[i]->TokenText.size();
1243 }
1244 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1245 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1246 First[0]->TokenText.size() + AddLength);
1247 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001248 return true;
1249 }
1250
1251 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001252 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001253 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001254 FormatToken *Last = Tokens.back();
1255 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001256 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001257
1258 FormatToken *String = Tokens[Tokens.size() - 2];
1259 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001260 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001261
1262 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001263 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001264
1265 FormatToken *Macro = Tokens[Tokens.size() - 4];
1266 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001267 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001268
1269 const char *Start = Macro->TokenText.data();
1270 const char *End = Last->TokenText.data() + Last->TokenText.size();
1271 String->TokenText = StringRef(Start, End - Start);
1272 String->IsFirst = Macro->IsFirst;
1273 String->LastNewlineOffset = Macro->LastNewlineOffset;
1274 String->WhitespaceRange = Macro->WhitespaceRange;
1275 String->OriginalColumn = Macro->OriginalColumn;
1276 String->ColumnWidth = encoding::columnWidthWithTabs(
1277 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1278
1279 Tokens.pop_back();
1280 Tokens.pop_back();
1281 Tokens.pop_back();
1282 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001283 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001284 }
1285
Manuel Klimek68b03042014-04-14 09:14:11 +00001286 bool tryMergeConflictMarkers() {
1287 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1288 return false;
1289
1290 // Conflict lines look like:
1291 // <marker> <text from the vcs>
1292 // For example:
1293 // >>>>>>> /file/in/file/system at revision 1234
1294 //
1295 // We merge all tokens in a line that starts with a conflict marker
1296 // into a single token with a special token type that the unwrapped line
1297 // parser will use to correctly rebuild the underlying code.
1298
1299 FileID ID;
1300 // Get the position of the first token in the line.
1301 unsigned FirstInLineOffset;
1302 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1303 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1304 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1305 // Calculate the offset of the start of the current line.
1306 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1307 if (LineOffset == StringRef::npos) {
1308 LineOffset = 0;
1309 } else {
1310 ++LineOffset;
1311 }
1312
1313 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1314 StringRef LineStart;
1315 if (FirstSpace == StringRef::npos) {
1316 LineStart = Buffer.substr(LineOffset);
1317 } else {
1318 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1319 }
1320
1321 TokenType Type = TT_Unknown;
1322 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1323 Type = TT_ConflictStart;
1324 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1325 LineStart == "====") {
1326 Type = TT_ConflictAlternative;
1327 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1328 Type = TT_ConflictEnd;
1329 }
1330
1331 if (Type != TT_Unknown) {
1332 FormatToken *Next = Tokens.back();
1333
1334 Tokens.resize(FirstInLineIndex + 1);
1335 // We do not need to build a complete token here, as we will skip it
1336 // during parsing anyway (as we must not touch whitespace around conflict
1337 // markers).
1338 Tokens.back()->Type = Type;
1339 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1340
1341 Tokens.push_back(Next);
1342 return true;
1343 }
1344
1345 return false;
1346 }
1347
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001348 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001350 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001351 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001352 Token Greater = FormatTok->Tok;
1353 FormatTok = new (Allocator.Allocate()) FormatToken;
1354 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001355 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001356 FormatTok->Tok.getLocation().getLocWithOffset(1);
1357 FormatTok->WhitespaceRange =
1358 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001359 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001360 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001361 GreaterStashed = false;
1362 return FormatTok;
1363 }
1364
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001365 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001366 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001367 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001368 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001369 FormatTok->IsFirst = IsFirstToken;
1370 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001371
1372 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001373 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001374 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001375 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1376 switch (FormatTok->TokenText[i]) {
1377 case '\n':
1378 ++FormatTok->NewlinesBefore;
1379 // FIXME: This is technically incorrect, as it could also
1380 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001381 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1382 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1383 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001384 FormatTok->HasUnescapedNewline = true;
1385 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1386 Column = 0;
1387 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001388 case '\r':
1389 case '\f':
1390 case '\v':
1391 Column = 0;
1392 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001393 case ' ':
1394 ++Column;
1395 break;
1396 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001397 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001398 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001399 case '\\':
1400 ++Column;
1401 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1402 FormatTok->TokenText[i + 1] != '\n'))
1403 FormatTok->Type = TT_ImplicitStringLiteral;
1404 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001405 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001406 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001407 ++Column;
1408 break;
1409 }
1410 }
1411
Daniel Jasper877615c2013-10-11 19:45:02 +00001412 if (FormatTok->Type == TT_ImplicitStringLiteral)
1413 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001414 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001415
Daniel Jasper8369aa52013-07-16 20:28:33 +00001416 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001417 }
Manuel Klimekef920692013-01-07 07:56:50 +00001418
Manuel Klimek1abf7892013-01-04 23:34:14 +00001419 // In case the token starts with escaped newlines, we want to
1420 // take them into account as whitespace - this pattern is quite frequent
1421 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001422 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001423 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1424 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001425 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001426 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001427 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001428 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001429 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001430
1431 FormatTok->WhitespaceRange = SourceRange(
1432 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1433
Manuel Klimek31c85922013-08-29 15:21:40 +00001434 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001435
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001436 TrailingWhitespace = 0;
1437 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001438 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001439 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001440 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001441 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001442 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001443 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001444 FormatTok->Tok.setIdentifierInfo(&Info);
1445 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001446 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001447 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001448 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001449 GreaterStashed = true;
1450 }
1451
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001452 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001453
Alexander Kornienko39856b72013-09-10 09:38:25 +00001454 StringRef Text = FormatTok->TokenText;
1455 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001456 if (FirstNewlinePos == StringRef::npos) {
1457 // FIXME: ColumnWidth actually depends on the start column, we need to
1458 // take this into account when the token is moved.
1459 FormatTok->ColumnWidth =
1460 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1461 Column += FormatTok->ColumnWidth;
1462 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001463 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001464 // FIXME: ColumnWidth actually depends on the start column, we need to
1465 // take this into account when the token is moved.
1466 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1467 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1468
Alexander Kornienko39856b72013-09-10 09:38:25 +00001469 // The last line of the token always starts in column 0.
1470 // Thus, the length can be precomputed even in the presence of tabs.
1471 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1472 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1473 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001474 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001475 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001476
Daniel Jaspere1e43192014-04-01 12:55:11 +00001477 FormatTok->IsForEachMacro =
1478 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1479 FormatTok->Tok.getIdentifierInfo());
1480
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001481 return FormatTok;
1482 }
1483
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001484 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001485 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001486 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001487 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001488 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001489 Lexer &Lex;
1490 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001491 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001492 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001493 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001494 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001495 // Index (in 'Tokens') of the last token that starts a new line.
1496 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001497 SmallVector<FormatToken *, 16> Tokens;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001498 SmallVector<IdentifierInfo*, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001499
Daniel Jasper8369aa52013-07-16 20:28:33 +00001500 void readRawToken(FormatToken &Tok) {
1501 Lex.LexFromRawLexer(Tok.Tok);
1502 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1503 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001504 // For formatting, treat unterminated string literals like normal string
1505 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001506 if (Tok.is(tok::unknown)) {
1507 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1508 Tok.Tok.setKind(tok::string_literal);
1509 Tok.IsUnterminatedLiteral = true;
1510 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1511 Tok.TokenText == "''") {
1512 Tok.Tok.setKind(tok::char_constant);
1513 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001514 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001515 }
1516};
1517
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001518static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1519 switch (Language) {
1520 case FormatStyle::LK_Cpp:
1521 return "C++";
1522 case FormatStyle::LK_JavaScript:
1523 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001524 case FormatStyle::LK_Proto:
1525 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001526 default:
1527 return "Unknown";
1528 }
1529}
1530
Daniel Jasperf7935112012-12-03 18:12:45 +00001531class Formatter : public UnwrappedLineConsumer {
1532public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001533 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001534 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001535 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001536 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001537 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001538 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001539 DEBUG(llvm::dbgs() << "File encoding: "
1540 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1541 : "unknown")
1542 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001543 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1544 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001545 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001546
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001547 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001548 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001549 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001550
1551 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001552 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001553 assert(UnwrappedLines.rbegin()->empty());
1554 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1555 ++Run) {
1556 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1557 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1558 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1559 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1560 }
1561 tooling::Replacements RunResult =
1562 format(AnnotatedLines, StructuralError, Tokens);
1563 DEBUG({
1564 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1565 for (tooling::Replacements::iterator I = RunResult.begin(),
1566 E = RunResult.end();
1567 I != E; ++I) {
1568 llvm::dbgs() << I->toString() << "\n";
1569 }
1570 });
1571 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1572 delete AnnotatedLines[i];
1573 }
1574 Result.insert(RunResult.begin(), RunResult.end());
1575 Whitespaces.reset();
1576 }
1577 return Result;
1578 }
1579
1580 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1581 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001582 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001583 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001584 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001585 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001586 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001587 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001588 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001589 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001590 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001591
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001592 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001593 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1594 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001595 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001596 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001597 return Whitespaces.generateReplacements();
1598 }
1599
1600private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001601 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001602 // Returns \c true if at least one line between I and E or one of their
1603 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001604 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1605 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1606 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001607 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001608 while (I != E) {
1609 AnnotatedLine *Line = *I;
1610 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1611
1612 // If a line is part of a preprocessor directive, it needs to be formatted
1613 // if any token within the directive is affected.
1614 if (Line->InPPDirective) {
1615 FormatToken *Last = Line->Last;
1616 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1617 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1618 Last = (*PPEnd)->Last;
1619 ++PPEnd;
1620 }
1621
1622 if (affectsTokenRange(*Line->First, *Last,
1623 /*IncludeLeadingNewlines=*/false)) {
1624 SomeLineAffected = true;
1625 markAllAsAffected(I, PPEnd);
1626 }
1627 I = PPEnd;
1628 continue;
1629 }
1630
Daniel Jasper38c82402013-11-29 09:27:43 +00001631 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001632 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001633
Daniel Jasper38c82402013-11-29 09:27:43 +00001634 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001635 ++I;
1636 }
1637 return SomeLineAffected;
1638 }
1639
Daniel Jasper9c199562013-11-28 15:58:55 +00001640 // Determines whether 'Line' is affected by the SourceRanges given as input.
1641 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001642 bool nonPPLineAffected(AnnotatedLine *Line,
1643 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001644 bool SomeLineAffected = false;
1645 Line->ChildrenAffected =
1646 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1647 if (Line->ChildrenAffected)
1648 SomeLineAffected = true;
1649
1650 // Stores whether one of the line's tokens is directly affected.
1651 bool SomeTokenAffected = false;
1652 // Stores whether we need to look at the leading newlines of the next token
1653 // in order to determine whether it was affected.
1654 bool IncludeLeadingNewlines = false;
1655
1656 // Stores whether the first child line of any of this line's tokens is
1657 // affected.
1658 bool SomeFirstChildAffected = false;
1659
1660 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1661 // Determine whether 'Tok' was affected.
1662 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1663 SomeTokenAffected = true;
1664
1665 // Determine whether the first child of 'Tok' was affected.
1666 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1667 SomeFirstChildAffected = true;
1668
1669 IncludeLeadingNewlines = Tok->Children.empty();
1670 }
1671
1672 // Was this line moved, i.e. has it previously been on the same line as an
1673 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001674 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1675 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001676
Daniel Jasper38c82402013-11-29 09:27:43 +00001677 bool IsContinuedComment = Line->First->is(tok::comment) &&
1678 Line->First->Next == NULL &&
1679 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001680 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001681 PreviousLine->Last->is(tok::comment);
1682
1683 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1684 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001685 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001686 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001687 }
1688 return SomeLineAffected;
1689 }
1690
Daniel Jasper5500f612013-11-25 11:08:59 +00001691 // Marks all lines between I and E as well as all their children as affected.
1692 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1693 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1694 while (I != E) {
1695 (*I)->Affected = true;
1696 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1697 ++I;
1698 }
1699 }
1700
1701 // Returns true if the range from 'First' to 'Last' intersects with one of the
1702 // input ranges.
1703 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1704 bool IncludeLeadingNewlines) {
1705 SourceLocation Start = First.WhitespaceRange.getBegin();
1706 if (!IncludeLeadingNewlines)
1707 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001708 SourceLocation End = Last.getStartOfNonWhitespace();
1709 if (Last.TokenText.size() > 0)
1710 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001711 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1712 return affectsCharSourceRange(Range);
1713 }
1714
1715 // Returns true if one of the input ranges intersect the leading empty lines
1716 // before 'Tok'.
1717 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1718 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1719 Tok.WhitespaceRange.getBegin(),
1720 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1721 return affectsCharSourceRange(EmptyLineRange);
1722 }
1723
1724 // Returns true if 'Range' intersects with one of the input ranges.
1725 bool affectsCharSourceRange(const CharSourceRange &Range) {
1726 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1727 E = Ranges.end();
1728 I != E; ++I) {
1729 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1730 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1731 return true;
1732 }
1733 return false;
1734 }
1735
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001736 static bool inputUsesCRLF(StringRef Text) {
1737 return Text.count('\r') * 2 > Text.count('\n');
1738 }
1739
Manuel Klimek71814b42013-10-11 21:25:45 +00001740 void
1741 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001742 unsigned CountBoundToVariable = 0;
1743 unsigned CountBoundToType = 0;
1744 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001745 bool HasBinPackedFunction = false;
1746 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001747 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001748 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001749 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001750 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001751 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001752 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001753 bool SpacesBefore =
1754 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1755 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1756 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001757 if (SpacesBefore && !SpacesAfter)
1758 ++CountBoundToVariable;
1759 else if (!SpacesBefore && SpacesAfter)
1760 ++CountBoundToType;
1761 }
1762
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001763 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1764 if (Tok->is(tok::coloncolon) &&
1765 Tok->Previous->Type == TT_TemplateOpener)
1766 HasCpp03IncompatibleFormat = true;
1767 if (Tok->Type == TT_TemplateCloser &&
1768 Tok->Previous->Type == TT_TemplateCloser)
1769 HasCpp03IncompatibleFormat = true;
1770 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001771
1772 if (Tok->PackingKind == PPK_BinPacked)
1773 HasBinPackedFunction = true;
1774 if (Tok->PackingKind == PPK_OnePerLine)
1775 HasOnePerLineFunction = true;
1776
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001777 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001778 }
1779 }
1780 if (Style.DerivePointerBinding) {
1781 if (CountBoundToType > CountBoundToVariable)
1782 Style.PointerBindsToType = true;
1783 else if (CountBoundToType < CountBoundToVariable)
1784 Style.PointerBindsToType = false;
1785 }
1786 if (Style.Standard == FormatStyle::LS_Auto) {
1787 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1788 : FormatStyle::LS_Cpp03;
1789 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001790 BinPackInconclusiveFunctions =
1791 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001792 }
1793
Craig Topperfb6b25b2014-03-15 04:29:04 +00001794 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001795 assert(!UnwrappedLines.empty());
1796 UnwrappedLines.back().push_back(TheLine);
1797 }
1798
Craig Topperfb6b25b2014-03-15 04:29:04 +00001799 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001800 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001801 }
1802
1803 FormatStyle Style;
1804 Lexer &Lex;
1805 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001806 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001807 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001808 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001809
1810 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001811 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001812};
1813
Craig Topperaf35e852013-06-30 22:29:28 +00001814} // end anonymous namespace
1815
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001816tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1817 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001818 std::vector<CharSourceRange> Ranges) {
1819 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001820 return formatter.format();
1821}
1822
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001823tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1824 std::vector<tooling::Range> Ranges,
1825 StringRef FileName) {
1826 FileManager Files((FileSystemOptions()));
1827 DiagnosticsEngine Diagnostics(
1828 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1829 new DiagnosticOptions);
1830 SourceManager SourceMgr(Diagnostics, Files);
1831 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1832 const clang::FileEntry *Entry =
1833 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1834 SourceMgr.overrideFileContents(Entry, Buf);
1835 FileID ID =
1836 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001837 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1838 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001839 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1840 std::vector<CharSourceRange> CharRanges;
1841 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1842 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1843 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1844 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1845 }
1846 return reformat(Style, Lex, SourceMgr, CharRanges);
1847}
1848
Alexander Kornienko1e808872013-06-28 12:51:24 +00001849LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001850 LangOptions LangOpts;
1851 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001852 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001853 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001854 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001855 LangOpts.Bool = 1;
1856 LangOpts.ObjC1 = 1;
1857 LangOpts.ObjC2 = 1;
1858 return LangOpts;
1859}
1860
Edwin Vaned544aa72013-09-30 13:31:48 +00001861const char *StyleOptionHelpDescription =
1862 "Coding style, currently supports:\n"
1863 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1864 "Use -style=file to load style configuration from\n"
1865 ".clang-format file located in one of the parent\n"
1866 "directories of the source file (or current\n"
1867 "directory for stdin).\n"
1868 "Use -style=\"{key: value, ...}\" to set specific\n"
1869 "parameters, e.g.:\n"
1870 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1871
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001872static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001873 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001874 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001875 } else if (FileName.endswith_lower(".proto") ||
1876 FileName.endswith_lower(".protodevel")) {
1877 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001878 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001879 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001880}
1881
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001882FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1883 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001884 FormatStyle Style = getLLVMStyle();
1885 Style.Language = getLanguageByFileName(FileName);
1886 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001887 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1888 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001889 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001890 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001891
1892 if (StyleName.startswith("{")) {
1893 // Parse YAML/JSON style from the command line.
1894 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001895 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1896 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001897 }
1898 return Style;
1899 }
1900
1901 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001902 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001903 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1904 << " style\n";
1905 return Style;
1906 }
1907
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001908 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001909 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001910 SmallString<128> Path(FileName);
1911 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001912 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001913 Directory = llvm::sys::path::parent_path(Directory)) {
1914 if (!llvm::sys::fs::is_directory(Directory))
1915 continue;
1916 SmallString<128> ConfigFile(Directory);
1917
1918 llvm::sys::path::append(ConfigFile, ".clang-format");
1919 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1920 bool IsFile = false;
1921 // Ignore errors from is_regular_file: we only need to know if we can read
1922 // the file or not.
1923 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1924
1925 if (!IsFile) {
1926 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1927 ConfigFile = Directory;
1928 llvm::sys::path::append(ConfigFile, "_clang-format");
1929 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1930 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1931 }
1932
1933 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001934 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001935 if (llvm::error_code ec =
1936 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001937 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001938 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001939 }
1940 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001941 if (ec == llvm::errc::not_supported) {
1942 if (!UnsuitableConfigFiles.empty())
1943 UnsuitableConfigFiles.append(", ");
1944 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001945 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001946 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001947 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1948 << "\n";
1949 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001950 }
1951 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1952 return Style;
1953 }
1954 }
1955 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1956 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001957 if (!UnsuitableConfigFiles.empty()) {
1958 llvm::errs() << "Configuration file(s) do(es) not support "
1959 << getLanguageName(Style.Language) << ": "
1960 << UnsuitableConfigFiles << "\n";
1961 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001962 return Style;
1963}
1964
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001965} // namespace format
1966} // namespace clang