blob: 740adb2b1263acb29b9f194335b19fba8e75c749 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000044 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000046 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 }
48};
49
50template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57 }
58};
59
60template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63 IO.enumCase(Value, "false", FormatStyle::UT_Never);
64 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65 IO.enumCase(Value, "true", FormatStyle::UT_Always);
66 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67 }
68};
69
Daniel Jasperd74cf402014-04-08 12:46:38 +000070template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72 IO.enumCase(Value, "None", FormatStyle::SFS_None);
73 IO.enumCase(Value, "false", FormatStyle::SFS_None);
74 IO.enumCase(Value, "All", FormatStyle::SFS_All);
75 IO.enumCase(Value, "true", FormatStyle::SFS_All);
76 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
77 }
78};
79
Daniel Jasperac043c92014-09-15 11:11:00 +000080template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
81 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
82 IO.enumCase(Value, "All", FormatStyle::BOS_All);
83 IO.enumCase(Value, "true", FormatStyle::BOS_All);
84 IO.enumCase(Value, "None", FormatStyle::BOS_None);
85 IO.enumCase(Value, "false", FormatStyle::BOS_None);
86 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
87 }
88};
89
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
91 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
92 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
93 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
94 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
95 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000096 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000097 }
98};
99
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000101struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000102 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103 FormatStyle::NamespaceIndentationKind &Value) {
104 IO.enumCase(Value, "None", FormatStyle::NI_None);
105 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
106 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000107 }
108};
109
110template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000111struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
112 static void enumeration(IO &IO,
113 FormatStyle::PointerAlignmentStyle &Value) {
114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Alp Toker958027b2014-07-14 19:42:55 +0000118 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000126 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000129 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000132
133 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000136 }
137};
138
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
143
Alexander Kornienko49149672013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000145 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000146 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000160 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000168 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000169 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
173 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000174 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000175 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
176 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000177 IO.mapOptional("AllowShortBlocksOnASingleLine",
178 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000179 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
180 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000181 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
182 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000183 IO.mapOptional("AllowShortLoopsOnASingleLine",
184 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000185 IO.mapOptional("AllowShortFunctionsOnASingleLine",
186 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000187 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
188 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000189 IO.mapOptional("AlwaysBreakTemplateDeclarations",
190 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000191 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
192 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000193 IO.mapOptional("BreakBeforeBinaryOperators",
194 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000195 IO.mapOptional("BreakBeforeTernaryOperators",
196 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000197 IO.mapOptional("BreakConstructorInitializersBeforeComma",
198 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000199 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000200 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
202 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
203 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000204 IO.mapOptional("ConstructorInitializerIndentWidth",
205 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000206 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000207 IO.mapOptional("ExperimentalAutoDetectBinPacking",
208 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000209 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000210 IO.mapOptional("IndentWrappedFunctionNames",
211 Style.IndentWrappedFunctionNames);
212 IO.mapOptional("IndentFunctionDeclarationAfterType",
213 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000214 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000215 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
216 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000217 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000218 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000219 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000220 IO.mapOptional("ObjCSpaceBeforeProtocolList",
221 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000222 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
223 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000224 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
225 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000226 IO.mapOptional("PenaltyBreakFirstLessLess",
227 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000228 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
229 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
230 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000231 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000232 IO.mapOptional("SpacesBeforeTrailingComments",
233 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000234 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000236 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000237 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000238 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000239 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000240 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000241 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000242 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000243 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000244 IO.mapOptional("SpacesInCStyleCastParentheses",
245 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000246 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000247 IO.mapOptional("SpacesInContainerLiterals",
248 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000249 IO.mapOptional("SpaceBeforeAssignmentOperators",
250 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000251 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000252 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000253 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000254
255 // For backward compatibility.
256 if (!IO.outputting()) {
257 IO.mapOptional("SpaceAfterControlStatementKeyword",
258 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000259 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
260 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000261 }
262 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000263 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000264 }
265};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000266
267// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000268// IO.getContext() should contain a pointer to the FormatStyle structure, that
269// will be used to get default values for missing keys.
270// If the first element has no Language specified, it will be treated as the
271// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000272template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000273 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
274 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000275 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000276 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000277 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000278 if (Index >= Seq.size()) {
279 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000280 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000281 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000282 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000283 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000284 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000285 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000286 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000287 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000288 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000289 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000290 }
291};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000292}
293}
294
Daniel Jasperf7935112012-12-03 18:12:45 +0000295namespace clang {
296namespace format {
297
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000298const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000299 static ParseErrorCategory C;
300 return C;
301}
302std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000303 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000304}
305
306const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
307 return "clang-format.parse_error";
308}
309
310std::string ParseErrorCategory::message(int EV) const {
311 switch (static_cast<ParseError>(EV)) {
312 case ParseError::Success:
313 return "Success";
314 case ParseError::Error:
315 return "Invalid argument";
316 case ParseError::Unsuitable:
317 return "Unsuitable";
318 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000319 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000320}
321
Daniel Jasperf7935112012-12-03 18:12:45 +0000322FormatStyle getLLVMStyle() {
323 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000324 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000325 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000326 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000327 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000328 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000329 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000330 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000331 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000332 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000333 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000334 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000335 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000336 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000337 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000338 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000339 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000340 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000341 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
342 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000343 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000344 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000345 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000346 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000347 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000348 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000349 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000350 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000351 LLVMStyle.ForEachMacros.push_back("foreach");
352 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
353 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000354 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000355 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000356 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000357 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000358 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000359 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000360 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000361 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000362 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000363 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000364 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000365 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000366 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000367 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000368 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000369 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000370 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000371 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000372 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000373 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000374 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000375 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000376 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000377
Daniel Jasper19a541e2013-12-19 16:45:34 +0000378 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000379 LLVMStyle.PenaltyBreakFirstLessLess = 120;
380 LLVMStyle.PenaltyBreakString = 1000;
381 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000382 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000383 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000384
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000385 LLVMStyle.DisableFormat = false;
386
Daniel Jasperf7935112012-12-03 18:12:45 +0000387 return LLVMStyle;
388}
389
Nico Weber514ecc82014-02-02 20:50:45 +0000390FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000391 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000392 GoogleStyle.Language = Language;
393
Daniel Jasperf7935112012-12-03 18:12:45 +0000394 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000395 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000396 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000397 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000398 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000399 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000400 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000401 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000402 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000403 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000404 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000405 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000406 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000407 GoogleStyle.SpacesBeforeTrailingComments = 2;
408 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000409
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000410 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000411 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000412
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000413 if (Language == FormatStyle::LK_Java) {
Daniel Jasperb89fbe62014-10-28 16:15:52 +0000414 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000415 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
416 GoogleStyle.ColumnLimit = 100;
417 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000418 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000419 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000420 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000421 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000422 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000423 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Nico Weber514ecc82014-02-02 20:50:45 +0000424 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000425 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000426 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000427 }
428
Daniel Jasperf7935112012-12-03 18:12:45 +0000429 return GoogleStyle;
430}
431
Nico Weber514ecc82014-02-02 20:50:45 +0000432FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
433 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000434 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000435 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000436 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000437 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000438 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000439 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000440 return ChromiumStyle;
441}
442
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000443FormatStyle getMozillaStyle() {
444 FormatStyle MozillaStyle = getLLVMStyle();
445 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000446 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000447 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000448 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000449 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000450 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000451 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
452 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000453 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000454 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000455 return MozillaStyle;
456}
457
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000458FormatStyle getWebKitStyle() {
459 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000460 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000461 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000462 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000463 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000464 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000465 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000466 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000467 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000468 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000469 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000470 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000471 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000472 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000473 return Style;
474}
475
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000476FormatStyle getGNUStyle() {
477 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000478 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000479 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000480 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000481 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000482 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000483 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000484 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000485 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000486 return Style;
487}
488
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000489FormatStyle getNoStyle() {
490 FormatStyle NoStyle = getLLVMStyle();
491 NoStyle.DisableFormat = true;
492 return NoStyle;
493}
494
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000495bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
496 FormatStyle *Style) {
497 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000498 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000499 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000500 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000501 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000502 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000503 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000504 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000505 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000506 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000507 } else if (Name.equals_lower("gnu")) {
508 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000509 } else if (Name.equals_lower("none")) {
510 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000511 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000512 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000513 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000514
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000516 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000517}
518
Rafael Espindolac0809172014-06-12 14:02:15 +0000519std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000520 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 FormatStyle::LanguageKind Language = Style->Language;
522 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000523 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000524 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000525
526 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000527 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000528 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
529 // values for the fields, keys for which are missing from the configuration.
530 // Mapping also uses the context to get the language to find the correct
531 // base style.
532 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000533 Input >> Styles;
534 if (Input.error())
535 return Input.error();
536
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000537 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000538 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000539 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000540 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000541 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 for (unsigned j = 0; j < i; ++j) {
543 if (Styles[i].Language == Styles[j].Language) {
544 DEBUG(llvm::dbgs()
545 << "Duplicate languages in the config file on positions " << j
546 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000547 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000549 }
550 }
551 // Look for a suitable configuration starting from the end, so we can
552 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000553 // configuration (which can only be at slot 0) after it.
554 for (int i = Styles.size() - 1; i >= 0; --i) {
555 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000556 Styles[i].Language == FormatStyle::LK_None) {
557 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000559 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000560 }
561 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000562 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000563}
564
565std::string configurationAsText(const FormatStyle &Style) {
566 std::string Text;
567 llvm::raw_string_ostream Stream(Text);
568 llvm::yaml::Output Output(Stream);
569 // We use the same mapping method for input and output, so we need a non-const
570 // reference here.
571 FormatStyle NonConstStyle = Style;
572 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000573 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000574}
575
Craig Topperaf35e852013-06-30 22:29:28 +0000576namespace {
577
Nico Weber34272652014-11-13 16:25:37 +0000578bool startsExternCBlock(const AnnotatedLine &Line) {
579 const FormatToken *Next = Line.First->getNextNonComment();
580 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
581 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
582 NextNext && NextNext->is(tok::l_brace);
583}
584
Daniel Jasperde0328a2013-08-16 11:20:30 +0000585class NoColumnLimitFormatter {
586public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000587 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000588
589 /// \brief Formats the line starting at \p State, simply keeping all of the
590 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000591 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000592 LineState State =
593 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000594 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000595 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000596 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000597 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
598 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
599 }
600 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000601
Daniel Jasperde0328a2013-08-16 11:20:30 +0000602private:
603 ContinuationIndenter *Indenter;
604};
605
Daniel Jasper56f8b432013-11-06 23:12:09 +0000606class LineJoiner {
607public:
608 LineJoiner(const FormatStyle &Style) : Style(Style) {}
609
610 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
611 unsigned
612 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000613 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000614 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
615 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000616 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000617 if (TheLine->Last->Type == TT_LineComment)
618 return 0;
619
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000620 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
621 return 0;
622
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000623 unsigned Limit =
624 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000625 // If we already exceed the column limit, we set 'Limit' to 0. The different
626 // tryMerge..() functions can then decide whether to still do merging.
627 Limit = TheLine->Last->TotalLength > Limit
628 ? 0
629 : Limit - TheLine->Last->TotalLength;
630
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000631 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000632 return 0;
633
Daniel Jasperd74cf402014-04-08 12:46:38 +0000634 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
635 // If necessary, change to something smarter.
636 bool MergeShortFunctions =
637 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
638 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
639 TheLine->Level != 0);
640
Daniel Jasper234379f2013-12-24 13:31:25 +0000641 if (TheLine->Last->Type == TT_FunctionLBrace &&
642 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000643 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000644 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000645 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000646 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000647 ? tryMergeSimpleBlock(I, E, Limit)
648 : 0;
649 }
650 if (I[1]->First->Type == TT_FunctionLBrace &&
651 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000652 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000653 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
654 return 0;
655 Limit -= 2;
656
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000657 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000658 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000659 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
660 // If we managed to merge the block, count the function header, which is
661 // on a separate line.
662 if (MergedLines > 0)
663 ++MergedLines;
664 }
665 return MergedLines;
666 }
667 if (TheLine->First->is(tok::kw_if)) {
668 return Style.AllowShortIfStatementsOnASingleLine
669 ? tryMergeSimpleControlStatement(I, E, Limit)
670 : 0;
671 }
672 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
673 return Style.AllowShortLoopsOnASingleLine
674 ? tryMergeSimpleControlStatement(I, E, Limit)
675 : 0;
676 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000677 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
678 return Style.AllowShortCaseLabelsOnASingleLine
679 ? tryMergeShortCaseLabels(I, E, Limit)
680 : 0;
681 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000682 if (TheLine->InPPDirective &&
683 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000684 return tryMergeSimplePPDirective(I, E, Limit);
685 }
686 return 0;
687 }
688
689private:
690 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000691 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000692 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
693 unsigned Limit) {
694 if (Limit == 0)
695 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000696 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000698 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000699 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 return 0;
702 return 1;
703 }
704
705 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000706 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000707 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
708 if (Limit == 0)
709 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000710 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
711 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000712 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000713 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000714 if (I[1]->InPPDirective != (*I)->InPPDirective ||
715 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000716 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000717 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000718 AnnotatedLine &Line = **I;
719 if (Line.Last->isNot(tok::r_paren))
720 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000721 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000723 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000724 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000725 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000726 return 0;
727 // Only inline simple if's (no nested if or else).
728 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000729 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000730 return 0;
731 return 1;
732 }
733
Daniel Jasperb87899b2014-09-10 13:11:45 +0000734 unsigned tryMergeShortCaseLabels(
735 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
736 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
737 if (Limit == 0 || I + 1 == E ||
738 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
739 return 0;
740 unsigned NumStmts = 0;
741 unsigned Length = 0;
742 for (; NumStmts < 3; ++NumStmts) {
743 if (I + 1 + NumStmts == E)
744 break;
745 const AnnotatedLine *Line = I[1 + NumStmts];
746 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
747 break;
748 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
749 tok::kw_while))
750 return 0;
751 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
752 }
753 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
754 return 0;
755 return NumStmts;
756 }
757
Daniel Jasper56f8b432013-11-06 23:12:09 +0000758 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000759 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000760 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
761 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000762 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000763
764 // Don't merge ObjC @ keywords and methods.
765 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000766 return 0;
767
Daniel Jasper17605d32014-05-14 09:33:35 +0000768 // Check that the current line allows merging. This depends on whether we
769 // are in a control flow statements as well as several style flags.
770 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
771 return 0;
772 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
773 tok::kw_catch, tok::kw_for, tok::r_brace)) {
774 if (!Style.AllowShortBlocksOnASingleLine)
775 return 0;
776 if (!Style.AllowShortIfStatementsOnASingleLine &&
777 Line.First->is(tok::kw_if))
778 return 0;
779 if (!Style.AllowShortLoopsOnASingleLine &&
780 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
781 return 0;
782 // FIXME: Consider an option to allow short exception handling clauses on
783 // a single line.
784 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
785 return 0;
786 }
787
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000788 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000789 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000790 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000791 Tok->getNextNonComment()->is(tok::semi))) {
792 // We merge empty blocks even if the line exceeds the column limit.
793 Tok->SpacesRequiredBefore = 0;
794 Tok->CanBreakBefore = true;
795 return 1;
Nico Weber34272652014-11-13 16:25:37 +0000796 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
797 !startsExternCBlock(Line)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000798 // We don't merge short records.
799 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
800 return 0;
801
Daniel Jasper56f8b432013-11-06 23:12:09 +0000802 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000803 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000804 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000805 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000806
807 if (!nextTwoLinesFitInto(I, Limit))
808 return 0;
809
810 // Second, check that the next line does not contain any braces - if it
811 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000812 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000813 return 0;
814 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000815 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000816 return 0;
817 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000818 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000819
Daniel Jasper79dffb42014-05-07 09:48:30 +0000820 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000821 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000822 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000823 return 0;
824
825 return 2;
826 }
827 return 0;
828 }
829
Daniel Jasper64989962014-02-07 13:45:27 +0000830 /// Returns the modified column limit for \p I if it is inside a macro and
831 /// needs a trailing '\'.
832 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000833 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000834 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
835 unsigned Limit) {
836 if (I[0]->InPPDirective && I + 1 != E &&
837 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
838 return Limit < 2 ? 0 : Limit - 2;
839 }
840 return Limit;
841 }
842
Daniel Jasper56f8b432013-11-06 23:12:09 +0000843 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
844 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000845 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
846 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000847 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000848 }
849
Daniel Jasper234379f2013-12-24 13:31:25 +0000850 bool containsMustBreak(const AnnotatedLine *Line) {
851 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
852 if (Tok->MustBreakBefore)
853 return true;
854 }
855 return false;
856 }
857
Daniel Jasper56f8b432013-11-06 23:12:09 +0000858 const FormatStyle &Style;
859};
860
Daniel Jasperf7935112012-12-03 18:12:45 +0000861class UnwrappedLineFormatter {
862public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000863 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000864 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000865 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000866 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
867 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000868
Daniel Jasper56f8b432013-11-06 23:12:09 +0000869 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000870 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000871 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000872 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
873 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000874 auto CacheIt = PenaltyCache.find(CacheKey);
875 if (DryRun && CacheIt != PenaltyCache.end())
876 return CacheIt->second;
877
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000878 assert(!Lines.empty());
879 unsigned Penalty = 0;
880 std::vector<int> IndentForLevel;
881 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
882 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000883 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000884 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
885 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000886 I != E; ++I) {
887 const AnnotatedLine &TheLine = **I;
888 const FormatToken *FirstTok = TheLine.First;
889 int Offset = getIndentOffset(*FirstTok);
890
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000891 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000892 unsigned Indent;
893 if (TheLine.InPPDirective) {
894 Indent = TheLine.Level * Style.IndentWidth;
895 } else {
896 while (IndentForLevel.size() <= TheLine.Level)
897 IndentForLevel.push_back(-1);
898 IndentForLevel.resize(TheLine.Level + 1);
899 Indent = getIndent(IndentForLevel, TheLine.Level);
900 }
901 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000902 if (static_cast<int>(Indent) + Offset >= 0)
903 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000904
905 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000906 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000907 if (MergedLines > 0 && Style.ColumnLimit == 0) {
908 // Disallow line merging if there is a break at the start of one of the
909 // input lines.
910 for (unsigned i = 0; i < MergedLines; ++i) {
911 if (I[i + 1]->First->NewlinesBefore > 0)
912 MergedLines = 0;
913 }
914 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000915 if (!DryRun) {
916 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000917 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000918 }
919 }
920 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000921
Daniel Jasper9c199562013-11-28 15:58:55 +0000922 bool FixIndentation =
923 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000924 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000925 if (PreviousLine && PreviousLine->Affected && !DryRun) {
926 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000927 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
928 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
929 /*IndentLevel=*/0, /*Spaces=*/0,
930 /*TargetColumn=*/0);
931 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000932 } else if (TheLine.Type != LT_Invalid &&
933 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000934 if (FirstTok->WhitespaceRange.isValid()) {
935 if (!DryRun)
936 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
937 Indent, TheLine.InPPDirective);
938 } else {
939 Indent = LevelIndent = FirstTok->OriginalColumn;
940 }
941
942 // If everything fits on a single line, just put it there.
943 unsigned ColumnLimit = Style.ColumnLimit;
944 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000945 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000946 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
947 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
948 }
949
950 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
951 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000952 while (State.NextToken) {
953 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000954 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000955 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000956 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000957 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000958 NoColumnLimitFormatter Formatter(Indenter);
959 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000960 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000961 } else {
962 Penalty += format(TheLine, Indent, DryRun);
963 }
964
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000965 if (!TheLine.InPPDirective)
966 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000967 } else if (TheLine.ChildrenAffected) {
968 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000969 } else {
970 // Format the first token if necessary, and notify the WhitespaceManager
971 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000972 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000973 if (Tok == TheLine.First &&
974 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
975 unsigned LevelIndent = Tok->OriginalColumn;
976 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000977 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000978 if ((PreviousLine && PreviousLine->Affected) ||
979 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000980 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
981 TheLine.InPPDirective);
982 } else {
983 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
984 }
985 }
986
987 if (static_cast<int>(LevelIndent) - Offset >= 0)
988 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000989 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000990 IndentForLevel[TheLine.Level] = LevelIndent;
991 } else if (!DryRun) {
992 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
993 }
994 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000995 }
996 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000997 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000998 Tok->Finalized = true;
999 }
1000 }
1001 PreviousLine = *I;
1002 }
Daniel Jasperc359ad02014-04-15 08:13:47 +00001003 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001004 return Penalty;
1005 }
1006
1007private:
1008 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001009 ///
1010 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001011 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1012 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001013 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001014
Daniel Jasperacc33662013-02-08 08:22:00 +00001015 // If the ObjC method declaration does not fit on a line, we should format
1016 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001017 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001018 State.Stack.back().BreakBeforeParameter = true;
1019
Daniel Jasper4b866272013-02-01 11:00:45 +00001020 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001021 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001022 }
1023
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001024 /// \brief An edge in the solution space from \c Previous->State to \c State,
1025 /// inserting a newline dependent on the \c NewLine.
1026 struct StateNode {
1027 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001028 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001029 LineState State;
1030 bool NewLine;
1031 StateNode *Previous;
1032 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001033
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001034 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1035 ///
1036 /// In case of equal penalties, we want to prefer states that were inserted
1037 /// first. During state generation we make sure that we insert states first
1038 /// that break the line as late as possible.
1039 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1040
1041 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1042 /// \c State has the given \c OrderedPenalty.
1043 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1044
1045 /// \brief The BFS queue type.
1046 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1047 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001048
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001049 /// \brief Get the offset of the line relatively to the level.
1050 ///
1051 /// For example, 'public:' labels in classes are offset by 1 or 2
1052 /// characters to the left from their level.
1053 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001054 if (Style.Language == FormatStyle::LK_Java)
1055 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001056 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1057 return Style.AccessModifierOffset;
1058 return 0;
1059 }
1060
1061 /// \brief Add a new line and the required indent before the first Token
1062 /// of the \c UnwrappedLine if there was no structural parsing error.
1063 void formatFirstToken(FormatToken &RootToken,
1064 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1065 unsigned Indent, bool InPPDirective) {
1066 unsigned Newlines =
1067 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1068 // Remove empty lines before "}" where applicable.
1069 if (RootToken.is(tok::r_brace) &&
1070 (!RootToken.Next ||
1071 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1072 Newlines = std::min(Newlines, 1u);
1073 if (Newlines == 0 && !RootToken.IsFirst)
1074 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001075 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1076 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001077
Daniel Jasper11164bd2014-03-21 12:58:53 +00001078 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001079 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1080 PreviousLine->Last->is(tok::l_brace) &&
Nico Weber34272652014-11-13 16:25:37 +00001081 PreviousLine->First->isNot(tok::kw_namespace) &&
1082 !startsExternCBlock(*PreviousLine))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001083 Newlines = 1;
1084
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001085 // Insert extra new line before access specifiers.
1086 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1087 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1088 ++Newlines;
1089
1090 // Remove empty lines after access specifiers.
1091 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1092 Newlines = std::min(1u, Newlines);
1093
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001094 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1095 Indent, InPPDirective &&
1096 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001097 }
1098
1099 /// \brief Get the indent of \p Level from \p IndentForLevel.
1100 ///
1101 /// \p IndentForLevel must contain the indent for the level \c l
1102 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1103 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001104 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001105 if (IndentForLevel[Level] != -1)
1106 return IndentForLevel[Level];
1107 if (Level == 0)
1108 return 0;
1109 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1110 }
1111
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001112 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1113 assert(!A.Last->Next);
1114 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001115 if (B.Affected)
1116 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001117 A.Last->Next = B.First;
1118 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001119 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001120 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1121 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1122 Tok->TotalLength += LengthA;
1123 A.Last = Tok;
1124 }
1125 }
1126
1127 unsigned getColumnLimit(bool InPPDirective) const {
1128 // In preprocessor directives reserve two chars for trailing " \"
1129 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1130 }
1131
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001132 struct CompareLineStatePointers {
1133 bool operator()(LineState *obj1, LineState *obj2) const {
1134 return *obj1 < *obj2;
1135 }
1136 };
1137
Daniel Jasper4b866272013-02-01 11:00:45 +00001138 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001139 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001140 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1141 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1142 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001143 /// to a state where all tokens are placed. Returns the penalty.
1144 ///
1145 /// If \p DryRun is \c false, directly applies the changes.
1146 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001147 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001148
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001149 // Increasing count of \c StateNode items we have created. This is used to
1150 // create a deterministic order independent of the container.
1151 unsigned Count = 0;
1152 QueueType Queue;
1153
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001155 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001156 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001157 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1158 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001159
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001160 unsigned Penalty = 0;
1161
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 // While not empty, take first element and follow edges.
1163 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001164 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001165 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001166 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001167 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001168 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001169 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001170 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001171
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001172 // Cut off the analysis of certain solutions if the analysis gets too
1173 // complex. See description of IgnoreStackForComparison.
1174 if (Count > 10000)
1175 Node->State.IgnoreStackForComparison = true;
1176
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001177 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001178 // State already examined with lower penalty.
1179 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001180
Manuel Klimek71814b42013-10-11 21:25:45 +00001181 FormatDecision LastFormat = Node->State.NextToken->Decision;
1182 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001183 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001184 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001185 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001186 }
1187
Manuel Klimek71814b42013-10-11 21:25:45 +00001188 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001189 // We were unable to find a solution, do nothing.
1190 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001191 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001192 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001193 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001194
Daniel Jasper4b866272013-02-01 11:00:45 +00001195 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001196 if (!DryRun)
1197 reconstructPath(InitialState, Queue.top().second);
1198
Alexander Kornienko49149672013-05-10 11:56:10 +00001199 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1200 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001201
1202 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001203 }
1204
1205 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001206 std::deque<StateNode *> Path;
1207 // We do not need a break before the initial token.
1208 while (Current->Previous) {
1209 Path.push_front(Current);
1210 Current = Current->Previous;
1211 }
1212 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1213 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001214 unsigned Penalty = 0;
1215 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1216 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1217
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001218 DEBUG({
1219 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001220 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001221 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001222 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001223 }
1224 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001225 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001226 }
1227
Manuel Klimekaf491072013-02-13 10:54:19 +00001228 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001229 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001230 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001231 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001232 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001233 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001234 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001235 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001236 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001237 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001238
1239 StateNode *Node = new (Allocator.Allocate())
1240 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001241 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1242 return;
1243
Daniel Jasperde0328a2013-08-16 11:20:30 +00001244 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001245
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001246 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1247 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001248 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001249
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001250 /// \brief If the \p State's next token is an r_brace closing a nested block,
1251 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001252 ///
1253 /// Returns \c true if all children could be placed successfully and adapts
1254 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1255 /// creates changes using \c Whitespaces.
1256 ///
1257 /// The crucial idea here is that children always get formatted upon
1258 /// encountering the closing brace right after the nested block. Now, if we
1259 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1260 /// \c false), the entire block has to be kept on the same line (which is only
1261 /// possible if it fits on the line, only contains a single statement, etc.
1262 ///
1263 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1264 /// break after the "{", format all lines with correct indentation and the put
1265 /// the closing "}" on yet another new line.
1266 ///
1267 /// This enables us to keep the simple structure of the
1268 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1269 /// break or don't break.
1270 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1271 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001272 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001273 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1274 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1275 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001276 // The previous token does not open a block. Nothing to do. We don't
1277 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001278 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001279
1280 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001281 int AdditionalIndent =
1282 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001283 if (State.Stack.size() < 2 ||
1284 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1285 AdditionalIndent = State.Stack.back().Indent -
1286 Previous.Children[0]->Level * Style.IndentWidth;
1287 }
1288
Daniel Jasper9c199562013-11-28 15:58:55 +00001289 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1290 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001291 return true;
1292 }
1293
Daniel Jasper56346192014-10-27 16:31:46 +00001294 if (Previous.Children[0]->First->MustBreakBefore)
1295 return false;
1296
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001297 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001298 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001299 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001300
Daniel Jasper21397a32014-04-09 12:21:48 +00001301 // Cannot merge into one line if this line ends on a comment.
1302 if (Previous.is(tok::comment))
1303 return false;
1304
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001305 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001306 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001307 return false;
1308
Daniel Jasper98583d52014-04-15 08:28:06 +00001309 // If the child line exceeds the column limit, we wouldn't want to merge it.
1310 // We add +2 for the trailing " }".
1311 if (Style.ColumnLimit > 0 &&
1312 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1313 Style.ColumnLimit)
1314 return false;
1315
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001316 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001317 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001318 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001319 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001320 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001321 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001322 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001323
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001324 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001325 return true;
1326 }
1327
Daniel Jasperde0328a2013-08-16 11:20:30 +00001328 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001329 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001330 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001331 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001332
1333 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001334
1335 // Cache to store the penalty of formatting a vector of AnnotatedLines
1336 // starting from a specific additional offset. Improves performance if there
1337 // are many nested blocks.
1338 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1339 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001340};
1341
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001342class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001343public:
Daniel Jasper23376252014-09-09 14:37:39 +00001344 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001345 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001346 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001347 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1348 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1349 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1350 FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +00001351 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1352 getFormattingLangOpts(Style)));
1353 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001354
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001355 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001356 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1357 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001358 }
1359
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001360 ArrayRef<FormatToken *> lex() {
1361 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001362 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001363 do {
1364 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001365 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001366 if (Tokens.back()->NewlinesBefore > 0)
1367 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001368 } while (Tokens.back()->Tok.isNot(tok::eof));
1369 return Tokens;
1370 }
1371
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001372 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001373
1374private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001375 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001376 if (tryMerge_TMacro())
1377 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001378 if (tryMergeConflictMarkers())
1379 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001380
1381 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001382 if (tryMergeJSRegexLiteral())
1383 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001384 if (tryMergeEscapeSequence())
1385 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001386
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001387 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1388 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1389 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1390 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001391 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001392 // FIXME: We probably need to change token type to mimic operator with the
1393 // correct priority.
1394 if (tryMergeTokens(JSIdentity))
1395 return;
1396 if (tryMergeTokens(JSNotIdentity))
1397 return;
1398 if (tryMergeTokens(JSShiftEqual))
1399 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001400 if (tryMergeTokens(JSRightArrow))
1401 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001402 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001403 }
1404
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001405 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1406 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001407 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001408
1409 SmallVectorImpl<FormatToken *>::const_iterator First =
1410 Tokens.end() - Kinds.size();
1411 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001412 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001413 unsigned AddLength = 0;
1414 for (unsigned i = 1; i < Kinds.size(); ++i) {
1415 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1416 First[i]->WhitespaceRange.getEnd())
1417 return false;
1418 AddLength += First[i]->TokenText.size();
1419 }
1420 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1421 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1422 First[0]->TokenText.size() + AddLength);
1423 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001424 return true;
1425 }
1426
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001427 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001428 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001429 bool tryMergeEscapeSequence() {
1430 if (Tokens.size() < 2)
1431 return false;
1432 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +00001433 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001434 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001435 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001436 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001437 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1438 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001439 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +00001440 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001441 return true;
1442 }
1443
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001444 // Try to determine whether the current token ends a JavaScript regex literal.
1445 // We heuristically assume that this is a regex literal if we find two
1446 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001447 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1448 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001449 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001450 if (Tokens.size() < 2)
1451 return false;
1452 // If a regex literal ends in "\//", this gets represented by an unknown
1453 // token "\" and a comment.
1454 bool MightEndWithEscapedSlash =
1455 Tokens.back()->is(tok::comment) &&
1456 Tokens.back()->TokenText.startswith("//") &&
1457 Tokens[Tokens.size() - 2]->TokenText == "\\";
1458 if (!MightEndWithEscapedSlash &&
1459 (Tokens.back()->isNot(tok::slash) ||
1460 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1461 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001462 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001463 unsigned TokenCount = 0;
1464 unsigned LastColumn = Tokens.back()->OriginalColumn;
1465 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1466 ++TokenCount;
1467 if (I[0]->is(tok::slash) && I + 1 != E &&
1468 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1469 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1470 tok::question, tok::kw_return) ||
1471 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001472 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +00001473 // This regex literal ends in '\//'. Skip past the '//' of the last
1474 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +00001475 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1476 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +00001477 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001478 Tokens.resize(Tokens.size() - TokenCount);
1479 Tokens.back()->Tok.setKind(tok::unknown);
1480 Tokens.back()->Type = TT_RegexLiteral;
1481 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1482 return true;
1483 }
1484
1485 // There can't be a newline inside a regex literal.
1486 if (I[0]->NewlinesBefore > 0)
1487 return false;
1488 }
1489 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001490 }
1491
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001492 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001493 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001494 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001495 FormatToken *Last = Tokens.back();
1496 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001497 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001498
1499 FormatToken *String = Tokens[Tokens.size() - 2];
1500 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001501 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001502
1503 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001504 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001505
1506 FormatToken *Macro = Tokens[Tokens.size() - 4];
1507 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001508 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001509
1510 const char *Start = Macro->TokenText.data();
1511 const char *End = Last->TokenText.data() + Last->TokenText.size();
1512 String->TokenText = StringRef(Start, End - Start);
1513 String->IsFirst = Macro->IsFirst;
1514 String->LastNewlineOffset = Macro->LastNewlineOffset;
1515 String->WhitespaceRange = Macro->WhitespaceRange;
1516 String->OriginalColumn = Macro->OriginalColumn;
1517 String->ColumnWidth = encoding::columnWidthWithTabs(
1518 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1519
1520 Tokens.pop_back();
1521 Tokens.pop_back();
1522 Tokens.pop_back();
1523 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001524 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001525 }
1526
Manuel Klimek68b03042014-04-14 09:14:11 +00001527 bool tryMergeConflictMarkers() {
1528 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1529 return false;
1530
1531 // Conflict lines look like:
1532 // <marker> <text from the vcs>
1533 // For example:
1534 // >>>>>>> /file/in/file/system at revision 1234
1535 //
1536 // We merge all tokens in a line that starts with a conflict marker
1537 // into a single token with a special token type that the unwrapped line
1538 // parser will use to correctly rebuild the underlying code.
1539
1540 FileID ID;
1541 // Get the position of the first token in the line.
1542 unsigned FirstInLineOffset;
1543 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1544 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1545 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1546 // Calculate the offset of the start of the current line.
1547 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1548 if (LineOffset == StringRef::npos) {
1549 LineOffset = 0;
1550 } else {
1551 ++LineOffset;
1552 }
1553
1554 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1555 StringRef LineStart;
1556 if (FirstSpace == StringRef::npos) {
1557 LineStart = Buffer.substr(LineOffset);
1558 } else {
1559 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1560 }
1561
1562 TokenType Type = TT_Unknown;
1563 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1564 Type = TT_ConflictStart;
1565 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1566 LineStart == "====") {
1567 Type = TT_ConflictAlternative;
1568 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1569 Type = TT_ConflictEnd;
1570 }
1571
1572 if (Type != TT_Unknown) {
1573 FormatToken *Next = Tokens.back();
1574
1575 Tokens.resize(FirstInLineIndex + 1);
1576 // We do not need to build a complete token here, as we will skip it
1577 // during parsing anyway (as we must not touch whitespace around conflict
1578 // markers).
1579 Tokens.back()->Type = Type;
1580 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1581
1582 Tokens.push_back(Next);
1583 return true;
1584 }
1585
1586 return false;
1587 }
1588
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001589 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001590 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001591 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001592 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001593 Token Greater = FormatTok->Tok;
1594 FormatTok = new (Allocator.Allocate()) FormatToken;
1595 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001596 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001597 FormatTok->Tok.getLocation().getLocWithOffset(1);
1598 FormatTok->WhitespaceRange =
1599 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001600 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001601 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001602 GreaterStashed = false;
1603 return FormatTok;
1604 }
1605
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001606 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001607 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001608 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001609 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001610 FormatTok->IsFirst = IsFirstToken;
1611 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001612
1613 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001614 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001615 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001616 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1617 switch (FormatTok->TokenText[i]) {
1618 case '\n':
1619 ++FormatTok->NewlinesBefore;
1620 // FIXME: This is technically incorrect, as it could also
1621 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001622 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1623 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1624 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001625 FormatTok->HasUnescapedNewline = true;
1626 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1627 Column = 0;
1628 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001629 case '\r':
1630 case '\f':
1631 case '\v':
1632 Column = 0;
1633 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001634 case ' ':
1635 ++Column;
1636 break;
1637 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001638 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001639 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001640 case '\\':
1641 ++Column;
1642 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1643 FormatTok->TokenText[i + 1] != '\n'))
1644 FormatTok->Type = TT_ImplicitStringLiteral;
1645 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001646 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001647 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001648 ++Column;
1649 break;
1650 }
1651 }
1652
Daniel Jasper877615c2013-10-11 19:45:02 +00001653 if (FormatTok->Type == TT_ImplicitStringLiteral)
1654 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001655 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001656
Daniel Jasper8369aa52013-07-16 20:28:33 +00001657 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001658 }
Manuel Klimekef920692013-01-07 07:56:50 +00001659
Manuel Klimek1abf7892013-01-04 23:34:14 +00001660 // In case the token starts with escaped newlines, we want to
1661 // take them into account as whitespace - this pattern is quite frequent
1662 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001663 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001664 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1665 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001666 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001667 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001668 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001669 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001670 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001671
1672 FormatTok->WhitespaceRange = SourceRange(
1673 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1674
Manuel Klimek31c85922013-08-29 15:21:40 +00001675 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001676
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001677 TrailingWhitespace = 0;
1678 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001679 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001680 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001681 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001682 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001683 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001684 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001685 FormatTok->Tok.setIdentifierInfo(&Info);
1686 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001687 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001688 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001689 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001690 GreaterStashed = true;
1691 }
1692
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001693 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001694
Alexander Kornienko39856b72013-09-10 09:38:25 +00001695 StringRef Text = FormatTok->TokenText;
1696 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001697 if (FirstNewlinePos == StringRef::npos) {
1698 // FIXME: ColumnWidth actually depends on the start column, we need to
1699 // take this into account when the token is moved.
1700 FormatTok->ColumnWidth =
1701 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1702 Column += FormatTok->ColumnWidth;
1703 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001704 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001705 // FIXME: ColumnWidth actually depends on the start column, we need to
1706 // take this into account when the token is moved.
1707 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1708 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1709
Alexander Kornienko39856b72013-09-10 09:38:25 +00001710 // The last line of the token always starts in column 0.
1711 // Thus, the length can be precomputed even in the presence of tabs.
1712 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1713 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1714 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001715 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001716 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001717
Daniel Jaspere1e43192014-04-01 12:55:11 +00001718 FormatTok->IsForEachMacro =
1719 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1720 FormatTok->Tok.getIdentifierInfo());
1721
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001722 return FormatTok;
1723 }
1724
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001725 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001726 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001727 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001728 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001729 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001730 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001731 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001732 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001733 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001734 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001735 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001736 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001737 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001738 // Index (in 'Tokens') of the last token that starts a new line.
1739 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001740 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001741 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001742
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001743 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001744
Daniel Jasper8369aa52013-07-16 20:28:33 +00001745 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001746 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001747 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1748 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001749 // For formatting, treat unterminated string literals like normal string
1750 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001751 if (Tok.is(tok::unknown)) {
1752 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1753 Tok.Tok.setKind(tok::string_literal);
1754 Tok.IsUnterminatedLiteral = true;
1755 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1756 Tok.TokenText == "''") {
1757 Tok.Tok.setKind(tok::char_constant);
1758 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001759 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001760
1761 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1762 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001763 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001764 }
1765
Daniel Jasper471894432014-08-06 13:40:26 +00001766 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001767
1768 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1769 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001770 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001771 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001772 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001773
1774 void resetLexer(unsigned Offset) {
1775 StringRef Buffer = SourceMgr.getBufferData(ID);
1776 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1777 getFormattingLangOpts(Style), Buffer.begin(),
1778 Buffer.begin() + Offset, Buffer.end()));
1779 Lex->SetKeepWhitespaceMode(true);
1780 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001781};
1782
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001783static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1784 switch (Language) {
1785 case FormatStyle::LK_Cpp:
1786 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001787 case FormatStyle::LK_Java:
1788 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001789 case FormatStyle::LK_JavaScript:
1790 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001791 case FormatStyle::LK_Proto:
1792 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001793 default:
1794 return "Unknown";
1795 }
1796}
1797
Daniel Jasperf7935112012-12-03 18:12:45 +00001798class Formatter : public UnwrappedLineConsumer {
1799public:
Daniel Jasper23376252014-09-09 14:37:39 +00001800 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001801 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001802 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1803 Whitespaces(SourceMgr, Style,
1804 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001805 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001806 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001807 DEBUG(llvm::dbgs() << "File encoding: "
1808 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1809 : "unknown")
1810 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001811 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1812 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001813 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001814
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001815 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001816 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001817 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001818
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001819 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1820 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001821 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001822 assert(UnwrappedLines.rbegin()->empty());
1823 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1824 ++Run) {
1825 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1826 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1827 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1828 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1829 }
1830 tooling::Replacements RunResult =
1831 format(AnnotatedLines, StructuralError, Tokens);
1832 DEBUG({
1833 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1834 for (tooling::Replacements::iterator I = RunResult.begin(),
1835 E = RunResult.end();
1836 I != E; ++I) {
1837 llvm::dbgs() << I->toString() << "\n";
1838 }
1839 });
1840 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1841 delete AnnotatedLines[i];
1842 }
1843 Result.insert(RunResult.begin(), RunResult.end());
1844 Whitespaces.reset();
1845 }
1846 return Result;
1847 }
1848
1849 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1850 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001851 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001852 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001853 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001854 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001855 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001856 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001857 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001858 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001859 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001860
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001861 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001862 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1863 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001864 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001865 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001866 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001867 return Whitespaces.generateReplacements();
1868 }
1869
1870private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001871 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001872 // Returns \c true if at least one line between I and E or one of their
1873 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001874 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1875 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1876 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001877 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001878 while (I != E) {
1879 AnnotatedLine *Line = *I;
1880 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1881
1882 // If a line is part of a preprocessor directive, it needs to be formatted
1883 // if any token within the directive is affected.
1884 if (Line->InPPDirective) {
1885 FormatToken *Last = Line->Last;
1886 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1887 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1888 Last = (*PPEnd)->Last;
1889 ++PPEnd;
1890 }
1891
1892 if (affectsTokenRange(*Line->First, *Last,
1893 /*IncludeLeadingNewlines=*/false)) {
1894 SomeLineAffected = true;
1895 markAllAsAffected(I, PPEnd);
1896 }
1897 I = PPEnd;
1898 continue;
1899 }
1900
Daniel Jasper38c82402013-11-29 09:27:43 +00001901 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001902 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001903
Daniel Jasper38c82402013-11-29 09:27:43 +00001904 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001905 ++I;
1906 }
1907 return SomeLineAffected;
1908 }
1909
Daniel Jasper9c199562013-11-28 15:58:55 +00001910 // Determines whether 'Line' is affected by the SourceRanges given as input.
1911 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001912 bool nonPPLineAffected(AnnotatedLine *Line,
1913 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001914 bool SomeLineAffected = false;
1915 Line->ChildrenAffected =
1916 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1917 if (Line->ChildrenAffected)
1918 SomeLineAffected = true;
1919
1920 // Stores whether one of the line's tokens is directly affected.
1921 bool SomeTokenAffected = false;
1922 // Stores whether we need to look at the leading newlines of the next token
1923 // in order to determine whether it was affected.
1924 bool IncludeLeadingNewlines = false;
1925
1926 // Stores whether the first child line of any of this line's tokens is
1927 // affected.
1928 bool SomeFirstChildAffected = false;
1929
1930 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1931 // Determine whether 'Tok' was affected.
1932 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1933 SomeTokenAffected = true;
1934
1935 // Determine whether the first child of 'Tok' was affected.
1936 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1937 SomeFirstChildAffected = true;
1938
1939 IncludeLeadingNewlines = Tok->Children.empty();
1940 }
1941
1942 // Was this line moved, i.e. has it previously been on the same line as an
1943 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001944 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1945 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001946
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001947 bool IsContinuedComment =
1948 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1949 Line->First->NewlinesBefore < 2 && PreviousLine &&
1950 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001951
1952 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1953 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001954 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001955 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001956 }
1957 return SomeLineAffected;
1958 }
1959
Daniel Jasper5500f612013-11-25 11:08:59 +00001960 // Marks all lines between I and E as well as all their children as affected.
1961 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1962 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1963 while (I != E) {
1964 (*I)->Affected = true;
1965 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1966 ++I;
1967 }
1968 }
1969
1970 // Returns true if the range from 'First' to 'Last' intersects with one of the
1971 // input ranges.
1972 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1973 bool IncludeLeadingNewlines) {
1974 SourceLocation Start = First.WhitespaceRange.getBegin();
1975 if (!IncludeLeadingNewlines)
1976 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001977 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001978 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001979 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1980 return affectsCharSourceRange(Range);
1981 }
1982
1983 // Returns true if one of the input ranges intersect the leading empty lines
1984 // before 'Tok'.
1985 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1986 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1987 Tok.WhitespaceRange.getBegin(),
1988 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1989 return affectsCharSourceRange(EmptyLineRange);
1990 }
1991
1992 // Returns true if 'Range' intersects with one of the input ranges.
1993 bool affectsCharSourceRange(const CharSourceRange &Range) {
1994 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1995 E = Ranges.end();
1996 I != E; ++I) {
1997 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1998 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1999 return true;
2000 }
2001 return false;
2002 }
2003
Alexander Kornienko9e649af2013-09-11 12:25:57 +00002004 static bool inputUsesCRLF(StringRef Text) {
2005 return Text.count('\r') * 2 > Text.count('\n');
2006 }
2007
Manuel Klimek71814b42013-10-11 21:25:45 +00002008 void
2009 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002010 unsigned CountBoundToVariable = 0;
2011 unsigned CountBoundToType = 0;
2012 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002013 bool HasBinPackedFunction = false;
2014 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002015 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002016 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002017 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002018 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002019 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002020 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002021 bool SpacesBefore =
2022 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2023 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2024 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002025 if (SpacesBefore && !SpacesAfter)
2026 ++CountBoundToVariable;
2027 else if (!SpacesBefore && SpacesAfter)
2028 ++CountBoundToType;
2029 }
2030
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002031 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2032 if (Tok->is(tok::coloncolon) &&
2033 Tok->Previous->Type == TT_TemplateOpener)
2034 HasCpp03IncompatibleFormat = true;
2035 if (Tok->Type == TT_TemplateCloser &&
2036 Tok->Previous->Type == TT_TemplateCloser)
2037 HasCpp03IncompatibleFormat = true;
2038 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002039
2040 if (Tok->PackingKind == PPK_BinPacked)
2041 HasBinPackedFunction = true;
2042 if (Tok->PackingKind == PPK_OnePerLine)
2043 HasOnePerLineFunction = true;
2044
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002045 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002046 }
2047 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002048 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002049 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002050 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002051 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002052 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002053 }
2054 if (Style.Standard == FormatStyle::LS_Auto) {
2055 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2056 : FormatStyle::LS_Cpp03;
2057 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002058 BinPackInconclusiveFunctions =
2059 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002060 }
2061
Craig Topperfb6b25b2014-03-15 04:29:04 +00002062 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002063 assert(!UnwrappedLines.empty());
2064 UnwrappedLines.back().push_back(TheLine);
2065 }
2066
Craig Topperfb6b25b2014-03-15 04:29:04 +00002067 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002068 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002069 }
2070
2071 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002072 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002073 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002074 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002075 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002076 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002077
2078 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002079 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002080};
2081
Craig Topperaf35e852013-06-30 22:29:28 +00002082} // end anonymous namespace
2083
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002084tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2085 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002086 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002087 if (Style.DisableFormat)
2088 return tooling::Replacements();
2089 return reformat(Style, SourceMgr,
2090 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2091}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002092
Daniel Jasper23376252014-09-09 14:37:39 +00002093tooling::Replacements reformat(const FormatStyle &Style,
2094 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002095 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002096 if (Style.DisableFormat)
2097 return tooling::Replacements();
2098 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002099 return formatter.format();
2100}
2101
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002102tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002103 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002104 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002105 if (Style.DisableFormat)
2106 return tooling::Replacements();
2107
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002108 FileManager Files((FileSystemOptions()));
2109 DiagnosticsEngine Diagnostics(
2110 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2111 new DiagnosticOptions);
2112 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002113 std::unique_ptr<llvm::MemoryBuffer> Buf =
2114 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002115 const clang::FileEntry *Entry =
2116 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002117 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002118 FileID ID =
2119 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002120 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2121 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002122 for (const tooling::Range &Range : Ranges) {
2123 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2124 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002125 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2126 }
Daniel Jasper23376252014-09-09 14:37:39 +00002127 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002128}
2129
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002130LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002131 LangOptions LangOpts;
2132 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002133 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2134 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002135 LangOpts.LineComment = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002136 LangOpts.CXXOperatorNames =
2137 Style.Language != FormatStyle::LK_JavaScript ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002138 LangOpts.Bool = 1;
2139 LangOpts.ObjC1 = 1;
2140 LangOpts.ObjC2 = 1;
2141 return LangOpts;
2142}
2143
Edwin Vaned544aa72013-09-30 13:31:48 +00002144const char *StyleOptionHelpDescription =
2145 "Coding style, currently supports:\n"
2146 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2147 "Use -style=file to load style configuration from\n"
2148 ".clang-format file located in one of the parent\n"
2149 "directories of the source file (or current\n"
2150 "directory for stdin).\n"
2151 "Use -style=\"{key: value, ...}\" to set specific\n"
2152 "parameters, e.g.:\n"
2153 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2154
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002155static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002156 if (FileName.endswith(".java")) {
2157 return FormatStyle::LK_Java;
2158 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002159 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002160 } else if (FileName.endswith_lower(".proto") ||
2161 FileName.endswith_lower(".protodevel")) {
2162 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002163 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002164 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002165}
2166
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002167FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2168 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002169 FormatStyle Style = getLLVMStyle();
2170 Style.Language = getLanguageByFileName(FileName);
2171 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002172 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2173 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002174 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002175 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002176
2177 if (StyleName.startswith("{")) {
2178 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002179 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002180 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2181 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002182 }
2183 return Style;
2184 }
2185
2186 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002187 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002188 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2189 << " style\n";
2190 return Style;
2191 }
2192
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002193 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002194 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002195 SmallString<128> Path(FileName);
2196 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002197 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002198 Directory = llvm::sys::path::parent_path(Directory)) {
2199 if (!llvm::sys::fs::is_directory(Directory))
2200 continue;
2201 SmallString<128> ConfigFile(Directory);
2202
2203 llvm::sys::path::append(ConfigFile, ".clang-format");
2204 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2205 bool IsFile = false;
2206 // Ignore errors from is_regular_file: we only need to know if we can read
2207 // the file or not.
2208 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2209
2210 if (!IsFile) {
2211 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2212 ConfigFile = Directory;
2213 llvm::sys::path::append(ConfigFile, "_clang-format");
2214 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2215 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2216 }
2217
2218 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002219 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2220 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2221 if (std::error_code EC = Text.getError()) {
2222 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002223 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002224 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002225 if (std::error_code ec =
2226 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002227 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002228 if (!UnsuitableConfigFiles.empty())
2229 UnsuitableConfigFiles.append(", ");
2230 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002231 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002232 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002233 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2234 << "\n";
2235 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002236 }
2237 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2238 return Style;
2239 }
2240 }
2241 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2242 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002243 if (!UnsuitableConfigFiles.empty()) {
2244 llvm::errs() << "Configuration file(s) do(es) not support "
2245 << getLanguageName(Style.Language) << ": "
2246 << UnsuitableConfigFiles << "\n";
2247 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002248 return Style;
2249}
2250
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002251} // namespace format
2252} // namespace clang