blob: 4a9c37e08419f97248c215da6d65950586348857 [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
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
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;
Nico Weber514ecc82014-02-02 20:50:45 +0000346 }
347
Daniel Jasperf7935112012-12-03 18:12:45 +0000348 return GoogleStyle;
349}
350
Nico Weber514ecc82014-02-02 20:50:45 +0000351FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
352 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000353 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000354 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000355 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000356 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000357 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000358 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000359 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000360 return ChromiumStyle;
361}
362
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000363FormatStyle getMozillaStyle() {
364 FormatStyle MozillaStyle = getLLVMStyle();
365 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000366 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000367 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
368 MozillaStyle.DerivePointerBinding = true;
369 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000370 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000371 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
372 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
373 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000374 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000375 return MozillaStyle;
376}
377
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000378FormatStyle getWebKitStyle() {
379 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000380 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000381 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000382 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000383 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000384 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000385 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000386 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000387 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000388 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000389 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000390 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000391 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000392 return Style;
393}
394
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000395FormatStyle getGNUStyle() {
396 FormatStyle Style = getLLVMStyle();
397 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000398 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000399 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000400 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000401 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000402 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000403 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000404 return Style;
405}
406
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000407bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
408 FormatStyle *Style) {
409 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000410 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000411 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000412 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000413 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000414 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000415 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000416 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000417 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000418 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000419 } else if (Name.equals_lower("gnu")) {
420 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000421 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000422 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000423 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000424
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000425 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000426 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000427}
428
429llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000430 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000431 FormatStyle::LanguageKind Language = Style->Language;
432 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000433 if (Text.trim().empty())
434 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000435
436 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000437 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000438 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
439 // values for the fields, keys for which are missing from the configuration.
440 // Mapping also uses the context to get the language to find the correct
441 // base style.
442 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000443 Input >> Styles;
444 if (Input.error())
445 return Input.error();
446
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000447 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000448 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000449 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000450 return llvm::make_error_code(llvm::errc::invalid_argument);
451 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000452 for (unsigned j = 0; j < i; ++j) {
453 if (Styles[i].Language == Styles[j].Language) {
454 DEBUG(llvm::dbgs()
455 << "Duplicate languages in the config file on positions " << j
456 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000457 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000458 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000459 }
460 }
461 // Look for a suitable configuration starting from the end, so we can
462 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000463 // configuration (which can only be at slot 0) after it.
464 for (int i = Styles.size() - 1; i >= 0; --i) {
465 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000466 Styles[i].Language == FormatStyle::LK_None) {
467 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000468 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000469 return llvm::make_error_code(llvm::errc::success);
470 }
471 }
472 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000473}
474
475std::string configurationAsText(const FormatStyle &Style) {
476 std::string Text;
477 llvm::raw_string_ostream Stream(Text);
478 llvm::yaml::Output Output(Stream);
479 // We use the same mapping method for input and output, so we need a non-const
480 // reference here.
481 FormatStyle NonConstStyle = Style;
482 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000483 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000484}
485
Craig Topperaf35e852013-06-30 22:29:28 +0000486namespace {
487
Daniel Jasperde0328a2013-08-16 11:20:30 +0000488class NoColumnLimitFormatter {
489public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000490 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000491
492 /// \brief Formats the line starting at \p State, simply keeping all of the
493 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000494 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000495 LineState State =
496 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000497 while (State.NextToken != NULL) {
498 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000499 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000500 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
501 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
502 }
503 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000504
Daniel Jasperde0328a2013-08-16 11:20:30 +0000505private:
506 ContinuationIndenter *Indenter;
507};
508
Daniel Jasper56f8b432013-11-06 23:12:09 +0000509class LineJoiner {
510public:
511 LineJoiner(const FormatStyle &Style) : Style(Style) {}
512
513 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
514 unsigned
515 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000516 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000517 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
518 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000519 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000520 if (TheLine->Last->Type == TT_LineComment)
521 return 0;
522
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000523 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
524 return 0;
525
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000526 unsigned Limit =
527 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000528 // If we already exceed the column limit, we set 'Limit' to 0. The different
529 // tryMerge..() functions can then decide whether to still do merging.
530 Limit = TheLine->Last->TotalLength > Limit
531 ? 0
532 : Limit - TheLine->Last->TotalLength;
533
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000534 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000535 return 0;
536
Daniel Jasperd74cf402014-04-08 12:46:38 +0000537 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
538 // If necessary, change to something smarter.
539 bool MergeShortFunctions =
540 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
541 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
542 TheLine->Level != 0);
543
Daniel Jasper234379f2013-12-24 13:31:25 +0000544 if (TheLine->Last->Type == TT_FunctionLBrace &&
545 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000546 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000547 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000548 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000549 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000550 ? tryMergeSimpleBlock(I, E, Limit)
551 : 0;
552 }
553 if (I[1]->First->Type == TT_FunctionLBrace &&
554 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000555 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000556 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
557 return 0;
558 Limit -= 2;
559
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000560 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000561 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000562 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
563 // If we managed to merge the block, count the function header, which is
564 // on a separate line.
565 if (MergedLines > 0)
566 ++MergedLines;
567 }
568 return MergedLines;
569 }
570 if (TheLine->First->is(tok::kw_if)) {
571 return Style.AllowShortIfStatementsOnASingleLine
572 ? tryMergeSimpleControlStatement(I, E, Limit)
573 : 0;
574 }
575 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
576 return Style.AllowShortLoopsOnASingleLine
577 ? tryMergeSimpleControlStatement(I, E, Limit)
578 : 0;
579 }
580 if (TheLine->InPPDirective &&
581 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000582 return tryMergeSimplePPDirective(I, E, Limit);
583 }
584 return 0;
585 }
586
587private:
588 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000589 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000590 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
591 unsigned Limit) {
592 if (Limit == 0)
593 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000594 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000595 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000596 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000597 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000598 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000599 return 0;
600 return 1;
601 }
602
603 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000604 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000605 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
606 if (Limit == 0)
607 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000608 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
609 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000610 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000611 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000612 if (I[1]->InPPDirective != (*I)->InPPDirective ||
613 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000614 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000615 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616 AnnotatedLine &Line = **I;
617 if (Line.Last->isNot(tok::r_paren))
618 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000619 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000620 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000621 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000622 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000623 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000624 return 0;
625 // Only inline simple if's (no nested if or else).
626 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000627 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000628 return 0;
629 return 1;
630 }
631
632 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000633 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000634 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
635 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000636 // First, check that the current line allows merging. This is the case if
637 // we're not in a control flow statement and the last token is an opening
638 // brace.
639 AnnotatedLine &Line = **I;
640 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
641 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper922349c2014-04-04 06:46:23 +0000642 tok::kw_for, tok::kw_case,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000643 // This gets rid of all ObjC @ keywords and methods.
644 tok::at, tok::minus, tok::plus))
645 return 0;
646
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000647 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000648 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
649 (Tok->getNextNonComment() == NULL ||
650 Tok->getNextNonComment()->is(tok::semi))) {
651 // We merge empty blocks even if the line exceeds the column limit.
652 Tok->SpacesRequiredBefore = 0;
653 Tok->CanBreakBefore = true;
654 return 1;
655 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
656 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000657 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000658 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000659 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000660
661 if (!nextTwoLinesFitInto(I, Limit))
662 return 0;
663
664 // Second, check that the next line does not contain any braces - if it
665 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000666 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000667 return 0;
668 do {
669 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
670 return 0;
671 Tok = Tok->Next;
672 } while (Tok != NULL);
673
674 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000675 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000676 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
677 Tok->MustBreakBefore)
678 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) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 }
702
Daniel Jasper234379f2013-12-24 13:31:25 +0000703 bool containsMustBreak(const AnnotatedLine *Line) {
704 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
705 if (Tok->MustBreakBefore)
706 return true;
707 }
708 return false;
709 }
710
Daniel Jasper56f8b432013-11-06 23:12:09 +0000711 const FormatStyle &Style;
712};
713
Daniel Jasperf7935112012-12-03 18:12:45 +0000714class UnwrappedLineFormatter {
715public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000716 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000717 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000718 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000719 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
720 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000721
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000723 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000724 // Try to look up already computed penalty in DryRun-mode.
725 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey{
726 &Lines, AdditionalIndent};
727 auto CacheIt = PenaltyCache.find(CacheKey);
728 if (DryRun && CacheIt != PenaltyCache.end())
729 return CacheIt->second;
730
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000731 assert(!Lines.empty());
732 unsigned Penalty = 0;
733 std::vector<int> IndentForLevel;
734 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
735 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000736 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
738 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000739 I != E; ++I) {
740 const AnnotatedLine &TheLine = **I;
741 const FormatToken *FirstTok = TheLine.First;
742 int Offset = getIndentOffset(*FirstTok);
743
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000744 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000745 unsigned Indent;
746 if (TheLine.InPPDirective) {
747 Indent = TheLine.Level * Style.IndentWidth;
748 } else {
749 while (IndentForLevel.size() <= TheLine.Level)
750 IndentForLevel.push_back(-1);
751 IndentForLevel.resize(TheLine.Level + 1);
752 Indent = getIndent(IndentForLevel, TheLine.Level);
753 }
754 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000755 if (static_cast<int>(Indent) + Offset >= 0)
756 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000757
758 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000759 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000760 if (MergedLines > 0 && Style.ColumnLimit == 0) {
761 // Disallow line merging if there is a break at the start of one of the
762 // input lines.
763 for (unsigned i = 0; i < MergedLines; ++i) {
764 if (I[i + 1]->First->NewlinesBefore > 0)
765 MergedLines = 0;
766 }
767 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000768 if (!DryRun) {
769 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000770 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000771 }
772 }
773 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000774
Daniel Jasper9c199562013-11-28 15:58:55 +0000775 bool FixIndentation =
776 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000777 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000778 if (PreviousLine && PreviousLine->Affected && !DryRun) {
779 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000780 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
781 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
782 /*IndentLevel=*/0, /*Spaces=*/0,
783 /*TargetColumn=*/0);
784 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000785 } else if (TheLine.Type != LT_Invalid &&
786 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000787 if (FirstTok->WhitespaceRange.isValid()) {
788 if (!DryRun)
789 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
790 Indent, TheLine.InPPDirective);
791 } else {
792 Indent = LevelIndent = FirstTok->OriginalColumn;
793 }
794
795 // If everything fits on a single line, just put it there.
796 unsigned ColumnLimit = Style.ColumnLimit;
797 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000798 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000799 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
800 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
801 }
802
803 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
804 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
805 while (State.NextToken != NULL)
806 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
807 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000808 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000809 NoColumnLimitFormatter Formatter(Indenter);
810 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000811 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000812 } else {
813 Penalty += format(TheLine, Indent, DryRun);
814 }
815
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000816 if (!TheLine.InPPDirective)
817 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000818 } else if (TheLine.ChildrenAffected) {
819 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000820 } else {
821 // Format the first token if necessary, and notify the WhitespaceManager
822 // about the unchanged whitespace.
823 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
824 if (Tok == TheLine.First &&
825 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
826 unsigned LevelIndent = Tok->OriginalColumn;
827 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000828 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000829 if ((PreviousLine && PreviousLine->Affected) ||
830 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000831 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
832 TheLine.InPPDirective);
833 } else {
834 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
835 }
836 }
837
838 if (static_cast<int>(LevelIndent) - Offset >= 0)
839 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000840 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000841 IndentForLevel[TheLine.Level] = LevelIndent;
842 } else if (!DryRun) {
843 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
844 }
845 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000846 }
847 if (!DryRun) {
848 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
849 Tok->Finalized = true;
850 }
851 }
852 PreviousLine = *I;
853 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000854 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000855 return Penalty;
856 }
857
858private:
859 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000860 ///
861 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000862 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
863 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000864 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000865
Daniel Jasperacc33662013-02-08 08:22:00 +0000866 // If the ObjC method declaration does not fit on a line, we should format
867 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000868 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000869 State.Stack.back().BreakBeforeParameter = true;
870
Daniel Jasper4b866272013-02-01 11:00:45 +0000871 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000872 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000873 }
874
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000875 /// \brief An edge in the solution space from \c Previous->State to \c State,
876 /// inserting a newline dependent on the \c NewLine.
877 struct StateNode {
878 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000879 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000880 LineState State;
881 bool NewLine;
882 StateNode *Previous;
883 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000884
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000885 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
886 ///
887 /// In case of equal penalties, we want to prefer states that were inserted
888 /// first. During state generation we make sure that we insert states first
889 /// that break the line as late as possible.
890 typedef std::pair<unsigned, unsigned> OrderedPenalty;
891
892 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
893 /// \c State has the given \c OrderedPenalty.
894 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
895
896 /// \brief The BFS queue type.
897 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
898 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000899
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000900 /// \brief Get the offset of the line relatively to the level.
901 ///
902 /// For example, 'public:' labels in classes are offset by 1 or 2
903 /// characters to the left from their level.
904 int getIndentOffset(const FormatToken &RootToken) {
905 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
906 return Style.AccessModifierOffset;
907 return 0;
908 }
909
910 /// \brief Add a new line and the required indent before the first Token
911 /// of the \c UnwrappedLine if there was no structural parsing error.
912 void formatFirstToken(FormatToken &RootToken,
913 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
914 unsigned Indent, bool InPPDirective) {
915 unsigned Newlines =
916 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
917 // Remove empty lines before "}" where applicable.
918 if (RootToken.is(tok::r_brace) &&
919 (!RootToken.Next ||
920 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
921 Newlines = std::min(Newlines, 1u);
922 if (Newlines == 0 && !RootToken.IsFirst)
923 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000924 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
925 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000926
Daniel Jasper11164bd2014-03-21 12:58:53 +0000927 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000928 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
929 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000930 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000931 Newlines = 1;
932
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000933 // Insert extra new line before access specifiers.
934 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
935 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
936 ++Newlines;
937
938 // Remove empty lines after access specifiers.
939 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
940 Newlines = std::min(1u, Newlines);
941
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000942 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
943 Indent, InPPDirective &&
944 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000945 }
946
947 /// \brief Get the indent of \p Level from \p IndentForLevel.
948 ///
949 /// \p IndentForLevel must contain the indent for the level \c l
950 /// at \p IndentForLevel[l], or a value < 0 if the indent for
951 /// that level is unknown.
952 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
953 if (IndentForLevel[Level] != -1)
954 return IndentForLevel[Level];
955 if (Level == 0)
956 return 0;
957 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
958 }
959
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000960 void join(AnnotatedLine &A, const AnnotatedLine &B) {
961 assert(!A.Last->Next);
962 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000963 if (B.Affected)
964 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000965 A.Last->Next = B.First;
966 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000967 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000968 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
969 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
970 Tok->TotalLength += LengthA;
971 A.Last = Tok;
972 }
973 }
974
975 unsigned getColumnLimit(bool InPPDirective) const {
976 // In preprocessor directives reserve two chars for trailing " \"
977 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
978 }
979
Daniel Jasper4b866272013-02-01 11:00:45 +0000980 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000982 /// This implements a variant of Dijkstra's algorithm on the graph that spans
983 /// the solution space (\c LineStates are the nodes). The algorithm tries to
984 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000985 /// to a state where all tokens are placed. Returns the penalty.
986 ///
987 /// If \p DryRun is \c false, directly applies the changes.
988 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000989 std::set<LineState> Seen;
990
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000991 // Increasing count of \c StateNode items we have created. This is used to
992 // create a deterministic order independent of the container.
993 unsigned Count = 0;
994 QueueType Queue;
995
Daniel Jasper4b866272013-02-01 11:00:45 +0000996 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000997 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000998 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
999 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1000 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001001
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001002 unsigned Penalty = 0;
1003
Daniel Jasper4b866272013-02-01 11:00:45 +00001004 // While not empty, take first element and follow edges.
1005 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001006 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001007 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001008 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001009 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001010 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001011 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001012 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001013
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001014 // Cut off the analysis of certain solutions if the analysis gets too
1015 // complex. See description of IgnoreStackForComparison.
1016 if (Count > 10000)
1017 Node->State.IgnoreStackForComparison = true;
1018
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001019 if (!Seen.insert(Node->State).second)
1020 // State already examined with lower penalty.
1021 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001022
Manuel Klimek71814b42013-10-11 21:25:45 +00001023 FormatDecision LastFormat = Node->State.NextToken->Decision;
1024 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001025 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001026 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001027 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001028 }
1029
Manuel Klimek71814b42013-10-11 21:25:45 +00001030 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001031 // We were unable to find a solution, do nothing.
1032 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001033 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001034 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001035 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001036
Daniel Jasper4b866272013-02-01 11:00:45 +00001037 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001038 if (!DryRun)
1039 reconstructPath(InitialState, Queue.top().second);
1040
Alexander Kornienko49149672013-05-10 11:56:10 +00001041 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1042 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001043
1044 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001045 }
1046
1047 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001048 std::deque<StateNode *> Path;
1049 // We do not need a break before the initial token.
1050 while (Current->Previous) {
1051 Path.push_front(Current);
1052 Current = Current->Previous;
1053 }
1054 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1055 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001056 unsigned Penalty = 0;
1057 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1058 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1059
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001060 DEBUG({
1061 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001062 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001063 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001064 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001065 }
1066 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001067 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001068 }
1069
Manuel Klimekaf491072013-02-13 10:54:19 +00001070 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001071 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001072 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001073 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001074 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001075 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001076 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001077 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001078 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001079 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001080
1081 StateNode *Node = new (Allocator.Allocate())
1082 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001083 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1084 return;
1085
Daniel Jasperde0328a2013-08-16 11:20:30 +00001086 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001087
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001088 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1089 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001090 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001091
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001092 /// \brief If the \p State's next token is an r_brace closing a nested block,
1093 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001094 ///
1095 /// Returns \c true if all children could be placed successfully and adapts
1096 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1097 /// creates changes using \c Whitespaces.
1098 ///
1099 /// The crucial idea here is that children always get formatted upon
1100 /// encountering the closing brace right after the nested block. Now, if we
1101 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1102 /// \c false), the entire block has to be kept on the same line (which is only
1103 /// possible if it fits on the line, only contains a single statement, etc.
1104 ///
1105 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1106 /// break after the "{", format all lines with correct indentation and the put
1107 /// the closing "}" on yet another new line.
1108 ///
1109 /// This enables us to keep the simple structure of the
1110 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1111 /// break or don't break.
1112 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1113 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001114 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001115 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1116 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1117 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001118 // The previous token does not open a block. Nothing to do. We don't
1119 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001120 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001121
1122 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001123 int AdditionalIndent = State.Stack.back().Indent -
1124 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001125 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1126 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127 return true;
1128 }
1129
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001130 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001131 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001132 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001133
Daniel Jasper21397a32014-04-09 12:21:48 +00001134 // Cannot merge into one line if this line ends on a comment.
1135 if (Previous.is(tok::comment))
1136 return false;
1137
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001138 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001139 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001140 return false;
1141
Daniel Jasper98583d52014-04-15 08:28:06 +00001142 // If the child line exceeds the column limit, we wouldn't want to merge it.
1143 // We add +2 for the trailing " }".
1144 if (Style.ColumnLimit > 0 &&
1145 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1146 Style.ColumnLimit)
1147 return false;
1148
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001149 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001150 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001151 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001152 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001153 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001154 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001155 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001156
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001157 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001158 return true;
1159 }
1160
Daniel Jasperde0328a2013-08-16 11:20:30 +00001161 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001162 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001163 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001164 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001165
1166 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001167
1168 // Cache to store the penalty of formatting a vector of AnnotatedLines
1169 // starting from a specific additional offset. Improves performance if there
1170 // are many nested blocks.
1171 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1172 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001173};
1174
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001175class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001176public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001177 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001178 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001179 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001180 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
Manuel Klimek68b03042014-04-14 09:14:11 +00001181 IdentTable(getFormattingLangOpts()), Encoding(Encoding),
1182 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001183 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001184
1185 for (const std::string& ForEachMacro : Style.ForEachMacros)
1186 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1187 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001188 }
1189
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001190 ArrayRef<FormatToken *> lex() {
1191 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001192 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001193 do {
1194 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001195 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001196 if (Tokens.back()->NewlinesBefore > 0)
1197 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001198 } while (Tokens.back()->Tok.isNot(tok::eof));
1199 return Tokens;
1200 }
1201
1202 IdentifierTable &getIdentTable() { return IdentTable; }
1203
1204private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001205 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001206 if (tryMerge_TMacro())
1207 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001208 if (tryMergeConflictMarkers())
1209 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001210
1211 if (Style.Language == FormatStyle::LK_JavaScript) {
1212 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1213 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1214 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1215 tok::greaterequal };
1216 // FIXME: We probably need to change token type to mimic operator with the
1217 // correct priority.
1218 if (tryMergeTokens(JSIdentity))
1219 return;
1220 if (tryMergeTokens(JSNotIdentity))
1221 return;
1222 if (tryMergeTokens(JSShiftEqual))
1223 return;
1224 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001225 }
1226
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001227 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1228 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001229 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001230
1231 SmallVectorImpl<FormatToken *>::const_iterator First =
1232 Tokens.end() - Kinds.size();
1233 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001234 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001235 unsigned AddLength = 0;
1236 for (unsigned i = 1; i < Kinds.size(); ++i) {
1237 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1238 First[i]->WhitespaceRange.getEnd())
1239 return false;
1240 AddLength += First[i]->TokenText.size();
1241 }
1242 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1243 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1244 First[0]->TokenText.size() + AddLength);
1245 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001246 return true;
1247 }
1248
1249 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001250 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001251 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001252 FormatToken *Last = Tokens.back();
1253 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001254 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001255
1256 FormatToken *String = Tokens[Tokens.size() - 2];
1257 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001258 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001259
1260 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001261 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001262
1263 FormatToken *Macro = Tokens[Tokens.size() - 4];
1264 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001265 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001266
1267 const char *Start = Macro->TokenText.data();
1268 const char *End = Last->TokenText.data() + Last->TokenText.size();
1269 String->TokenText = StringRef(Start, End - Start);
1270 String->IsFirst = Macro->IsFirst;
1271 String->LastNewlineOffset = Macro->LastNewlineOffset;
1272 String->WhitespaceRange = Macro->WhitespaceRange;
1273 String->OriginalColumn = Macro->OriginalColumn;
1274 String->ColumnWidth = encoding::columnWidthWithTabs(
1275 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1276
1277 Tokens.pop_back();
1278 Tokens.pop_back();
1279 Tokens.pop_back();
1280 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001281 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001282 }
1283
Manuel Klimek68b03042014-04-14 09:14:11 +00001284 bool tryMergeConflictMarkers() {
1285 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1286 return false;
1287
1288 // Conflict lines look like:
1289 // <marker> <text from the vcs>
1290 // For example:
1291 // >>>>>>> /file/in/file/system at revision 1234
1292 //
1293 // We merge all tokens in a line that starts with a conflict marker
1294 // into a single token with a special token type that the unwrapped line
1295 // parser will use to correctly rebuild the underlying code.
1296
1297 FileID ID;
1298 // Get the position of the first token in the line.
1299 unsigned FirstInLineOffset;
1300 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1301 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1302 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1303 // Calculate the offset of the start of the current line.
1304 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1305 if (LineOffset == StringRef::npos) {
1306 LineOffset = 0;
1307 } else {
1308 ++LineOffset;
1309 }
1310
1311 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1312 StringRef LineStart;
1313 if (FirstSpace == StringRef::npos) {
1314 LineStart = Buffer.substr(LineOffset);
1315 } else {
1316 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1317 }
1318
1319 TokenType Type = TT_Unknown;
1320 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1321 Type = TT_ConflictStart;
1322 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1323 LineStart == "====") {
1324 Type = TT_ConflictAlternative;
1325 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1326 Type = TT_ConflictEnd;
1327 }
1328
1329 if (Type != TT_Unknown) {
1330 FormatToken *Next = Tokens.back();
1331
1332 Tokens.resize(FirstInLineIndex + 1);
1333 // We do not need to build a complete token here, as we will skip it
1334 // during parsing anyway (as we must not touch whitespace around conflict
1335 // markers).
1336 Tokens.back()->Type = Type;
1337 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1338
1339 Tokens.push_back(Next);
1340 return true;
1341 }
1342
1343 return false;
1344 }
1345
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001346 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001347 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001348 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001349 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001350 Token Greater = FormatTok->Tok;
1351 FormatTok = new (Allocator.Allocate()) FormatToken;
1352 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001353 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001354 FormatTok->Tok.getLocation().getLocWithOffset(1);
1355 FormatTok->WhitespaceRange =
1356 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001357 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001358 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001359 GreaterStashed = false;
1360 return FormatTok;
1361 }
1362
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001363 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001364 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001365 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001366 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001367 FormatTok->IsFirst = IsFirstToken;
1368 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001369
1370 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001371 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001372 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001373 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1374 switch (FormatTok->TokenText[i]) {
1375 case '\n':
1376 ++FormatTok->NewlinesBefore;
1377 // FIXME: This is technically incorrect, as it could also
1378 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001379 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1380 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1381 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001382 FormatTok->HasUnescapedNewline = true;
1383 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1384 Column = 0;
1385 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001386 case '\r':
1387 case '\f':
1388 case '\v':
1389 Column = 0;
1390 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001391 case ' ':
1392 ++Column;
1393 break;
1394 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001395 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001396 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001397 case '\\':
1398 ++Column;
1399 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1400 FormatTok->TokenText[i + 1] != '\n'))
1401 FormatTok->Type = TT_ImplicitStringLiteral;
1402 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001403 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001404 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001405 ++Column;
1406 break;
1407 }
1408 }
1409
Daniel Jasper877615c2013-10-11 19:45:02 +00001410 if (FormatTok->Type == TT_ImplicitStringLiteral)
1411 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001412 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001413
Daniel Jasper8369aa52013-07-16 20:28:33 +00001414 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001415 }
Manuel Klimekef920692013-01-07 07:56:50 +00001416
Manuel Klimek1abf7892013-01-04 23:34:14 +00001417 // In case the token starts with escaped newlines, we want to
1418 // take them into account as whitespace - this pattern is quite frequent
1419 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001420 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001421 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1422 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001423 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001424 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001425 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001426 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001427 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001428
1429 FormatTok->WhitespaceRange = SourceRange(
1430 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1431
Manuel Klimek31c85922013-08-29 15:21:40 +00001432 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001433
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001434 TrailingWhitespace = 0;
1435 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001436 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001437 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001438 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001439 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001440 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001441 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001442 FormatTok->Tok.setIdentifierInfo(&Info);
1443 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001444 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001445 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001446 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001447 GreaterStashed = true;
1448 }
1449
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001450 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001451
Alexander Kornienko39856b72013-09-10 09:38:25 +00001452 StringRef Text = FormatTok->TokenText;
1453 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001454 if (FirstNewlinePos == StringRef::npos) {
1455 // FIXME: ColumnWidth actually depends on the start column, we need to
1456 // take this into account when the token is moved.
1457 FormatTok->ColumnWidth =
1458 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1459 Column += FormatTok->ColumnWidth;
1460 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001461 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001462 // FIXME: ColumnWidth actually depends on the start column, we need to
1463 // take this into account when the token is moved.
1464 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1465 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1466
Alexander Kornienko39856b72013-09-10 09:38:25 +00001467 // The last line of the token always starts in column 0.
1468 // Thus, the length can be precomputed even in the presence of tabs.
1469 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1470 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1471 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001472 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001473 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001474
Daniel Jaspere1e43192014-04-01 12:55:11 +00001475 FormatTok->IsForEachMacro =
1476 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1477 FormatTok->Tok.getIdentifierInfo());
1478
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001479 return FormatTok;
1480 }
1481
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001482 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001483 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001484 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001485 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001486 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001487 Lexer &Lex;
1488 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001489 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001490 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001491 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001492 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001493 // Index (in 'Tokens') of the last token that starts a new line.
1494 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001495 SmallVector<FormatToken *, 16> Tokens;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001496 SmallVector<IdentifierInfo*, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001497
Daniel Jasper8369aa52013-07-16 20:28:33 +00001498 void readRawToken(FormatToken &Tok) {
1499 Lex.LexFromRawLexer(Tok.Tok);
1500 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1501 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001502 // For formatting, treat unterminated string literals like normal string
1503 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001504 if (Tok.is(tok::unknown)) {
1505 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1506 Tok.Tok.setKind(tok::string_literal);
1507 Tok.IsUnterminatedLiteral = true;
1508 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1509 Tok.TokenText == "''") {
1510 Tok.Tok.setKind(tok::char_constant);
1511 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001512 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001513 }
1514};
1515
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001516static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1517 switch (Language) {
1518 case FormatStyle::LK_Cpp:
1519 return "C++";
1520 case FormatStyle::LK_JavaScript:
1521 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001522 case FormatStyle::LK_Proto:
1523 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001524 default:
1525 return "Unknown";
1526 }
1527}
1528
Daniel Jasperf7935112012-12-03 18:12:45 +00001529class Formatter : public UnwrappedLineConsumer {
1530public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001531 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001532 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001533 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001534 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001535 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001536 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001537 DEBUG(llvm::dbgs() << "File encoding: "
1538 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1539 : "unknown")
1540 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001541 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1542 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001543 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001544
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001545 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001546 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001547 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001548
1549 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001550 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001551 assert(UnwrappedLines.rbegin()->empty());
1552 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1553 ++Run) {
1554 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1555 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1556 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1557 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1558 }
1559 tooling::Replacements RunResult =
1560 format(AnnotatedLines, StructuralError, Tokens);
1561 DEBUG({
1562 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1563 for (tooling::Replacements::iterator I = RunResult.begin(),
1564 E = RunResult.end();
1565 I != E; ++I) {
1566 llvm::dbgs() << I->toString() << "\n";
1567 }
1568 });
1569 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1570 delete AnnotatedLines[i];
1571 }
1572 Result.insert(RunResult.begin(), RunResult.end());
1573 Whitespaces.reset();
1574 }
1575 return Result;
1576 }
1577
1578 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1579 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001580 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001581 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001582 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001583 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001584 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001585 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001586 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001587 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001588 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001589
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001590 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001591 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1592 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001593 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001594 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001595 return Whitespaces.generateReplacements();
1596 }
1597
1598private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001599 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001600 // Returns \c true if at least one line between I and E or one of their
1601 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001602 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1603 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1604 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001605 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001606 while (I != E) {
1607 AnnotatedLine *Line = *I;
1608 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1609
1610 // If a line is part of a preprocessor directive, it needs to be formatted
1611 // if any token within the directive is affected.
1612 if (Line->InPPDirective) {
1613 FormatToken *Last = Line->Last;
1614 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1615 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1616 Last = (*PPEnd)->Last;
1617 ++PPEnd;
1618 }
1619
1620 if (affectsTokenRange(*Line->First, *Last,
1621 /*IncludeLeadingNewlines=*/false)) {
1622 SomeLineAffected = true;
1623 markAllAsAffected(I, PPEnd);
1624 }
1625 I = PPEnd;
1626 continue;
1627 }
1628
Daniel Jasper38c82402013-11-29 09:27:43 +00001629 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001630 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001631
Daniel Jasper38c82402013-11-29 09:27:43 +00001632 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001633 ++I;
1634 }
1635 return SomeLineAffected;
1636 }
1637
Daniel Jasper9c199562013-11-28 15:58:55 +00001638 // Determines whether 'Line' is affected by the SourceRanges given as input.
1639 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001640 bool nonPPLineAffected(AnnotatedLine *Line,
1641 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001642 bool SomeLineAffected = false;
1643 Line->ChildrenAffected =
1644 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1645 if (Line->ChildrenAffected)
1646 SomeLineAffected = true;
1647
1648 // Stores whether one of the line's tokens is directly affected.
1649 bool SomeTokenAffected = false;
1650 // Stores whether we need to look at the leading newlines of the next token
1651 // in order to determine whether it was affected.
1652 bool IncludeLeadingNewlines = false;
1653
1654 // Stores whether the first child line of any of this line's tokens is
1655 // affected.
1656 bool SomeFirstChildAffected = false;
1657
1658 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1659 // Determine whether 'Tok' was affected.
1660 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1661 SomeTokenAffected = true;
1662
1663 // Determine whether the first child of 'Tok' was affected.
1664 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1665 SomeFirstChildAffected = true;
1666
1667 IncludeLeadingNewlines = Tok->Children.empty();
1668 }
1669
1670 // Was this line moved, i.e. has it previously been on the same line as an
1671 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001672 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1673 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001674
Daniel Jasper38c82402013-11-29 09:27:43 +00001675 bool IsContinuedComment = Line->First->is(tok::comment) &&
1676 Line->First->Next == NULL &&
1677 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001678 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001679 PreviousLine->Last->is(tok::comment);
1680
1681 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1682 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001683 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001684 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001685 }
1686 return SomeLineAffected;
1687 }
1688
Daniel Jasper5500f612013-11-25 11:08:59 +00001689 // Marks all lines between I and E as well as all their children as affected.
1690 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1691 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1692 while (I != E) {
1693 (*I)->Affected = true;
1694 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1695 ++I;
1696 }
1697 }
1698
1699 // Returns true if the range from 'First' to 'Last' intersects with one of the
1700 // input ranges.
1701 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1702 bool IncludeLeadingNewlines) {
1703 SourceLocation Start = First.WhitespaceRange.getBegin();
1704 if (!IncludeLeadingNewlines)
1705 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001706 SourceLocation End = Last.getStartOfNonWhitespace();
1707 if (Last.TokenText.size() > 0)
1708 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001709 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1710 return affectsCharSourceRange(Range);
1711 }
1712
1713 // Returns true if one of the input ranges intersect the leading empty lines
1714 // before 'Tok'.
1715 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1716 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1717 Tok.WhitespaceRange.getBegin(),
1718 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1719 return affectsCharSourceRange(EmptyLineRange);
1720 }
1721
1722 // Returns true if 'Range' intersects with one of the input ranges.
1723 bool affectsCharSourceRange(const CharSourceRange &Range) {
1724 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1725 E = Ranges.end();
1726 I != E; ++I) {
1727 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1728 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1729 return true;
1730 }
1731 return false;
1732 }
1733
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001734 static bool inputUsesCRLF(StringRef Text) {
1735 return Text.count('\r') * 2 > Text.count('\n');
1736 }
1737
Manuel Klimek71814b42013-10-11 21:25:45 +00001738 void
1739 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001740 unsigned CountBoundToVariable = 0;
1741 unsigned CountBoundToType = 0;
1742 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001743 bool HasBinPackedFunction = false;
1744 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001745 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001746 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001747 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001748 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001749 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001750 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001751 bool SpacesBefore =
1752 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1753 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1754 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001755 if (SpacesBefore && !SpacesAfter)
1756 ++CountBoundToVariable;
1757 else if (!SpacesBefore && SpacesAfter)
1758 ++CountBoundToType;
1759 }
1760
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001761 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1762 if (Tok->is(tok::coloncolon) &&
1763 Tok->Previous->Type == TT_TemplateOpener)
1764 HasCpp03IncompatibleFormat = true;
1765 if (Tok->Type == TT_TemplateCloser &&
1766 Tok->Previous->Type == TT_TemplateCloser)
1767 HasCpp03IncompatibleFormat = true;
1768 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001769
1770 if (Tok->PackingKind == PPK_BinPacked)
1771 HasBinPackedFunction = true;
1772 if (Tok->PackingKind == PPK_OnePerLine)
1773 HasOnePerLineFunction = true;
1774
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001775 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001776 }
1777 }
1778 if (Style.DerivePointerBinding) {
1779 if (CountBoundToType > CountBoundToVariable)
1780 Style.PointerBindsToType = true;
1781 else if (CountBoundToType < CountBoundToVariable)
1782 Style.PointerBindsToType = false;
1783 }
1784 if (Style.Standard == FormatStyle::LS_Auto) {
1785 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1786 : FormatStyle::LS_Cpp03;
1787 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001788 BinPackInconclusiveFunctions =
1789 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001790 }
1791
Craig Topperfb6b25b2014-03-15 04:29:04 +00001792 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001793 assert(!UnwrappedLines.empty());
1794 UnwrappedLines.back().push_back(TheLine);
1795 }
1796
Craig Topperfb6b25b2014-03-15 04:29:04 +00001797 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001798 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001799 }
1800
1801 FormatStyle Style;
1802 Lexer &Lex;
1803 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001804 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001805 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001806 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001807
1808 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001809 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001810};
1811
Craig Topperaf35e852013-06-30 22:29:28 +00001812} // end anonymous namespace
1813
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001814tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1815 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001816 std::vector<CharSourceRange> Ranges) {
1817 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001818 return formatter.format();
1819}
1820
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001821tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1822 std::vector<tooling::Range> Ranges,
1823 StringRef FileName) {
1824 FileManager Files((FileSystemOptions()));
1825 DiagnosticsEngine Diagnostics(
1826 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1827 new DiagnosticOptions);
1828 SourceManager SourceMgr(Diagnostics, Files);
1829 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1830 const clang::FileEntry *Entry =
1831 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1832 SourceMgr.overrideFileContents(Entry, Buf);
1833 FileID ID =
1834 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001835 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1836 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001837 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1838 std::vector<CharSourceRange> CharRanges;
1839 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1840 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1841 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1842 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1843 }
1844 return reformat(Style, Lex, SourceMgr, CharRanges);
1845}
1846
Alexander Kornienko1e808872013-06-28 12:51:24 +00001847LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001848 LangOptions LangOpts;
1849 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001850 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001851 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001852 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001853 LangOpts.Bool = 1;
1854 LangOpts.ObjC1 = 1;
1855 LangOpts.ObjC2 = 1;
1856 return LangOpts;
1857}
1858
Edwin Vaned544aa72013-09-30 13:31:48 +00001859const char *StyleOptionHelpDescription =
1860 "Coding style, currently supports:\n"
1861 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1862 "Use -style=file to load style configuration from\n"
1863 ".clang-format file located in one of the parent\n"
1864 "directories of the source file (or current\n"
1865 "directory for stdin).\n"
1866 "Use -style=\"{key: value, ...}\" to set specific\n"
1867 "parameters, e.g.:\n"
1868 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1869
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001870static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001871 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001872 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001873 } else if (FileName.endswith_lower(".proto") ||
1874 FileName.endswith_lower(".protodevel")) {
1875 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001876 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001877 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001878}
1879
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001880FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1881 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001882 FormatStyle Style = getLLVMStyle();
1883 Style.Language = getLanguageByFileName(FileName);
1884 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001885 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1886 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001887 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001888 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001889
1890 if (StyleName.startswith("{")) {
1891 // Parse YAML/JSON style from the command line.
1892 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001893 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1894 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001895 }
1896 return Style;
1897 }
1898
1899 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001900 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001901 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1902 << " style\n";
1903 return Style;
1904 }
1905
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001906 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001907 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001908 SmallString<128> Path(FileName);
1909 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001910 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001911 Directory = llvm::sys::path::parent_path(Directory)) {
1912 if (!llvm::sys::fs::is_directory(Directory))
1913 continue;
1914 SmallString<128> ConfigFile(Directory);
1915
1916 llvm::sys::path::append(ConfigFile, ".clang-format");
1917 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1918 bool IsFile = false;
1919 // Ignore errors from is_regular_file: we only need to know if we can read
1920 // the file or not.
1921 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1922
1923 if (!IsFile) {
1924 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1925 ConfigFile = Directory;
1926 llvm::sys::path::append(ConfigFile, "_clang-format");
1927 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1928 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1929 }
1930
1931 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001932 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001933 if (llvm::error_code ec =
1934 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001935 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001936 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001937 }
1938 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001939 if (ec == llvm::errc::not_supported) {
1940 if (!UnsuitableConfigFiles.empty())
1941 UnsuitableConfigFiles.append(", ");
1942 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001943 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001944 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001945 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1946 << "\n";
1947 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001948 }
1949 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1950 return Style;
1951 }
1952 }
1953 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1954 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001955 if (!UnsuitableConfigFiles.empty()) {
1956 llvm::errs() << "Configuration file(s) do(es) not support "
1957 << getLanguageName(Style.Language) << ": "
1958 << UnsuitableConfigFiles << "\n";
1959 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001960 return Style;
1961}
1962
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001963} // namespace format
1964} // namespace clang