blob: 9443a60aa6d80046582d84d0aa8b845322632ffd [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper6b2afe42013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Edwin Vanef4e12c82013-09-30 13:31:48 +000030#include "llvm/Support/Path.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod71ec162013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000040 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000041 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000042 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000043 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
44 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
45 }
46};
47
Daniel Jasper1fb8d882013-05-14 09:30:02 +000048template <>
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000049struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +000050 static void enumeration(IO &IO,
51 clang::format::FormatStyle::UseTabStyle &Value) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000052 IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never);
53 IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never);
54 IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always);
55 IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always);
56 IO.enumCase(Value, "ForIndentation",
57 clang::format::FormatStyle::UT_ForIndentation);
58 }
59};
60
61template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000062struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
63 static void
64 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
65 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
66 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
67 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000068 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000069 }
70};
71
Daniel Jaspereff18b92013-07-31 23:16:02 +000072template <>
73struct ScalarEnumerationTraits<
74 clang::format::FormatStyle::NamespaceIndentationKind> {
75 static void
76 enumeration(IO &IO,
77 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
78 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
79 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
80 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
81 }
82};
83
Alexander Kornienkod71ec162013-05-07 15:32:14 +000084template <> struct MappingTraits<clang::format::FormatStyle> {
85 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000086 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000087 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
88 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000089 ArrayRef<StringRef> Styles(StylesArray);
90 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
91 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000092 clang::format::FormatStyle PredefinedStyle;
93 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
94 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000095 IO.mapOptional("# BasedOnStyle", StyleName);
96 break;
97 }
98 }
99 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 StringRef BasedOnStyle;
101 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000102 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000103 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
104 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
105 return;
106 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000107 }
108
109 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +0000110 IO.mapOptional("ConstructorInitializerIndentWidth",
111 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000112 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000113 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
115 Style.AllowAllParametersOfDeclarationOnNextLine);
116 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
117 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000118 IO.mapOptional("AllowShortLoopsOnASingleLine",
119 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000120 IO.mapOptional("AlwaysBreakTemplateDeclarations",
121 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000122 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
123 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000124 IO.mapOptional("BreakBeforeBinaryOperators",
125 Style.BreakBeforeBinaryOperators);
126 IO.mapOptional("BreakConstructorInitializersBeforeComma",
127 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000128 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
129 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
130 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
131 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
132 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000133 IO.mapOptional("ExperimentalAutoDetectBinPacking",
134 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000135 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
136 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000137 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000138 IO.mapOptional("ObjCSpaceBeforeProtocolList",
139 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper47066e42013-10-25 14:29:37 +0000140 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
141 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000142 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
143 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000144 IO.mapOptional("PenaltyBreakFirstLessLess",
145 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000146 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
147 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
148 Style.PenaltyReturnTypeOnItsOwnLine);
149 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
150 IO.mapOptional("SpacesBeforeTrailingComments",
151 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000152 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000153 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000154 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000155 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000156 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000157 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000158 IO.mapOptional("IndentFunctionDeclarationAfterType",
159 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000160 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000161 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000162 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000163 IO.mapOptional("SpacesInCStyleCastParentheses",
164 Style.SpacesInCStyleCastParentheses);
165 IO.mapOptional("SpaceAfterControlStatementKeyword",
166 Style.SpaceAfterControlStatementKeyword);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000167 IO.mapOptional("SpaceBeforeAssignmentOperators",
168 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000169 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000170 }
171};
172}
173}
174
Daniel Jasperbac016b2012-12-03 18:12:45 +0000175namespace clang {
176namespace format {
177
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000178void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000179 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000180 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000181 Style.PenaltyBreakString = 1000;
182 Style.PenaltyExcessCharacter = 1000000;
183}
184
Daniel Jasperbac016b2012-12-03 18:12:45 +0000185FormatStyle getLLVMStyle() {
186 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000187 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000188 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000189 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000190 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000191 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000192 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000193 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000194 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000195 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000196 LLVMStyle.BreakBeforeBinaryOperators = false;
197 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
198 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000199 LLVMStyle.ColumnLimit = 80;
200 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000201 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000202 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000203 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000204 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000205 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000206 LLVMStyle.IndentFunctionDeclarationAfterType = false;
207 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000208 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000209 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000210 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000211 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000212 LLVMStyle.PointerBindsToType = false;
213 LLVMStyle.SpacesBeforeTrailingComments = 1;
214 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000215 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000216 LLVMStyle.SpacesInParentheses = false;
217 LLVMStyle.SpaceInEmptyParentheses = false;
218 LLVMStyle.SpacesInCStyleCastParentheses = false;
219 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000220 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000221 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000222 LLVMStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000223
224 setDefaultPenalties(LLVMStyle);
225 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper47066e42013-10-25 14:29:37 +0000226 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000227
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228 return LLVMStyle;
229}
230
231FormatStyle getGoogleStyle() {
232 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000233 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000234 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000235 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000236 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000237 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000238 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000239 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000240 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000241 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000242 GoogleStyle.BreakBeforeBinaryOperators = false;
243 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
244 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000245 GoogleStyle.ColumnLimit = 80;
246 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000247 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000248 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000249 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000250 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000251 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000252 GoogleStyle.IndentFunctionDeclarationAfterType = true;
253 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000254 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000255 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000256 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000257 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000258 GoogleStyle.PointerBindsToType = true;
259 GoogleStyle.SpacesBeforeTrailingComments = 2;
260 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000261 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000262 GoogleStyle.SpacesInParentheses = false;
263 GoogleStyle.SpaceInEmptyParentheses = false;
264 GoogleStyle.SpacesInCStyleCastParentheses = false;
265 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000266 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000267 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000268 GoogleStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000269
270 setDefaultPenalties(GoogleStyle);
271 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper47066e42013-10-25 14:29:37 +0000272 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000273
Daniel Jasperbac016b2012-12-03 18:12:45 +0000274 return GoogleStyle;
275}
276
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000277FormatStyle getChromiumStyle() {
278 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000279 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000280 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000281 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000282 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000283 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000284 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000285 return ChromiumStyle;
286}
287
Alexander Kornienkofb594862013-05-06 14:11:27 +0000288FormatStyle getMozillaStyle() {
289 FormatStyle MozillaStyle = getLLVMStyle();
290 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
291 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
292 MozillaStyle.DerivePointerBinding = true;
293 MozillaStyle.IndentCaseLabels = true;
294 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
295 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
296 MozillaStyle.PointerBindsToType = true;
297 return MozillaStyle;
298}
299
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000300FormatStyle getWebKitStyle() {
301 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000302 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000303 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000304 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000305 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000306 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000307 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000308 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000309 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000310 Style.PointerBindsToType = true;
311 return Style;
312}
313
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000314bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000315 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000316 *Style = getLLVMStyle();
317 else if (Name.equals_lower("chromium"))
318 *Style = getChromiumStyle();
319 else if (Name.equals_lower("mozilla"))
320 *Style = getMozillaStyle();
321 else if (Name.equals_lower("google"))
322 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000323 else if (Name.equals_lower("webkit"))
324 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000325 else
326 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000327
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000328 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000329}
330
331llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000332 if (Text.trim().empty())
333 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000334 llvm::yaml::Input Input(Text);
335 Input >> *Style;
336 return Input.error();
337}
338
339std::string configurationAsText(const FormatStyle &Style) {
340 std::string Text;
341 llvm::raw_string_ostream Stream(Text);
342 llvm::yaml::Output Output(Stream);
343 // We use the same mapping method for input and output, so we need a non-const
344 // reference here.
345 FormatStyle NonConstStyle = Style;
346 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000347 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000348}
349
Craig Topper83f81d72013-06-30 22:29:28 +0000350namespace {
351
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000352class NoColumnLimitFormatter {
353public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000354 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000355
356 /// \brief Formats the line starting at \p State, simply keeping all of the
357 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000358 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000359 LineState State =
360 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000361 while (State.NextToken != NULL) {
362 bool Newline =
363 Indenter->mustBreak(State) ||
364 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
365 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
366 }
367 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000368
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000369private:
370 ContinuationIndenter *Indenter;
371};
372
Daniel Jasper4281d732013-11-06 23:12:09 +0000373class LineJoiner {
374public:
375 LineJoiner(const FormatStyle &Style) : Style(Style) {}
376
377 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
378 unsigned
379 tryFitMultipleLinesInOne(unsigned Indent,
380 SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
381 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
382 // We can never merge stuff if there are trailing line comments.
383 AnnotatedLine *TheLine = *I;
384 if (TheLine->Last->Type == TT_LineComment)
385 return 0;
386
387 if (Indent > Style.ColumnLimit)
388 return 0;
389
390 unsigned Limit = Style.ColumnLimit - Indent;
391 // If we already exceed the column limit, we set 'Limit' to 0. The different
392 // tryMerge..() functions can then decide whether to still do merging.
393 Limit = TheLine->Last->TotalLength > Limit
394 ? 0
395 : Limit - TheLine->Last->TotalLength;
396
397 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
398 return 0;
399
400 if (TheLine->Last->is(tok::l_brace)) {
401 return tryMergeSimpleBlock(I, E, Limit);
402 } else if (Style.AllowShortIfStatementsOnASingleLine &&
403 TheLine->First->is(tok::kw_if)) {
404 return tryMergeSimpleControlStatement(I, E, Limit);
405 } else if (Style.AllowShortLoopsOnASingleLine &&
406 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
407 return tryMergeSimpleControlStatement(I, E, Limit);
408 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
409 TheLine->First->IsFirst)) {
410 return tryMergeSimplePPDirective(I, E, Limit);
411 }
412 return 0;
413 }
414
415private:
416 unsigned
417 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
418 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
419 unsigned Limit) {
420 if (Limit == 0)
421 return 0;
422 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
423 return 0;
424 if (I + 2 != E && (*(I + 2))->InPPDirective &&
425 !(*(I + 2))->First->HasUnescapedNewline)
426 return 0;
427 if (1 + (*(I + 1))->Last->TotalLength > Limit)
428 return 0;
429 return 1;
430 }
431
432 unsigned tryMergeSimpleControlStatement(
433 SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
434 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
435 if (Limit == 0)
436 return 0;
437 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
438 (*(I + 1))->First->is(tok::l_brace))
439 return 0;
440 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
441 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
442 return 0;
443 AnnotatedLine &Line = **I;
444 if (Line.Last->isNot(tok::r_paren))
445 return 0;
446 if (1 + (*(I + 1))->Last->TotalLength > Limit)
447 return 0;
448 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
449 tok::kw_while) ||
450 (*(I + 1))->First->Type == TT_LineComment)
451 return 0;
452 // Only inline simple if's (no nested if or else).
453 if (I + 2 != E && Line.First->is(tok::kw_if) &&
454 (*(I + 2))->First->is(tok::kw_else))
455 return 0;
456 return 1;
457 }
458
459 unsigned
460 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
461 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
462 unsigned Limit) {
463 // No merging if the brace already is on the next line.
464 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
465 return 0;
466
467 // First, check that the current line allows merging. This is the case if
468 // we're not in a control flow statement and the last token is an opening
469 // brace.
470 AnnotatedLine &Line = **I;
471 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
472 tok::kw_else, tok::kw_try, tok::kw_catch,
473 tok::kw_for,
474 // This gets rid of all ObjC @ keywords and methods.
475 tok::at, tok::minus, tok::plus))
476 return 0;
477
478 FormatToken *Tok = (*(I + 1))->First;
479 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
480 (Tok->getNextNonComment() == NULL ||
481 Tok->getNextNonComment()->is(tok::semi))) {
482 // We merge empty blocks even if the line exceeds the column limit.
483 Tok->SpacesRequiredBefore = 0;
484 Tok->CanBreakBefore = true;
485 return 1;
486 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
487 // Check that we still have three lines and they fit into the limit.
488 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid)
489 return 0;
490
491 if (!nextTwoLinesFitInto(I, Limit))
492 return 0;
493
494 // Second, check that the next line does not contain any braces - if it
495 // does, readability declines when putting it into a single line.
496 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
497 return 0;
498 do {
499 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
500 return 0;
501 Tok = Tok->Next;
502 } while (Tok != NULL);
503
504 // Last, check that the third line contains a single closing brace.
505 Tok = (*(I + 2))->First;
506 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
507 Tok->MustBreakBefore)
508 return 0;
509
510 return 2;
511 }
512 return 0;
513 }
514
515 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
516 unsigned Limit) {
517 return 1 + (*(I + 1))->Last->TotalLength + 1 +
518 (*(I + 2))->Last->TotalLength <=
519 Limit;
520 }
521
522 const FormatStyle &Style;
523};
524
Daniel Jasperbac016b2012-12-03 18:12:45 +0000525class UnwrappedLineFormatter {
526public:
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000527 UnwrappedLineFormatter(SourceManager &SourceMgr,
528 SmallVectorImpl<CharSourceRange> &Ranges,
529 ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000530 WhitespaceManager *Whitespaces,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000531 const FormatStyle &Style)
532 : SourceMgr(SourceMgr), Ranges(Ranges), Indenter(Indenter),
Daniel Jasper4281d732013-11-06 23:12:09 +0000533 Whitespaces(Whitespaces), Style(Style), Joiner(Style) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000534
Daniel Jasper4281d732013-11-06 23:12:09 +0000535 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000536 int AdditionalIndent = 0) {
537 assert(!Lines.empty());
538 unsigned Penalty = 0;
539 std::vector<int> IndentForLevel;
540 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
541 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
542 bool PreviousLineWasTouched = false;
543 const AnnotatedLine *PreviousLine = NULL;
544 bool FormatPPDirective = false;
Daniel Jasper4281d732013-11-06 23:12:09 +0000545 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
546 E = Lines.end();
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000547 I != E; ++I) {
548 const AnnotatedLine &TheLine = **I;
549 const FormatToken *FirstTok = TheLine.First;
550 int Offset = getIndentOffset(*FirstTok);
551
552 // Check whether this line is part of a formatted preprocessor directive.
553 if (FirstTok->HasUnescapedNewline)
554 FormatPPDirective = false;
555 if (!FormatPPDirective && TheLine.InPPDirective &&
556 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
557 FormatPPDirective = true;
558
559 // Determine indent and try to merge multiple unwrapped lines.
560 while (IndentForLevel.size() <= TheLine.Level)
561 IndentForLevel.push_back(-1);
562 IndentForLevel.resize(TheLine.Level + 1);
563 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
564 if (static_cast<int>(Indent) + Offset >= 0)
565 Indent += Offset;
Daniel Jasper4281d732013-11-06 23:12:09 +0000566 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
567 if (!DryRun) {
568 for (unsigned i = 0; i < MergedLines; ++i) {
569 join(**(I + i), **(I + i + 1));
570 }
571 }
572 I += MergedLines;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000573
574 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
575 if (TheLine.First->is(tok::eof)) {
576 if (PreviousLineWasTouched && !DryRun) {
577 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
578 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
579 /*IndentLevel=*/0, /*Spaces=*/0,
580 /*TargetColumn=*/0);
581 }
582 } else if (TheLine.Type != LT_Invalid &&
583 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
584 unsigned LevelIndent =
585 getIndent(IndentForLevel, TheLine.Level);
586 if (FirstTok->WhitespaceRange.isValid()) {
587 if (!DryRun)
588 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
589 Indent, TheLine.InPPDirective);
590 } else {
591 Indent = LevelIndent = FirstTok->OriginalColumn;
592 }
593
594 // If everything fits on a single line, just put it there.
595 unsigned ColumnLimit = Style.ColumnLimit;
596 if (I + 1 != E) {
597 AnnotatedLine *NextLine = *(I + 1);
598 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
599 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
600 }
601
602 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
603 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
604 while (State.NextToken != NULL)
605 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
606 } else if (Style.ColumnLimit == 0) {
607 NoColumnLimitFormatter Formatter(Indenter);
608 if (!DryRun)
609 Formatter.format(Indent, &TheLine);
610 } else {
611 Penalty += format(TheLine, Indent, DryRun);
612 }
613
614 IndentForLevel[TheLine.Level] = LevelIndent;
615 PreviousLineWasTouched = true;
616 } else {
617 // Format the first token if necessary, and notify the WhitespaceManager
618 // about the unchanged whitespace.
619 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
620 if (Tok == TheLine.First &&
621 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
622 unsigned LevelIndent = Tok->OriginalColumn;
623 if (!DryRun) {
624 // Remove trailing whitespace of the previous line if it was
625 // touched.
626 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
627 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
628 TheLine.InPPDirective);
629 } else {
630 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
631 }
632 }
633
634 if (static_cast<int>(LevelIndent) - Offset >= 0)
635 LevelIndent -= Offset;
636 if (Tok->isNot(tok::comment))
637 IndentForLevel[TheLine.Level] = LevelIndent;
638 } else if (!DryRun) {
639 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
640 }
641 }
642 // If we did not reformat this unwrapped line, the column at the end of
643 // the last token is unchanged - thus, we can calculate the end of the
644 // last token.
645 PreviousLineWasTouched = false;
646 }
647 if (!DryRun) {
648 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
649 Tok->Finalized = true;
650 }
651 }
652 PreviousLine = *I;
653 }
654 return Penalty;
655 }
656
657private:
658 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000659 ///
660 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000661 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
662 bool DryRun) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000663 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000664
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000665 // If the ObjC method declaration does not fit on a line, we should format
666 // it with one arg per line.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000667 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000668 State.Stack.back().BreakBeforeParameter = true;
669
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000670 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000671 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000672 }
673
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000674 /// \brief An edge in the solution space from \c Previous->State to \c State,
675 /// inserting a newline dependent on the \c NewLine.
676 struct StateNode {
677 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000678 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000679 LineState State;
680 bool NewLine;
681 StateNode *Previous;
682 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000683
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000684 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
685 ///
686 /// In case of equal penalties, we want to prefer states that were inserted
687 /// first. During state generation we make sure that we insert states first
688 /// that break the line as late as possible.
689 typedef std::pair<unsigned, unsigned> OrderedPenalty;
690
691 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
692 /// \c State has the given \c OrderedPenalty.
693 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
694
695 /// \brief The BFS queue type.
696 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
697 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000698
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000699 /// \brief Get the offset of the line relatively to the level.
700 ///
701 /// For example, 'public:' labels in classes are offset by 1 or 2
702 /// characters to the left from their level.
703 int getIndentOffset(const FormatToken &RootToken) {
704 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
705 return Style.AccessModifierOffset;
706 return 0;
707 }
708
709 /// \brief Add a new line and the required indent before the first Token
710 /// of the \c UnwrappedLine if there was no structural parsing error.
711 void formatFirstToken(FormatToken &RootToken,
712 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
713 unsigned Indent, bool InPPDirective) {
714 unsigned Newlines =
715 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
716 // Remove empty lines before "}" where applicable.
717 if (RootToken.is(tok::r_brace) &&
718 (!RootToken.Next ||
719 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
720 Newlines = std::min(Newlines, 1u);
721 if (Newlines == 0 && !RootToken.IsFirst)
722 Newlines = 1;
723
724 // Insert extra new line before access specifiers.
725 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
726 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
727 ++Newlines;
728
729 // Remove empty lines after access specifiers.
730 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
731 Newlines = std::min(1u, Newlines);
732
733 Whitespaces->replaceWhitespace(
734 RootToken, Newlines, IndentLevel, Indent, Indent,
735 InPPDirective && !RootToken.HasUnescapedNewline);
736 }
737
738 /// \brief Get the indent of \p Level from \p IndentForLevel.
739 ///
740 /// \p IndentForLevel must contain the indent for the level \c l
741 /// at \p IndentForLevel[l], or a value < 0 if the indent for
742 /// that level is unknown.
743 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
744 if (IndentForLevel[Level] != -1)
745 return IndentForLevel[Level];
746 if (Level == 0)
747 return 0;
748 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
749 }
750
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000751 void join(AnnotatedLine &A, const AnnotatedLine &B) {
752 assert(!A.Last->Next);
753 assert(!B.First->Previous);
754 A.Last->Next = B.First;
755 B.First->Previous = A.Last;
756 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
757 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
758 Tok->TotalLength += LengthA;
759 A.Last = Tok;
760 }
761 }
762
763 unsigned getColumnLimit(bool InPPDirective) const {
764 // In preprocessor directives reserve two chars for trailing " \"
765 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
766 }
767
768 bool touchesRanges(const CharSourceRange &Range) {
769 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
770 E = Ranges.end();
771 I != E; ++I) {
772 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
773 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
774 return true;
775 }
776 return false;
777 }
778
779 bool touchesLine(const AnnotatedLine &TheLine) {
780 const FormatToken *First = TheLine.First;
781 const FormatToken *Last = TheLine.Last;
782 CharSourceRange LineRange = CharSourceRange::getCharRange(
783 First->WhitespaceRange.getBegin().getLocWithOffset(
784 First->LastNewlineOffset),
785 Last->getStartOfNonWhitespace().getLocWithOffset(
786 Last->TokenText.size() - 1));
787 return touchesRanges(LineRange);
788 }
789
790 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
791 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
792 for (; I != E; ++I) {
793 if ((*I)->First->HasUnescapedNewline)
794 return false;
795 if (touchesLine(**I))
796 return true;
797 }
798 return false;
799 }
800
801 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
802 const FormatToken *First = TheLine.First;
803 CharSourceRange LineRange = CharSourceRange::getCharRange(
804 First->WhitespaceRange.getBegin(),
805 First->WhitespaceRange.getBegin().getLocWithOffset(
806 First->LastNewlineOffset));
807 return touchesRanges(LineRange);
808 }
809
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000810 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000811 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000812 /// This implements a variant of Dijkstra's algorithm on the graph that spans
813 /// the solution space (\c LineStates are the nodes). The algorithm tries to
814 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000815 /// to a state where all tokens are placed. Returns the penalty.
816 ///
817 /// If \p DryRun is \c false, directly applies the changes.
818 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000819 std::set<LineState> Seen;
820
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000821 // Increasing count of \c StateNode items we have created. This is used to
822 // create a deterministic order independent of the container.
823 unsigned Count = 0;
824 QueueType Queue;
825
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000826 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000827 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000828 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
829 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
830 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000831
Daniel Jasper567dcf92013-09-05 09:29:45 +0000832 unsigned Penalty = 0;
833
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000834 // While not empty, take first element and follow edges.
835 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000836 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000837 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000838 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000839 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000840 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000841 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000842 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000843
Daniel Jasper54b4e442013-05-22 05:27:42 +0000844 // Cut off the analysis of certain solutions if the analysis gets too
845 // complex. See description of IgnoreStackForComparison.
846 if (Count > 10000)
847 Node->State.IgnoreStackForComparison = true;
848
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000849 if (!Seen.insert(Node->State).second)
850 // State already examined with lower penalty.
851 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000852
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000853 FormatDecision LastFormat = Node->State.NextToken->Decision;
854 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000855 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000856 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000857 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000858 }
859
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000860 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000861 // We were unable to find a solution, do nothing.
862 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000863 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000864 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000865 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000866
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000867 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000868 if (!DryRun)
869 reconstructPath(InitialState, Queue.top().second);
870
Alexander Kornienkodd256312013-05-10 11:56:10 +0000871 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
872 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000873
874 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000875 }
876
877 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000878 std::deque<StateNode *> Path;
879 // We do not need a break before the initial token.
880 while (Current->Previous) {
881 Path.push_front(Current);
882 Current = Current->Previous;
883 }
884 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
885 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000886 unsigned Penalty = 0;
887 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
888 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
889
Manuel Klimek9c333b92013-05-29 15:10:11 +0000890 DEBUG({
891 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000892 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000893 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000894 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000895 }
896 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000897 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000898 }
899
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000900 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000901 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000902 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000903 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000904 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000905 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000906 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000907 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000908 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000909 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000910
911 StateNode *Node = new (Allocator.Allocate())
912 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000913 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
914 return;
915
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000916 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000917
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000918 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
919 ++(*Count);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000920 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000921
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000922 /// \brief If the \p State's next token is an r_brace closing a nested block,
923 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000924 ///
925 /// Returns \c true if all children could be placed successfully and adapts
926 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
927 /// creates changes using \c Whitespaces.
928 ///
929 /// The crucial idea here is that children always get formatted upon
930 /// encountering the closing brace right after the nested block. Now, if we
931 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
932 /// \c false), the entire block has to be kept on the same line (which is only
933 /// possible if it fits on the line, only contains a single statement, etc.
934 ///
935 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
936 /// break after the "{", format all lines with correct indentation and the put
937 /// the closing "}" on yet another new line.
938 ///
939 /// This enables us to keep the simple structure of the
940 /// \c UnwrappedLineFormatter, where we only have two options for each token:
941 /// break or don't break.
942 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
943 unsigned &Penalty) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000944 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper15eef852013-10-20 17:28:32 +0000945 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
946 if (!LBrace || LBrace->isNot(tok::l_brace) ||
947 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000948 // The previous token does not open a block. Nothing to do. We don't
949 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000950 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000951
952 if (NewLine) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000953 int AdditionalIndent = State.Stack.back().Indent -
954 Previous.Children[0]->Level * Style.IndentWidth;
955 Penalty += format(Previous.Children, DryRun, AdditionalIndent);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000956 return true;
957 }
958
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000959 // Cannot merge multiple statements into a single line.
Daniel Jasper15eef852013-10-20 17:28:32 +0000960 if (Previous.Children.size() > 1)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000961 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000962
963 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +0000964 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +0000965 return false;
966
967 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000968 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +0000969 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000970 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000971 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000972 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000973 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000974
Daniel Jasper15eef852013-10-20 17:28:32 +0000975 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000976 return true;
977 }
978
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000979 SourceManager &SourceMgr;
980 SmallVectorImpl<CharSourceRange> &Ranges;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000981 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000982 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000983 FormatStyle Style;
Daniel Jasper4281d732013-11-06 23:12:09 +0000984 LineJoiner Joiner;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000985
986 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000987};
988
Manuel Klimek96e888b2013-05-28 11:55:06 +0000989class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000990public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000991 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000992 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000993 : FormatTok(NULL), GreaterStashed(false), Column(0),
994 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
995 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000996 Lex.SetKeepWhitespaceMode(true);
997 }
998
Manuel Klimek96e888b2013-05-28 11:55:06 +0000999 ArrayRef<FormatToken *> lex() {
1000 assert(Tokens.empty());
1001 do {
1002 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001003 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +00001004 } while (Tokens.back()->Tok.isNot(tok::eof));
1005 return Tokens;
1006 }
1007
1008 IdentifierTable &getIdentTable() { return IdentTable; }
1009
1010private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001011 void maybeJoinPreviousTokens() {
1012 if (Tokens.size() < 4)
1013 return;
1014 FormatToken *Last = Tokens.back();
1015 if (!Last->is(tok::r_paren))
1016 return;
1017
1018 FormatToken *String = Tokens[Tokens.size() - 2];
1019 if (!String->is(tok::string_literal) || String->IsMultiline)
1020 return;
1021
1022 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1023 return;
1024
1025 FormatToken *Macro = Tokens[Tokens.size() - 4];
1026 if (Macro->TokenText != "_T")
1027 return;
1028
1029 const char *Start = Macro->TokenText.data();
1030 const char *End = Last->TokenText.data() + Last->TokenText.size();
1031 String->TokenText = StringRef(Start, End - Start);
1032 String->IsFirst = Macro->IsFirst;
1033 String->LastNewlineOffset = Macro->LastNewlineOffset;
1034 String->WhitespaceRange = Macro->WhitespaceRange;
1035 String->OriginalColumn = Macro->OriginalColumn;
1036 String->ColumnWidth = encoding::columnWidthWithTabs(
1037 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1038
1039 Tokens.pop_back();
1040 Tokens.pop_back();
1041 Tokens.pop_back();
1042 Tokens.back() = String;
1043 }
1044
Manuel Klimek96e888b2013-05-28 11:55:06 +00001045 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001046 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001047 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +00001048 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001049 Token Greater = FormatTok->Tok;
1050 FormatTok = new (Allocator.Allocate()) FormatToken;
1051 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001052 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001053 FormatTok->Tok.getLocation().getLocWithOffset(1);
1054 FormatTok->WhitespaceRange =
1055 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001056 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001057 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001058 GreaterStashed = false;
1059 return FormatTok;
1060 }
1061
Manuel Klimek96e888b2013-05-28 11:55:06 +00001062 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001063 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001064 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001065 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001066 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001067 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001068
1069 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001070 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001071 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001072 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1073 switch (FormatTok->TokenText[i]) {
1074 case '\n':
1075 ++FormatTok->NewlinesBefore;
1076 // FIXME: This is technically incorrect, as it could also
1077 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001078 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1079 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1080 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +00001081 FormatTok->HasUnescapedNewline = true;
1082 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1083 Column = 0;
1084 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001085 case '\r':
1086 case '\f':
1087 case '\v':
1088 Column = 0;
1089 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001090 case ' ':
1091 ++Column;
1092 break;
1093 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +00001094 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001095 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001096 case '\\':
1097 ++Column;
1098 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1099 FormatTok->TokenText[i + 1] != '\n'))
1100 FormatTok->Type = TT_ImplicitStringLiteral;
1101 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001102 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001103 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001104 ++Column;
1105 break;
1106 }
1107 }
1108
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001109 if (FormatTok->Type == TT_ImplicitStringLiteral)
1110 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001111 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001112
Daniel Jasper561211d2013-07-16 20:28:33 +00001113 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001114 }
Manuel Klimek95419382013-01-07 07:56:50 +00001115
Manuel Klimekd4397b92013-01-04 23:34:14 +00001116 // In case the token starts with escaped newlines, we want to
1117 // take them into account as whitespace - this pattern is quite frequent
1118 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +00001119 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001120 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1121 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001122 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001123 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001124 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +00001125 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001126 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001127
1128 FormatTok->WhitespaceRange = SourceRange(
1129 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1130
Manuel Klimekc41e8192013-08-29 15:21:40 +00001131 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001132
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001133 TrailingWhitespace = 0;
1134 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001135 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +00001136 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +00001137 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +00001138 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001139 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001140 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001141 FormatTok->Tok.setIdentifierInfo(&Info);
1142 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001143 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001144 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001145 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001146 GreaterStashed = true;
1147 }
1148
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001149 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +00001150
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001151 StringRef Text = FormatTok->TokenText;
1152 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001153 if (FirstNewlinePos == StringRef::npos) {
1154 // FIXME: ColumnWidth actually depends on the start column, we need to
1155 // take this into account when the token is moved.
1156 FormatTok->ColumnWidth =
1157 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1158 Column += FormatTok->ColumnWidth;
1159 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001160 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001161 // FIXME: ColumnWidth actually depends on the start column, we need to
1162 // take this into account when the token is moved.
1163 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1164 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1165
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001166 // The last line of the token always starts in column 0.
1167 // Thus, the length can be precomputed even in the presence of tabs.
1168 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1169 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1170 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001171 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +00001172 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001173
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001174 return FormatTok;
1175 }
1176
Manuel Klimek96e888b2013-05-28 11:55:06 +00001177 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001178 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001179 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +00001180 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001181 Lexer &Lex;
1182 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001183 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001184 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001185 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001186 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1187 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001188
Daniel Jasper561211d2013-07-16 20:28:33 +00001189 void readRawToken(FormatToken &Tok) {
1190 Lex.LexFromRawLexer(Tok.Tok);
1191 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1192 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +00001193 // For formatting, treat unterminated string literals like normal string
1194 // literals.
1195 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1196 Tok.TokenText[0] == '"') {
1197 Tok.Tok.setKind(tok::string_literal);
1198 Tok.IsUnterminatedLiteral = true;
1199 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001200 }
1201};
1202
Daniel Jasperbac016b2012-12-03 18:12:45 +00001203class Formatter : public UnwrappedLineConsumer {
1204public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001205 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001206 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001207 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001208 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001209 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001210 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001211 DEBUG(llvm::dbgs() << "File encoding: "
1212 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1213 : "unknown")
1214 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001215 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001216
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001217 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001218 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001219 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001220
1221 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001222 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001223 assert(UnwrappedLines.rbegin()->empty());
1224 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1225 ++Run) {
1226 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1227 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1228 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1229 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1230 }
1231 tooling::Replacements RunResult =
1232 format(AnnotatedLines, StructuralError, Tokens);
1233 DEBUG({
1234 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1235 for (tooling::Replacements::iterator I = RunResult.begin(),
1236 E = RunResult.end();
1237 I != E; ++I) {
1238 llvm::dbgs() << I->toString() << "\n";
1239 }
1240 });
1241 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1242 delete AnnotatedLines[i];
1243 }
1244 Result.insert(RunResult.begin(), RunResult.end());
1245 Whitespaces.reset();
1246 }
1247 return Result;
1248 }
1249
1250 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1251 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +00001252 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001253 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001254 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001255 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001256 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001257 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001258 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001259 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001260
Daniel Jasperb77d7412013-09-06 07:54:20 +00001261 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001262 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1263 BinPackInconclusiveFunctions);
1264 UnwrappedLineFormatter Formatter(SourceMgr, Ranges, &Indenter, &Whitespaces,
1265 Style);
1266 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001267 return Whitespaces.generateReplacements();
1268 }
1269
1270private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001271 static bool inputUsesCRLF(StringRef Text) {
1272 return Text.count('\r') * 2 > Text.count('\n');
1273 }
1274
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001275 void
1276 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001277 unsigned CountBoundToVariable = 0;
1278 unsigned CountBoundToType = 0;
1279 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001280 bool HasBinPackedFunction = false;
1281 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001282 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001283 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001284 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001285 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001286 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001287 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001288 bool SpacesBefore =
1289 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1290 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1291 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001292 if (SpacesBefore && !SpacesAfter)
1293 ++CountBoundToVariable;
1294 else if (!SpacesBefore && SpacesAfter)
1295 ++CountBoundToType;
1296 }
1297
Daniel Jasper78a4e612013-10-12 05:16:06 +00001298 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1299 if (Tok->is(tok::coloncolon) &&
1300 Tok->Previous->Type == TT_TemplateOpener)
1301 HasCpp03IncompatibleFormat = true;
1302 if (Tok->Type == TT_TemplateCloser &&
1303 Tok->Previous->Type == TT_TemplateCloser)
1304 HasCpp03IncompatibleFormat = true;
1305 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001306
1307 if (Tok->PackingKind == PPK_BinPacked)
1308 HasBinPackedFunction = true;
1309 if (Tok->PackingKind == PPK_OnePerLine)
1310 HasOnePerLineFunction = true;
1311
Manuel Klimekb3987012013-05-29 14:47:47 +00001312 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001313 }
1314 }
1315 if (Style.DerivePointerBinding) {
1316 if (CountBoundToType > CountBoundToVariable)
1317 Style.PointerBindsToType = true;
1318 else if (CountBoundToType < CountBoundToVariable)
1319 Style.PointerBindsToType = false;
1320 }
1321 if (Style.Standard == FormatStyle::LS_Auto) {
1322 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1323 : FormatStyle::LS_Cpp03;
1324 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001325 BinPackInconclusiveFunctions =
1326 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001327 }
1328
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001329 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001330 assert(!UnwrappedLines.empty());
1331 UnwrappedLines.back().push_back(TheLine);
1332 }
1333
1334 virtual void finishRun() {
1335 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001336 }
1337
1338 FormatStyle Style;
1339 Lexer &Lex;
1340 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001341 WhitespaceManager Whitespaces;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001342 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001343 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001344
1345 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001346 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001347};
1348
Craig Topper83f81d72013-06-30 22:29:28 +00001349} // end anonymous namespace
1350
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001351tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1352 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001353 std::vector<CharSourceRange> Ranges) {
1354 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001355 return formatter.format();
1356}
1357
Daniel Jasper8a999452013-05-16 10:40:07 +00001358tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1359 std::vector<tooling::Range> Ranges,
1360 StringRef FileName) {
1361 FileManager Files((FileSystemOptions()));
1362 DiagnosticsEngine Diagnostics(
1363 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1364 new DiagnosticOptions);
1365 SourceManager SourceMgr(Diagnostics, Files);
1366 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1367 const clang::FileEntry *Entry =
1368 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1369 SourceMgr.overrideFileContents(Entry, Buf);
1370 FileID ID =
1371 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001372 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1373 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001374 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1375 std::vector<CharSourceRange> CharRanges;
1376 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1377 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1378 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1379 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1380 }
1381 return reformat(Style, Lex, SourceMgr, CharRanges);
1382}
1383
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001384LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001385 LangOptions LangOpts;
1386 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001387 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001388 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001389 LangOpts.Bool = 1;
1390 LangOpts.ObjC1 = 1;
1391 LangOpts.ObjC2 = 1;
1392 return LangOpts;
1393}
1394
Edwin Vanef4e12c82013-09-30 13:31:48 +00001395const char *StyleOptionHelpDescription =
1396 "Coding style, currently supports:\n"
1397 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1398 "Use -style=file to load style configuration from\n"
1399 ".clang-format file located in one of the parent\n"
1400 "directories of the source file (or current\n"
1401 "directory for stdin).\n"
1402 "Use -style=\"{key: value, ...}\" to set specific\n"
1403 "parameters, e.g.:\n"
1404 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1405
1406FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1407 // Fallback style in case the rest of this function can't determine a style.
1408 StringRef FallbackStyle = "LLVM";
1409 FormatStyle Style;
1410 getPredefinedStyle(FallbackStyle, &Style);
1411
1412 if (StyleName.startswith("{")) {
1413 // Parse YAML/JSON style from the command line.
1414 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001415 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1416 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00001417 }
1418 return Style;
1419 }
1420
1421 if (!StyleName.equals_lower("file")) {
1422 if (!getPredefinedStyle(StyleName, &Style))
1423 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1424 << " style\n";
1425 return Style;
1426 }
1427
1428 SmallString<128> Path(FileName);
1429 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001430 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00001431 Directory = llvm::sys::path::parent_path(Directory)) {
1432 if (!llvm::sys::fs::is_directory(Directory))
1433 continue;
1434 SmallString<128> ConfigFile(Directory);
1435
1436 llvm::sys::path::append(ConfigFile, ".clang-format");
1437 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1438 bool IsFile = false;
1439 // Ignore errors from is_regular_file: we only need to know if we can read
1440 // the file or not.
1441 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1442
1443 if (!IsFile) {
1444 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1445 ConfigFile = Directory;
1446 llvm::sys::path::append(ConfigFile, "_clang-format");
1447 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1448 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1449 }
1450
1451 if (IsFile) {
1452 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola28ce23a2013-10-25 19:00:49 +00001453 if (llvm::error_code ec =
1454 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vanef4e12c82013-09-30 13:31:48 +00001455 llvm::errs() << ec.message() << "\n";
1456 continue;
1457 }
1458 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1459 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1460 << "\n";
1461 continue;
1462 }
1463 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1464 return Style;
1465 }
1466 }
1467 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1468 << " style\n";
1469 return Style;
1470}
1471
Daniel Jaspercd162382013-01-07 13:26:07 +00001472} // namespace format
1473} // namespace clang