blob: 2821e4aa2c1f949bf0e13e36422543729184ce14 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000045 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 }
47};
48
49template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56 }
57};
58
59template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66 }
67};
68
Daniel Jasperd74cf402014-04-08 12:46:38 +000069template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71 IO.enumCase(Value, "None", FormatStyle::SFS_None);
72 IO.enumCase(Value, "false", FormatStyle::SFS_None);
73 IO.enumCase(Value, "All", FormatStyle::SFS_All);
74 IO.enumCase(Value, "true", FormatStyle::SFS_All);
75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76 }
77};
78
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000085 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086 }
87};
88
Alexander Kornienkod6538332013-05-07 15:32:14 +000089template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000091 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 FormatStyle::NamespaceIndentationKind &Value) {
93 IO.enumCase(Value, "None", FormatStyle::NI_None);
94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000096 }
97};
98
99template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000100struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000101 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102 FormatStyle::SpaceBeforeParensOptions &Value) {
103 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000104 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 FormatStyle::SBPO_ControlStatements);
106 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000107
108 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000109 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
110 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000111 }
112};
113
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000115 static void mapping(IO &IO, FormatStyle &Style) {
116 // When reading, read the language first, we need it for getPredefinedStyle.
117 IO.mapOptional("Language", Style.Language);
118
Alexander Kornienko49149672013-05-10 11:56:10 +0000119 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000120 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000121 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000122 ArrayRef<StringRef> Styles(StylesArray);
123 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
124 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000126 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000127 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000128 IO.mapOptional("# BasedOnStyle", StyleName);
129 break;
130 }
131 }
132 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000133 StringRef BasedOnStyle;
134 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000135 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000136 FormatStyle::LanguageKind OldLanguage = Style.Language;
137 FormatStyle::LanguageKind Language =
138 ((FormatStyle *)IO.getContext())->Language;
139 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000140 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
141 return;
142 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000143 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000144 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000145 }
146
147 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000148 IO.mapOptional("ConstructorInitializerIndentWidth",
149 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000150 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000151 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000152 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
153 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000154 IO.mapOptional("AllowShortBlocksOnASingleLine",
155 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000156 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
157 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000158 IO.mapOptional("AllowShortLoopsOnASingleLine",
159 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000160 IO.mapOptional("AllowShortFunctionsOnASingleLine",
161 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000162 IO.mapOptional("AlwaysBreakTemplateDeclarations",
163 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000164 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
165 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000166 IO.mapOptional("BreakBeforeBinaryOperators",
167 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000168 IO.mapOptional("BreakBeforeTernaryOperators",
169 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000170 IO.mapOptional("BreakConstructorInitializersBeforeComma",
171 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000172 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
173 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
174 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
175 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
176 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000177 IO.mapOptional("ExperimentalAutoDetectBinPacking",
178 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000179 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
180 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000181 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
182 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000183 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000184 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185 IO.mapOptional("ObjCSpaceBeforeProtocolList",
186 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000187 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
188 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000189 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
190 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000191 IO.mapOptional("PenaltyBreakFirstLessLess",
192 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000193 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
194 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
195 Style.PenaltyReturnTypeOnItsOwnLine);
196 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
197 IO.mapOptional("SpacesBeforeTrailingComments",
198 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000199 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000201 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000202 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000203 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000204 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000205 IO.mapOptional("IndentFunctionDeclarationAfterType",
206 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000207 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000208 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000209 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000210 IO.mapOptional("SpacesInCStyleCastParentheses",
211 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000212 IO.mapOptional("SpacesInContainerLiterals",
213 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000214 IO.mapOptional("SpaceBeforeAssignmentOperators",
215 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000216 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000217 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000218 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000219
220 // For backward compatibility.
221 if (!IO.outputting()) {
222 IO.mapOptional("SpaceAfterControlStatementKeyword",
223 Style.SpaceBeforeParens);
224 }
225 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000226 }
227};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000228
229// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000230// IO.getContext() should contain a pointer to the FormatStyle structure, that
231// will be used to get default values for missing keys.
232// If the first element has no Language specified, it will be treated as the
233// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000234template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000235 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
236 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000237 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000238 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000239 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000240 if (Index >= Seq.size()) {
241 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000242 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000243 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000244 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000245 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000246 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000247 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000248 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000249 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000250 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000251 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000252 }
253};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000254}
255}
256
Daniel Jasperf7935112012-12-03 18:12:45 +0000257namespace clang {
258namespace format {
259
Daniel Jasperf7935112012-12-03 18:12:45 +0000260FormatStyle getLLVMStyle() {
261 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000262 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000263 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000264 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000265 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000266 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000267 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000268 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000269 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000270 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000271 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000272 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000273 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000274 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000275 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000276 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
277 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000278 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000279 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000280 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000281 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000282 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000283 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000284 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000285 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000286 LLVMStyle.ForEachMacros.push_back("foreach");
287 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
288 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000289 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000290 LLVMStyle.IndentFunctionDeclarationAfterType = false;
291 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000292 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000293 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000294 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000295 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000296 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000297 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000298 LLVMStyle.PointerBindsToType = false;
299 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000300 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000301 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000302 LLVMStyle.SpacesInParentheses = false;
303 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000304 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000305 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000306 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000307 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000308 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000309
Daniel Jasper19a541e2013-12-19 16:45:34 +0000310 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000311 LLVMStyle.PenaltyBreakFirstLessLess = 120;
312 LLVMStyle.PenaltyBreakString = 1000;
313 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000314 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000315 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000316
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 return LLVMStyle;
318}
319
Nico Weber514ecc82014-02-02 20:50:45 +0000320FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000321 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000322 GoogleStyle.Language = Language;
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000325 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000326 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000327 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000328 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000329 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000330 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
331 GoogleStyle.DerivePointerBinding = true;
332 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000333 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000334 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000335 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000336 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000337 GoogleStyle.PointerBindsToType = true;
338 GoogleStyle.SpacesBeforeTrailingComments = 2;
339 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000340
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000341 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000342 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000343
Nico Weber514ecc82014-02-02 20:50:45 +0000344 if (Language == FormatStyle::LK_JavaScript) {
345 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000346 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000347 GoogleStyle.SpacesInContainerLiterals = false;
348 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000349 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000350 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000351 }
352
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 return GoogleStyle;
354}
355
Nico Weber514ecc82014-02-02 20:50:45 +0000356FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
357 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000358 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000359 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000360 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000361 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000362 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000363 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000364 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000365 return ChromiumStyle;
366}
367
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000368FormatStyle getMozillaStyle() {
369 FormatStyle MozillaStyle = getLLVMStyle();
370 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000371 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000372 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
373 MozillaStyle.DerivePointerBinding = true;
374 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000375 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000376 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
377 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
378 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000379 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000380 return MozillaStyle;
381}
382
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000383FormatStyle getWebKitStyle() {
384 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000385 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000386 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000387 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000388 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000389 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000390 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000391 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000392 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000393 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000394 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000395 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000396 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000397 return Style;
398}
399
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000400FormatStyle getGNUStyle() {
401 FormatStyle Style = getLLVMStyle();
402 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000403 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000404 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000405 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000406 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000407 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000408 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000409 return Style;
410}
411
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000412bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
413 FormatStyle *Style) {
414 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000415 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000416 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000417 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000418 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000419 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000420 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000421 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000422 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000423 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000424 } else if (Name.equals_lower("gnu")) {
425 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000426 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000427 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000428 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000429
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000430 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000431 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000432}
433
434llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000435 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000436 FormatStyle::LanguageKind Language = Style->Language;
437 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000438 if (Text.trim().empty())
439 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000440
441 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000442 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000443 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
444 // values for the fields, keys for which are missing from the configuration.
445 // Mapping also uses the context to get the language to find the correct
446 // base style.
447 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000448 Input >> Styles;
449 if (Input.error())
450 return Input.error();
451
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000452 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000453 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000454 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000455 return llvm::make_error_code(llvm::errc::invalid_argument);
456 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000457 for (unsigned j = 0; j < i; ++j) {
458 if (Styles[i].Language == Styles[j].Language) {
459 DEBUG(llvm::dbgs()
460 << "Duplicate languages in the config file on positions " << j
461 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000462 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000463 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000464 }
465 }
466 // Look for a suitable configuration starting from the end, so we can
467 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000468 // configuration (which can only be at slot 0) after it.
469 for (int i = Styles.size() - 1; i >= 0; --i) {
470 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000471 Styles[i].Language == FormatStyle::LK_None) {
472 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000473 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000474 return llvm::make_error_code(llvm::errc::success);
475 }
476 }
477 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000478}
479
480std::string configurationAsText(const FormatStyle &Style) {
481 std::string Text;
482 llvm::raw_string_ostream Stream(Text);
483 llvm::yaml::Output Output(Stream);
484 // We use the same mapping method for input and output, so we need a non-const
485 // reference here.
486 FormatStyle NonConstStyle = Style;
487 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000488 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000489}
490
Craig Topperaf35e852013-06-30 22:29:28 +0000491namespace {
492
Daniel Jasperde0328a2013-08-16 11:20:30 +0000493class NoColumnLimitFormatter {
494public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000495 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000496
497 /// \brief Formats the line starting at \p State, simply keeping all of the
498 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000499 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000500 LineState State =
501 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000502 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000503 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000504 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000505 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
506 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
507 }
508 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000509
Daniel Jasperde0328a2013-08-16 11:20:30 +0000510private:
511 ContinuationIndenter *Indenter;
512};
513
Daniel Jasper56f8b432013-11-06 23:12:09 +0000514class LineJoiner {
515public:
516 LineJoiner(const FormatStyle &Style) : Style(Style) {}
517
518 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
519 unsigned
520 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000521 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000522 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
523 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000524 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000525 if (TheLine->Last->Type == TT_LineComment)
526 return 0;
527
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000528 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
529 return 0;
530
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000531 unsigned Limit =
532 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000533 // If we already exceed the column limit, we set 'Limit' to 0. The different
534 // tryMerge..() functions can then decide whether to still do merging.
535 Limit = TheLine->Last->TotalLength > Limit
536 ? 0
537 : Limit - TheLine->Last->TotalLength;
538
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000539 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000540 return 0;
541
Daniel Jasperd74cf402014-04-08 12:46:38 +0000542 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
543 // If necessary, change to something smarter.
544 bool MergeShortFunctions =
545 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
546 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
547 TheLine->Level != 0);
548
Daniel Jasper234379f2013-12-24 13:31:25 +0000549 if (TheLine->Last->Type == TT_FunctionLBrace &&
550 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000551 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000552 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000553 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000554 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000555 ? tryMergeSimpleBlock(I, E, Limit)
556 : 0;
557 }
558 if (I[1]->First->Type == TT_FunctionLBrace &&
559 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000560 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000561 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
562 return 0;
563 Limit -= 2;
564
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000565 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000566 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000567 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
568 // If we managed to merge the block, count the function header, which is
569 // on a separate line.
570 if (MergedLines > 0)
571 ++MergedLines;
572 }
573 return MergedLines;
574 }
575 if (TheLine->First->is(tok::kw_if)) {
576 return Style.AllowShortIfStatementsOnASingleLine
577 ? tryMergeSimpleControlStatement(I, E, Limit)
578 : 0;
579 }
580 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
581 return Style.AllowShortLoopsOnASingleLine
582 ? tryMergeSimpleControlStatement(I, E, Limit)
583 : 0;
584 }
585 if (TheLine->InPPDirective &&
586 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000587 return tryMergeSimplePPDirective(I, E, Limit);
588 }
589 return 0;
590 }
591
592private:
593 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000594 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000595 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
596 unsigned Limit) {
597 if (Limit == 0)
598 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000599 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000600 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000601 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000602 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000603 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000604 return 0;
605 return 1;
606 }
607
608 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000609 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000610 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
611 if (Limit == 0)
612 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000613 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
614 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000615 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000617 if (I[1]->InPPDirective != (*I)->InPPDirective ||
618 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000619 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000620 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000621 AnnotatedLine &Line = **I;
622 if (Line.Last->isNot(tok::r_paren))
623 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000624 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000625 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000626 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000627 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000628 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000629 return 0;
630 // Only inline simple if's (no nested if or else).
631 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000632 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000633 return 0;
634 return 1;
635 }
636
637 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000638 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000639 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
640 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000641 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000642
643 // Don't merge ObjC @ keywords and methods.
644 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000645 return 0;
646
Daniel Jasper17605d32014-05-14 09:33:35 +0000647 // Check that the current line allows merging. This depends on whether we
648 // are in a control flow statements as well as several style flags.
649 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
650 return 0;
651 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
652 tok::kw_catch, tok::kw_for, tok::r_brace)) {
653 if (!Style.AllowShortBlocksOnASingleLine)
654 return 0;
655 if (!Style.AllowShortIfStatementsOnASingleLine &&
656 Line.First->is(tok::kw_if))
657 return 0;
658 if (!Style.AllowShortLoopsOnASingleLine &&
659 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
660 return 0;
661 // FIXME: Consider an option to allow short exception handling clauses on
662 // a single line.
663 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
664 return 0;
665 }
666
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000667 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000669 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 Tok->getNextNonComment()->is(tok::semi))) {
671 // We merge empty blocks even if the line exceeds the column limit.
672 Tok->SpacesRequiredBefore = 0;
673 Tok->CanBreakBefore = true;
674 return 1;
675 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000676 // We don't merge short records.
677 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
678 return 0;
679
Daniel Jasper56f8b432013-11-06 23:12:09 +0000680 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000681 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000682 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000683 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000684
685 if (!nextTwoLinesFitInto(I, Limit))
686 return 0;
687
688 // Second, check that the next line does not contain any braces - if it
689 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000690 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000691 return 0;
692 do {
Daniel Jasper39485162014-05-22 09:00:33 +0000693 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000694 !Style.AllowShortBlocksOnASingleLine)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000695 return 0;
696 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000697 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000698
Daniel Jasper79dffb42014-05-07 09:48:30 +0000699 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000701 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000702 return 0;
703
704 return 2;
705 }
706 return 0;
707 }
708
Daniel Jasper64989962014-02-07 13:45:27 +0000709 /// Returns the modified column limit for \p I if it is inside a macro and
710 /// needs a trailing '\'.
711 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000712 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000713 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
714 unsigned Limit) {
715 if (I[0]->InPPDirective && I + 1 != E &&
716 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
717 return Limit < 2 ? 0 : Limit - 2;
718 }
719 return Limit;
720 }
721
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
723 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000724 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
725 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000726 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000727 }
728
Daniel Jasper234379f2013-12-24 13:31:25 +0000729 bool containsMustBreak(const AnnotatedLine *Line) {
730 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
731 if (Tok->MustBreakBefore)
732 return true;
733 }
734 return false;
735 }
736
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 const FormatStyle &Style;
738};
739
Daniel Jasperf7935112012-12-03 18:12:45 +0000740class UnwrappedLineFormatter {
741public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000742 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000743 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000744 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000745 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
746 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000747
Daniel Jasper56f8b432013-11-06 23:12:09 +0000748 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000749 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000750 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000751 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
752 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000753 auto CacheIt = PenaltyCache.find(CacheKey);
754 if (DryRun && CacheIt != PenaltyCache.end())
755 return CacheIt->second;
756
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000757 assert(!Lines.empty());
758 unsigned Penalty = 0;
759 std::vector<int> IndentForLevel;
760 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
761 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000762 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000763 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
764 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000765 I != E; ++I) {
766 const AnnotatedLine &TheLine = **I;
767 const FormatToken *FirstTok = TheLine.First;
768 int Offset = getIndentOffset(*FirstTok);
769
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000770 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000771 unsigned Indent;
772 if (TheLine.InPPDirective) {
773 Indent = TheLine.Level * Style.IndentWidth;
774 } else {
775 while (IndentForLevel.size() <= TheLine.Level)
776 IndentForLevel.push_back(-1);
777 IndentForLevel.resize(TheLine.Level + 1);
778 Indent = getIndent(IndentForLevel, TheLine.Level);
779 }
780 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000781 if (static_cast<int>(Indent) + Offset >= 0)
782 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000783
784 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000785 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000786 if (MergedLines > 0 && Style.ColumnLimit == 0) {
787 // Disallow line merging if there is a break at the start of one of the
788 // input lines.
789 for (unsigned i = 0; i < MergedLines; ++i) {
790 if (I[i + 1]->First->NewlinesBefore > 0)
791 MergedLines = 0;
792 }
793 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000794 if (!DryRun) {
795 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000796 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000797 }
798 }
799 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000800
Daniel Jasper9c199562013-11-28 15:58:55 +0000801 bool FixIndentation =
802 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000803 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000804 if (PreviousLine && PreviousLine->Affected && !DryRun) {
805 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000806 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
807 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
808 /*IndentLevel=*/0, /*Spaces=*/0,
809 /*TargetColumn=*/0);
810 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000811 } else if (TheLine.Type != LT_Invalid &&
812 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000813 if (FirstTok->WhitespaceRange.isValid()) {
814 if (!DryRun)
815 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
816 Indent, TheLine.InPPDirective);
817 } else {
818 Indent = LevelIndent = FirstTok->OriginalColumn;
819 }
820
821 // If everything fits on a single line, just put it there.
822 unsigned ColumnLimit = Style.ColumnLimit;
823 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000824 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000825 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
826 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
827 }
828
829 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
830 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000831 while (State.NextToken) {
832 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000833 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000834 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000835 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000836 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000837 NoColumnLimitFormatter Formatter(Indenter);
838 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000839 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000840 } else {
841 Penalty += format(TheLine, Indent, DryRun);
842 }
843
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000844 if (!TheLine.InPPDirective)
845 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000846 } else if (TheLine.ChildrenAffected) {
847 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000848 } else {
849 // Format the first token if necessary, and notify the WhitespaceManager
850 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000851 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000852 if (Tok == TheLine.First &&
853 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
854 unsigned LevelIndent = Tok->OriginalColumn;
855 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000856 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000857 if ((PreviousLine && PreviousLine->Affected) ||
858 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000859 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
860 TheLine.InPPDirective);
861 } else {
862 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
863 }
864 }
865
866 if (static_cast<int>(LevelIndent) - Offset >= 0)
867 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000868 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000869 IndentForLevel[TheLine.Level] = LevelIndent;
870 } else if (!DryRun) {
871 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
872 }
873 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000874 }
875 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000876 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000877 Tok->Finalized = true;
878 }
879 }
880 PreviousLine = *I;
881 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000882 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000883 return Penalty;
884 }
885
886private:
887 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000888 ///
889 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000890 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
891 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000892 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000893
Daniel Jasperacc33662013-02-08 08:22:00 +0000894 // If the ObjC method declaration does not fit on a line, we should format
895 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000896 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000897 State.Stack.back().BreakBeforeParameter = true;
898
Daniel Jasper4b866272013-02-01 11:00:45 +0000899 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000900 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000901 }
902
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000903 /// \brief An edge in the solution space from \c Previous->State to \c State,
904 /// inserting a newline dependent on the \c NewLine.
905 struct StateNode {
906 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000907 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000908 LineState State;
909 bool NewLine;
910 StateNode *Previous;
911 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000912
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000913 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
914 ///
915 /// In case of equal penalties, we want to prefer states that were inserted
916 /// first. During state generation we make sure that we insert states first
917 /// that break the line as late as possible.
918 typedef std::pair<unsigned, unsigned> OrderedPenalty;
919
920 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
921 /// \c State has the given \c OrderedPenalty.
922 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
923
924 /// \brief The BFS queue type.
925 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
926 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000927
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000928 /// \brief Get the offset of the line relatively to the level.
929 ///
930 /// For example, 'public:' labels in classes are offset by 1 or 2
931 /// characters to the left from their level.
932 int getIndentOffset(const FormatToken &RootToken) {
933 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
934 return Style.AccessModifierOffset;
935 return 0;
936 }
937
938 /// \brief Add a new line and the required indent before the first Token
939 /// of the \c UnwrappedLine if there was no structural parsing error.
940 void formatFirstToken(FormatToken &RootToken,
941 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
942 unsigned Indent, bool InPPDirective) {
943 unsigned Newlines =
944 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
945 // Remove empty lines before "}" where applicable.
946 if (RootToken.is(tok::r_brace) &&
947 (!RootToken.Next ||
948 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
949 Newlines = std::min(Newlines, 1u);
950 if (Newlines == 0 && !RootToken.IsFirst)
951 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000952 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
953 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000954
Daniel Jasper11164bd2014-03-21 12:58:53 +0000955 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000956 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
957 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000958 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000959 Newlines = 1;
960
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000961 // Insert extra new line before access specifiers.
962 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
963 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
964 ++Newlines;
965
966 // Remove empty lines after access specifiers.
967 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
968 Newlines = std::min(1u, Newlines);
969
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000970 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
971 Indent, InPPDirective &&
972 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000973 }
974
975 /// \brief Get the indent of \p Level from \p IndentForLevel.
976 ///
977 /// \p IndentForLevel must contain the indent for the level \c l
978 /// at \p IndentForLevel[l], or a value < 0 if the indent for
979 /// that level is unknown.
980 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
981 if (IndentForLevel[Level] != -1)
982 return IndentForLevel[Level];
983 if (Level == 0)
984 return 0;
985 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
986 }
987
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000988 void join(AnnotatedLine &A, const AnnotatedLine &B) {
989 assert(!A.Last->Next);
990 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000991 if (B.Affected)
992 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000993 A.Last->Next = B.First;
994 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000995 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000996 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
997 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
998 Tok->TotalLength += LengthA;
999 A.Last = Tok;
1000 }
1001 }
1002
1003 unsigned getColumnLimit(bool InPPDirective) const {
1004 // In preprocessor directives reserve two chars for trailing " \"
1005 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1006 }
1007
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001008 struct CompareLineStatePointers {
1009 bool operator()(LineState *obj1, LineState *obj2) const {
1010 return *obj1 < *obj2;
1011 }
1012 };
1013
Daniel Jasper4b866272013-02-01 11:00:45 +00001014 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001015 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001016 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1017 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1018 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001019 /// to a state where all tokens are placed. Returns the penalty.
1020 ///
1021 /// If \p DryRun is \c false, directly applies the changes.
1022 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001023 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001024
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001025 // Increasing count of \c StateNode items we have created. This is used to
1026 // create a deterministic order independent of the container.
1027 unsigned Count = 0;
1028 QueueType Queue;
1029
Daniel Jasper4b866272013-02-01 11:00:45 +00001030 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001031 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001032 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001033 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1034 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001035
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001036 unsigned Penalty = 0;
1037
Daniel Jasper4b866272013-02-01 11:00:45 +00001038 // While not empty, take first element and follow edges.
1039 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001040 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001041 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001042 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001043 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001044 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001045 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001046 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001047
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001048 // Cut off the analysis of certain solutions if the analysis gets too
1049 // complex. See description of IgnoreStackForComparison.
1050 if (Count > 10000)
1051 Node->State.IgnoreStackForComparison = true;
1052
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001053 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001054 // State already examined with lower penalty.
1055 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001056
Manuel Klimek71814b42013-10-11 21:25:45 +00001057 FormatDecision LastFormat = Node->State.NextToken->Decision;
1058 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001059 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001060 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001061 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001062 }
1063
Manuel Klimek71814b42013-10-11 21:25:45 +00001064 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001065 // We were unable to find a solution, do nothing.
1066 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001067 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001068 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001069 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001070
Daniel Jasper4b866272013-02-01 11:00:45 +00001071 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001072 if (!DryRun)
1073 reconstructPath(InitialState, Queue.top().second);
1074
Alexander Kornienko49149672013-05-10 11:56:10 +00001075 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1076 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001077
1078 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001079 }
1080
1081 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001082 std::deque<StateNode *> Path;
1083 // We do not need a break before the initial token.
1084 while (Current->Previous) {
1085 Path.push_front(Current);
1086 Current = Current->Previous;
1087 }
1088 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1089 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001090 unsigned Penalty = 0;
1091 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1092 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1093
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001094 DEBUG({
1095 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001096 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001097 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001098 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001099 }
1100 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001101 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001102 }
1103
Manuel Klimekaf491072013-02-13 10:54:19 +00001104 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001105 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001106 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001107 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001108 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001109 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001110 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001111 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001112 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001113 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001114
1115 StateNode *Node = new (Allocator.Allocate())
1116 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001117 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1118 return;
1119
Daniel Jasperde0328a2013-08-16 11:20:30 +00001120 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001121
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001122 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1123 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001124 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001125
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001126 /// \brief If the \p State's next token is an r_brace closing a nested block,
1127 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001128 ///
1129 /// Returns \c true if all children could be placed successfully and adapts
1130 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1131 /// creates changes using \c Whitespaces.
1132 ///
1133 /// The crucial idea here is that children always get formatted upon
1134 /// encountering the closing brace right after the nested block. Now, if we
1135 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1136 /// \c false), the entire block has to be kept on the same line (which is only
1137 /// possible if it fits on the line, only contains a single statement, etc.
1138 ///
1139 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1140 /// break after the "{", format all lines with correct indentation and the put
1141 /// the closing "}" on yet another new line.
1142 ///
1143 /// This enables us to keep the simple structure of the
1144 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1145 /// break or don't break.
1146 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1147 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001148 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001149 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1150 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1151 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001152 // The previous token does not open a block. Nothing to do. We don't
1153 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001154 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001155
1156 if (NewLine) {
Daniel Jasperb16b9692014-05-21 12:51:23 +00001157 int AdditionalIndent = 0;
1158 if (State.Stack.size() < 2 ||
1159 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1160 AdditionalIndent = State.Stack.back().Indent -
1161 Previous.Children[0]->Level * Style.IndentWidth;
1162 }
1163
Daniel Jasper9c199562013-11-28 15:58:55 +00001164 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1165 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001166 return true;
1167 }
1168
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001169 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001170 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001171 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001172
Daniel Jasper21397a32014-04-09 12:21:48 +00001173 // Cannot merge into one line if this line ends on a comment.
1174 if (Previous.is(tok::comment))
1175 return false;
1176
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001177 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001178 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001179 return false;
1180
Daniel Jasper98583d52014-04-15 08:28:06 +00001181 // If the child line exceeds the column limit, we wouldn't want to merge it.
1182 // We add +2 for the trailing " }".
1183 if (Style.ColumnLimit > 0 &&
1184 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1185 Style.ColumnLimit)
1186 return false;
1187
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001188 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001189 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001190 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001191 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001192 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001193 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001194 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001195
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001196 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001197 return true;
1198 }
1199
Daniel Jasperde0328a2013-08-16 11:20:30 +00001200 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001201 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001202 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001203 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001204
1205 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001206
1207 // Cache to store the penalty of formatting a vector of AnnotatedLines
1208 // starting from a specific additional offset. Improves performance if there
1209 // are many nested blocks.
1210 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1211 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001212};
1213
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001214class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001215public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001216 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001217 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001218 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1219 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1220 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001221 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001222 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001223
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001224 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001225 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1226 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001227 }
1228
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001229 ArrayRef<FormatToken *> lex() {
1230 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001231 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001232 do {
1233 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001234 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001235 if (Tokens.back()->NewlinesBefore > 0)
1236 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001237 } while (Tokens.back()->Tok.isNot(tok::eof));
1238 return Tokens;
1239 }
1240
1241 IdentifierTable &getIdentTable() { return IdentTable; }
1242
1243private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001244 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001245 if (tryMerge_TMacro())
1246 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001247 if (tryMergeConflictMarkers())
1248 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001249
1250 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001251 if (tryMergeEscapeSequence())
1252 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001253 if (tryMergeJSRegexLiteral())
1254 return;
1255
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001256 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1257 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1258 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1259 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001260 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001261 // FIXME: We probably need to change token type to mimic operator with the
1262 // correct priority.
1263 if (tryMergeTokens(JSIdentity))
1264 return;
1265 if (tryMergeTokens(JSNotIdentity))
1266 return;
1267 if (tryMergeTokens(JSShiftEqual))
1268 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001269 if (tryMergeTokens(JSRightArrow))
1270 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001271 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001272 }
1273
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001274 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1275 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001276 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001277
1278 SmallVectorImpl<FormatToken *>::const_iterator First =
1279 Tokens.end() - Kinds.size();
1280 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001281 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001282 unsigned AddLength = 0;
1283 for (unsigned i = 1; i < Kinds.size(); ++i) {
1284 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1285 First[i]->WhitespaceRange.getEnd())
1286 return false;
1287 AddLength += First[i]->TokenText.size();
1288 }
1289 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1290 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1291 First[0]->TokenText.size() + AddLength);
1292 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001293 return true;
1294 }
1295
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001296 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001297 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001298 bool tryMergeEscapeSequence() {
1299 if (Tokens.size() < 2)
1300 return false;
1301 FormatToken *Previous = Tokens[Tokens.size() - 2];
1302 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1303 Tokens.back()->NewlinesBefore != 0)
1304 return false;
1305 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1306 StringRef Text = Previous->TokenText;
1307 Previous->TokenText =
1308 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1309 Tokens.resize(Tokens.size() - 1);
1310 return true;
1311 }
1312
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001313 // Try to determine whether the current token ends a JavaScript regex literal.
1314 // We heuristically assume that this is a regex literal if we find two
1315 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001316 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1317 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001318 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001319 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001320 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1321 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001322 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001323 unsigned TokenCount = 0;
1324 unsigned LastColumn = Tokens.back()->OriginalColumn;
1325 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1326 ++TokenCount;
1327 if (I[0]->is(tok::slash) && I + 1 != E &&
1328 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1329 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1330 tok::question, tok::kw_return) ||
1331 I[1]->isBinaryOperator())) {
1332 Tokens.resize(Tokens.size() - TokenCount);
1333 Tokens.back()->Tok.setKind(tok::unknown);
1334 Tokens.back()->Type = TT_RegexLiteral;
1335 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1336 return true;
1337 }
1338
1339 // There can't be a newline inside a regex literal.
1340 if (I[0]->NewlinesBefore > 0)
1341 return false;
1342 }
1343 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001344 }
1345
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001346 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001347 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001348 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001349 FormatToken *Last = Tokens.back();
1350 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001351 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001352
1353 FormatToken *String = Tokens[Tokens.size() - 2];
1354 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001355 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001356
1357 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001358 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001359
1360 FormatToken *Macro = Tokens[Tokens.size() - 4];
1361 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001362 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001363
1364 const char *Start = Macro->TokenText.data();
1365 const char *End = Last->TokenText.data() + Last->TokenText.size();
1366 String->TokenText = StringRef(Start, End - Start);
1367 String->IsFirst = Macro->IsFirst;
1368 String->LastNewlineOffset = Macro->LastNewlineOffset;
1369 String->WhitespaceRange = Macro->WhitespaceRange;
1370 String->OriginalColumn = Macro->OriginalColumn;
1371 String->ColumnWidth = encoding::columnWidthWithTabs(
1372 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1373
1374 Tokens.pop_back();
1375 Tokens.pop_back();
1376 Tokens.pop_back();
1377 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001378 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001379 }
1380
Manuel Klimek68b03042014-04-14 09:14:11 +00001381 bool tryMergeConflictMarkers() {
1382 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1383 return false;
1384
1385 // Conflict lines look like:
1386 // <marker> <text from the vcs>
1387 // For example:
1388 // >>>>>>> /file/in/file/system at revision 1234
1389 //
1390 // We merge all tokens in a line that starts with a conflict marker
1391 // into a single token with a special token type that the unwrapped line
1392 // parser will use to correctly rebuild the underlying code.
1393
1394 FileID ID;
1395 // Get the position of the first token in the line.
1396 unsigned FirstInLineOffset;
1397 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1398 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1399 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1400 // Calculate the offset of the start of the current line.
1401 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1402 if (LineOffset == StringRef::npos) {
1403 LineOffset = 0;
1404 } else {
1405 ++LineOffset;
1406 }
1407
1408 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1409 StringRef LineStart;
1410 if (FirstSpace == StringRef::npos) {
1411 LineStart = Buffer.substr(LineOffset);
1412 } else {
1413 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1414 }
1415
1416 TokenType Type = TT_Unknown;
1417 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1418 Type = TT_ConflictStart;
1419 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1420 LineStart == "====") {
1421 Type = TT_ConflictAlternative;
1422 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1423 Type = TT_ConflictEnd;
1424 }
1425
1426 if (Type != TT_Unknown) {
1427 FormatToken *Next = Tokens.back();
1428
1429 Tokens.resize(FirstInLineIndex + 1);
1430 // We do not need to build a complete token here, as we will skip it
1431 // during parsing anyway (as we must not touch whitespace around conflict
1432 // markers).
1433 Tokens.back()->Type = Type;
1434 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1435
1436 Tokens.push_back(Next);
1437 return true;
1438 }
1439
1440 return false;
1441 }
1442
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001443 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001444 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001445 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001446 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001447 Token Greater = FormatTok->Tok;
1448 FormatTok = new (Allocator.Allocate()) FormatToken;
1449 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001450 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001451 FormatTok->Tok.getLocation().getLocWithOffset(1);
1452 FormatTok->WhitespaceRange =
1453 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001454 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001455 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001456 GreaterStashed = false;
1457 return FormatTok;
1458 }
1459
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001460 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001461 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001462 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001463 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001464 FormatTok->IsFirst = IsFirstToken;
1465 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001466
1467 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001468 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001469 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001470 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1471 switch (FormatTok->TokenText[i]) {
1472 case '\n':
1473 ++FormatTok->NewlinesBefore;
1474 // FIXME: This is technically incorrect, as it could also
1475 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001476 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1477 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1478 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001479 FormatTok->HasUnescapedNewline = true;
1480 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1481 Column = 0;
1482 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001483 case '\r':
1484 case '\f':
1485 case '\v':
1486 Column = 0;
1487 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001488 case ' ':
1489 ++Column;
1490 break;
1491 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001492 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001493 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001494 case '\\':
1495 ++Column;
1496 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1497 FormatTok->TokenText[i + 1] != '\n'))
1498 FormatTok->Type = TT_ImplicitStringLiteral;
1499 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001500 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001501 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001502 ++Column;
1503 break;
1504 }
1505 }
1506
Daniel Jasper877615c2013-10-11 19:45:02 +00001507 if (FormatTok->Type == TT_ImplicitStringLiteral)
1508 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001509 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001510
Daniel Jasper8369aa52013-07-16 20:28:33 +00001511 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001512 }
Manuel Klimekef920692013-01-07 07:56:50 +00001513
Manuel Klimek1abf7892013-01-04 23:34:14 +00001514 // In case the token starts with escaped newlines, we want to
1515 // take them into account as whitespace - this pattern is quite frequent
1516 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001517 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001518 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1519 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001520 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001521 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001522 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001523 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001524 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001525
1526 FormatTok->WhitespaceRange = SourceRange(
1527 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1528
Manuel Klimek31c85922013-08-29 15:21:40 +00001529 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001530
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001531 TrailingWhitespace = 0;
1532 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001533 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001534 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001535 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001536 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001537 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001538 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001539 FormatTok->Tok.setIdentifierInfo(&Info);
1540 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001541 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001542 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001543 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001544 GreaterStashed = true;
1545 }
1546
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001547 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001548
Alexander Kornienko39856b72013-09-10 09:38:25 +00001549 StringRef Text = FormatTok->TokenText;
1550 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001551 if (FirstNewlinePos == StringRef::npos) {
1552 // FIXME: ColumnWidth actually depends on the start column, we need to
1553 // take this into account when the token is moved.
1554 FormatTok->ColumnWidth =
1555 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1556 Column += FormatTok->ColumnWidth;
1557 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001558 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001559 // FIXME: ColumnWidth actually depends on the start column, we need to
1560 // take this into account when the token is moved.
1561 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1562 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1563
Alexander Kornienko39856b72013-09-10 09:38:25 +00001564 // The last line of the token always starts in column 0.
1565 // Thus, the length can be precomputed even in the presence of tabs.
1566 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1567 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1568 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001569 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001570 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001571
Daniel Jaspere1e43192014-04-01 12:55:11 +00001572 FormatTok->IsForEachMacro =
1573 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1574 FormatTok->Tok.getIdentifierInfo());
1575
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001576 return FormatTok;
1577 }
1578
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001579 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001580 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001581 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001582 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001583 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001584 Lexer &Lex;
1585 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001586 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001587 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001588 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001589 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001590 // Index (in 'Tokens') of the last token that starts a new line.
1591 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001592 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001593 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001594
Daniel Jasper8369aa52013-07-16 20:28:33 +00001595 void readRawToken(FormatToken &Tok) {
1596 Lex.LexFromRawLexer(Tok.Tok);
1597 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1598 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001599 // For formatting, treat unterminated string literals like normal string
1600 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001601 if (Tok.is(tok::unknown)) {
1602 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1603 Tok.Tok.setKind(tok::string_literal);
1604 Tok.IsUnterminatedLiteral = true;
1605 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1606 Tok.TokenText == "''") {
1607 Tok.Tok.setKind(tok::char_constant);
1608 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001609 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001610 }
1611};
1612
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001613static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1614 switch (Language) {
1615 case FormatStyle::LK_Cpp:
1616 return "C++";
1617 case FormatStyle::LK_JavaScript:
1618 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001619 case FormatStyle::LK_Proto:
1620 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001621 default:
1622 return "Unknown";
1623 }
1624}
1625
Daniel Jasperf7935112012-12-03 18:12:45 +00001626class Formatter : public UnwrappedLineConsumer {
1627public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001628 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001629 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001630 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001631 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001632 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001633 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001634 DEBUG(llvm::dbgs() << "File encoding: "
1635 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1636 : "unknown")
1637 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001638 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1639 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001640 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001641
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001642 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001643 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001644 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001645
1646 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001647 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001648 assert(UnwrappedLines.rbegin()->empty());
1649 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1650 ++Run) {
1651 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1652 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1653 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1654 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1655 }
1656 tooling::Replacements RunResult =
1657 format(AnnotatedLines, StructuralError, Tokens);
1658 DEBUG({
1659 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1660 for (tooling::Replacements::iterator I = RunResult.begin(),
1661 E = RunResult.end();
1662 I != E; ++I) {
1663 llvm::dbgs() << I->toString() << "\n";
1664 }
1665 });
1666 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1667 delete AnnotatedLines[i];
1668 }
1669 Result.insert(RunResult.begin(), RunResult.end());
1670 Whitespaces.reset();
1671 }
1672 return Result;
1673 }
1674
1675 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1676 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001677 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001678 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001679 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001680 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001681 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001682 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001683 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001684 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001685 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001686
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001687 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001688 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1689 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001690 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001691 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001692 return Whitespaces.generateReplacements();
1693 }
1694
1695private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001696 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001697 // Returns \c true if at least one line between I and E or one of their
1698 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001699 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1700 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1701 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001702 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001703 while (I != E) {
1704 AnnotatedLine *Line = *I;
1705 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1706
1707 // If a line is part of a preprocessor directive, it needs to be formatted
1708 // if any token within the directive is affected.
1709 if (Line->InPPDirective) {
1710 FormatToken *Last = Line->Last;
1711 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1712 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1713 Last = (*PPEnd)->Last;
1714 ++PPEnd;
1715 }
1716
1717 if (affectsTokenRange(*Line->First, *Last,
1718 /*IncludeLeadingNewlines=*/false)) {
1719 SomeLineAffected = true;
1720 markAllAsAffected(I, PPEnd);
1721 }
1722 I = PPEnd;
1723 continue;
1724 }
1725
Daniel Jasper38c82402013-11-29 09:27:43 +00001726 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001727 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001728
Daniel Jasper38c82402013-11-29 09:27:43 +00001729 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001730 ++I;
1731 }
1732 return SomeLineAffected;
1733 }
1734
Daniel Jasper9c199562013-11-28 15:58:55 +00001735 // Determines whether 'Line' is affected by the SourceRanges given as input.
1736 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001737 bool nonPPLineAffected(AnnotatedLine *Line,
1738 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001739 bool SomeLineAffected = false;
1740 Line->ChildrenAffected =
1741 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1742 if (Line->ChildrenAffected)
1743 SomeLineAffected = true;
1744
1745 // Stores whether one of the line's tokens is directly affected.
1746 bool SomeTokenAffected = false;
1747 // Stores whether we need to look at the leading newlines of the next token
1748 // in order to determine whether it was affected.
1749 bool IncludeLeadingNewlines = false;
1750
1751 // Stores whether the first child line of any of this line's tokens is
1752 // affected.
1753 bool SomeFirstChildAffected = false;
1754
1755 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1756 // Determine whether 'Tok' was affected.
1757 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1758 SomeTokenAffected = true;
1759
1760 // Determine whether the first child of 'Tok' was affected.
1761 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1762 SomeFirstChildAffected = true;
1763
1764 IncludeLeadingNewlines = Tok->Children.empty();
1765 }
1766
1767 // Was this line moved, i.e. has it previously been on the same line as an
1768 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001769 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1770 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001771
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001772 bool IsContinuedComment =
1773 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1774 Line->First->NewlinesBefore < 2 && PreviousLine &&
1775 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001776
1777 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1778 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001779 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001780 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001781 }
1782 return SomeLineAffected;
1783 }
1784
Daniel Jasper5500f612013-11-25 11:08:59 +00001785 // Marks all lines between I and E as well as all their children as affected.
1786 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1787 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1788 while (I != E) {
1789 (*I)->Affected = true;
1790 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1791 ++I;
1792 }
1793 }
1794
1795 // Returns true if the range from 'First' to 'Last' intersects with one of the
1796 // input ranges.
1797 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1798 bool IncludeLeadingNewlines) {
1799 SourceLocation Start = First.WhitespaceRange.getBegin();
1800 if (!IncludeLeadingNewlines)
1801 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001802 SourceLocation End = Last.getStartOfNonWhitespace();
1803 if (Last.TokenText.size() > 0)
1804 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001805 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1806 return affectsCharSourceRange(Range);
1807 }
1808
1809 // Returns true if one of the input ranges intersect the leading empty lines
1810 // before 'Tok'.
1811 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1812 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1813 Tok.WhitespaceRange.getBegin(),
1814 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1815 return affectsCharSourceRange(EmptyLineRange);
1816 }
1817
1818 // Returns true if 'Range' intersects with one of the input ranges.
1819 bool affectsCharSourceRange(const CharSourceRange &Range) {
1820 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1821 E = Ranges.end();
1822 I != E; ++I) {
1823 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1824 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1825 return true;
1826 }
1827 return false;
1828 }
1829
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001830 static bool inputUsesCRLF(StringRef Text) {
1831 return Text.count('\r') * 2 > Text.count('\n');
1832 }
1833
Manuel Klimek71814b42013-10-11 21:25:45 +00001834 void
1835 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001836 unsigned CountBoundToVariable = 0;
1837 unsigned CountBoundToType = 0;
1838 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001839 bool HasBinPackedFunction = false;
1840 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001841 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001842 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001843 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001844 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001845 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001846 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001847 bool SpacesBefore =
1848 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1849 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1850 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001851 if (SpacesBefore && !SpacesAfter)
1852 ++CountBoundToVariable;
1853 else if (!SpacesBefore && SpacesAfter)
1854 ++CountBoundToType;
1855 }
1856
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001857 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1858 if (Tok->is(tok::coloncolon) &&
1859 Tok->Previous->Type == TT_TemplateOpener)
1860 HasCpp03IncompatibleFormat = true;
1861 if (Tok->Type == TT_TemplateCloser &&
1862 Tok->Previous->Type == TT_TemplateCloser)
1863 HasCpp03IncompatibleFormat = true;
1864 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001865
1866 if (Tok->PackingKind == PPK_BinPacked)
1867 HasBinPackedFunction = true;
1868 if (Tok->PackingKind == PPK_OnePerLine)
1869 HasOnePerLineFunction = true;
1870
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001871 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001872 }
1873 }
1874 if (Style.DerivePointerBinding) {
1875 if (CountBoundToType > CountBoundToVariable)
1876 Style.PointerBindsToType = true;
1877 else if (CountBoundToType < CountBoundToVariable)
1878 Style.PointerBindsToType = false;
1879 }
1880 if (Style.Standard == FormatStyle::LS_Auto) {
1881 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1882 : FormatStyle::LS_Cpp03;
1883 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001884 BinPackInconclusiveFunctions =
1885 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001886 }
1887
Craig Topperfb6b25b2014-03-15 04:29:04 +00001888 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001889 assert(!UnwrappedLines.empty());
1890 UnwrappedLines.back().push_back(TheLine);
1891 }
1892
Craig Topperfb6b25b2014-03-15 04:29:04 +00001893 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001894 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001895 }
1896
1897 FormatStyle Style;
1898 Lexer &Lex;
1899 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001900 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001901 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001902 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001903
1904 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001905 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001906};
1907
Craig Topperaf35e852013-06-30 22:29:28 +00001908} // end anonymous namespace
1909
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001910tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1911 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001912 std::vector<CharSourceRange> Ranges) {
1913 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001914 return formatter.format();
1915}
1916
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001917tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1918 std::vector<tooling::Range> Ranges,
1919 StringRef FileName) {
1920 FileManager Files((FileSystemOptions()));
1921 DiagnosticsEngine Diagnostics(
1922 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1923 new DiagnosticOptions);
1924 SourceManager SourceMgr(Diagnostics, Files);
1925 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1926 const clang::FileEntry *Entry =
1927 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1928 SourceMgr.overrideFileContents(Entry, Buf);
1929 FileID ID =
1930 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001931 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1932 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001933 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1934 std::vector<CharSourceRange> CharRanges;
1935 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1936 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1937 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1938 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1939 }
1940 return reformat(Style, Lex, SourceMgr, CharRanges);
1941}
1942
Alexander Kornienko1e808872013-06-28 12:51:24 +00001943LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001944 LangOptions LangOpts;
1945 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001946 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001947 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001948 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00001949 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001950 LangOpts.Bool = 1;
1951 LangOpts.ObjC1 = 1;
1952 LangOpts.ObjC2 = 1;
1953 return LangOpts;
1954}
1955
Edwin Vaned544aa72013-09-30 13:31:48 +00001956const char *StyleOptionHelpDescription =
1957 "Coding style, currently supports:\n"
1958 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1959 "Use -style=file to load style configuration from\n"
1960 ".clang-format file located in one of the parent\n"
1961 "directories of the source file (or current\n"
1962 "directory for stdin).\n"
1963 "Use -style=\"{key: value, ...}\" to set specific\n"
1964 "parameters, e.g.:\n"
1965 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1966
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001967static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001968 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001969 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001970 } else if (FileName.endswith_lower(".proto") ||
1971 FileName.endswith_lower(".protodevel")) {
1972 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001973 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001974 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001975}
1976
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001977FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1978 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001979 FormatStyle Style = getLLVMStyle();
1980 Style.Language = getLanguageByFileName(FileName);
1981 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001982 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1983 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001984 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001985 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001986
1987 if (StyleName.startswith("{")) {
1988 // Parse YAML/JSON style from the command line.
1989 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001990 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1991 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001992 }
1993 return Style;
1994 }
1995
1996 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001997 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001998 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1999 << " style\n";
2000 return Style;
2001 }
2002
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002003 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002004 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002005 SmallString<128> Path(FileName);
2006 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002007 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002008 Directory = llvm::sys::path::parent_path(Directory)) {
2009 if (!llvm::sys::fs::is_directory(Directory))
2010 continue;
2011 SmallString<128> ConfigFile(Directory);
2012
2013 llvm::sys::path::append(ConfigFile, ".clang-format");
2014 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2015 bool IsFile = false;
2016 // Ignore errors from is_regular_file: we only need to know if we can read
2017 // the file or not.
2018 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2019
2020 if (!IsFile) {
2021 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2022 ConfigFile = Directory;
2023 llvm::sys::path::append(ConfigFile, "_clang-format");
2024 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2025 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2026 }
2027
2028 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002029 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00002030 if (llvm::error_code ec =
2031 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002032 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002033 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002034 }
2035 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002036 if (ec == llvm::errc::not_supported) {
2037 if (!UnsuitableConfigFiles.empty())
2038 UnsuitableConfigFiles.append(", ");
2039 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002040 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002041 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002042 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2043 << "\n";
2044 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002045 }
2046 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2047 return Style;
2048 }
2049 }
2050 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2051 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002052 if (!UnsuitableConfigFiles.empty()) {
2053 llvm::errs() << "Configuration file(s) do(es) not support "
2054 << getLanguageName(Style.Language) << ": "
2055 << UnsuitableConfigFiles << "\n";
2056 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002057 return Style;
2058}
2059
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002060} // namespace format
2061} // namespace clang