blob: a5fc83e84e40f4cf93d27f6102d980c143364834 [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);
Daniel Jasper1a896a52013-11-08 00:57:11 +0000126 IO.mapOptional("BreakBeforeTernaryOperators",
127 Style.BreakBeforeTernaryOperators);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000128 IO.mapOptional("BreakConstructorInitializersBeforeComma",
129 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000130 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
131 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
132 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
133 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
134 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000135 IO.mapOptional("ExperimentalAutoDetectBinPacking",
136 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000137 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
138 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000139 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000140 IO.mapOptional("ObjCSpaceBeforeProtocolList",
141 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper47066e42013-10-25 14:29:37 +0000142 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
143 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000144 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
145 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000146 IO.mapOptional("PenaltyBreakFirstLessLess",
147 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000148 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
149 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
150 Style.PenaltyReturnTypeOnItsOwnLine);
151 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
152 IO.mapOptional("SpacesBeforeTrailingComments",
153 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000154 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000155 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000156 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000157 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000158 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000159 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000160 IO.mapOptional("IndentFunctionDeclarationAfterType",
161 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000162 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000163 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000164 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000165 IO.mapOptional("SpacesInCStyleCastParentheses",
166 Style.SpacesInCStyleCastParentheses);
167 IO.mapOptional("SpaceAfterControlStatementKeyword",
168 Style.SpaceAfterControlStatementKeyword);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000169 IO.mapOptional("SpaceBeforeAssignmentOperators",
170 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000171 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000172 }
173};
174}
175}
176
Daniel Jasperbac016b2012-12-03 18:12:45 +0000177namespace clang {
178namespace format {
179
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000180void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000181 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000182 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000183 Style.PenaltyBreakString = 1000;
184 Style.PenaltyExcessCharacter = 1000000;
185}
186
Daniel Jasperbac016b2012-12-03 18:12:45 +0000187FormatStyle getLLVMStyle() {
188 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000189 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000190 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000191 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000192 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000193 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000194 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000195 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000196 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000197 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000198 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000199 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000200 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
201 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000202 LLVMStyle.ColumnLimit = 80;
203 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000204 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000205 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000206 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000207 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000208 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000209 LLVMStyle.IndentFunctionDeclarationAfterType = false;
210 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000211 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000212 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000213 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000214 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000215 LLVMStyle.PointerBindsToType = false;
216 LLVMStyle.SpacesBeforeTrailingComments = 1;
217 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000218 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000219 LLVMStyle.SpacesInParentheses = false;
220 LLVMStyle.SpaceInEmptyParentheses = false;
221 LLVMStyle.SpacesInCStyleCastParentheses = false;
222 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000223 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000224 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000225 LLVMStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000226
227 setDefaultPenalties(LLVMStyle);
228 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper47066e42013-10-25 14:29:37 +0000229 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000230
Daniel Jasperbac016b2012-12-03 18:12:45 +0000231 return LLVMStyle;
232}
233
234FormatStyle getGoogleStyle() {
235 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000236 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000237 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000238 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000239 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000240 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000241 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000242 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000243 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000244 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000245 GoogleStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000246 GoogleStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000247 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
248 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000249 GoogleStyle.ColumnLimit = 80;
250 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000251 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000252 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000253 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000254 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000255 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000256 GoogleStyle.IndentFunctionDeclarationAfterType = true;
257 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000258 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000259 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000260 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000261 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000262 GoogleStyle.PointerBindsToType = true;
263 GoogleStyle.SpacesBeforeTrailingComments = 2;
264 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000265 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000266 GoogleStyle.SpacesInParentheses = false;
267 GoogleStyle.SpaceInEmptyParentheses = false;
268 GoogleStyle.SpacesInCStyleCastParentheses = false;
269 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000270 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000271 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000272 GoogleStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000273
274 setDefaultPenalties(GoogleStyle);
275 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper47066e42013-10-25 14:29:37 +0000276 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000277
Daniel Jasperbac016b2012-12-03 18:12:45 +0000278 return GoogleStyle;
279}
280
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000281FormatStyle getChromiumStyle() {
282 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000283 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000284 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000285 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000286 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000287 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000288 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000289 return ChromiumStyle;
290}
291
Alexander Kornienkofb594862013-05-06 14:11:27 +0000292FormatStyle getMozillaStyle() {
293 FormatStyle MozillaStyle = getLLVMStyle();
294 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
295 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
296 MozillaStyle.DerivePointerBinding = true;
297 MozillaStyle.IndentCaseLabels = true;
298 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
299 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
300 MozillaStyle.PointerBindsToType = true;
301 return MozillaStyle;
302}
303
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000304FormatStyle getWebKitStyle() {
305 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000306 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000307 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000308 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000309 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000310 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000311 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000312 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000313 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000314 Style.PointerBindsToType = true;
315 return Style;
316}
317
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000318bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000319 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000320 *Style = getLLVMStyle();
321 else if (Name.equals_lower("chromium"))
322 *Style = getChromiumStyle();
323 else if (Name.equals_lower("mozilla"))
324 *Style = getMozillaStyle();
325 else if (Name.equals_lower("google"))
326 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000327 else if (Name.equals_lower("webkit"))
328 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000329 else
330 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000331
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000332 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000333}
334
335llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000336 if (Text.trim().empty())
337 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000338 llvm::yaml::Input Input(Text);
339 Input >> *Style;
340 return Input.error();
341}
342
343std::string configurationAsText(const FormatStyle &Style) {
344 std::string Text;
345 llvm::raw_string_ostream Stream(Text);
346 llvm::yaml::Output Output(Stream);
347 // We use the same mapping method for input and output, so we need a non-const
348 // reference here.
349 FormatStyle NonConstStyle = Style;
350 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000351 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000352}
353
Craig Topper83f81d72013-06-30 22:29:28 +0000354namespace {
355
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000356class NoColumnLimitFormatter {
357public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000358 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000359
360 /// \brief Formats the line starting at \p State, simply keeping all of the
361 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000362 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000363 LineState State =
364 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000365 while (State.NextToken != NULL) {
366 bool Newline =
367 Indenter->mustBreak(State) ||
368 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
369 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
370 }
371 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000372
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000373private:
374 ContinuationIndenter *Indenter;
375};
376
Daniel Jasper4281d732013-11-06 23:12:09 +0000377class LineJoiner {
378public:
379 LineJoiner(const FormatStyle &Style) : Style(Style) {}
380
381 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
382 unsigned
383 tryFitMultipleLinesInOne(unsigned Indent,
384 SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
385 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
386 // We can never merge stuff if there are trailing line comments.
387 AnnotatedLine *TheLine = *I;
388 if (TheLine->Last->Type == TT_LineComment)
389 return 0;
390
391 if (Indent > Style.ColumnLimit)
392 return 0;
393
Daniel Jasperc2e03292013-11-08 17:33:27 +0000394 unsigned Limit =
395 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper4281d732013-11-06 23:12:09 +0000396 // If we already exceed the column limit, we set 'Limit' to 0. The different
397 // tryMerge..() functions can then decide whether to still do merging.
398 Limit = TheLine->Last->TotalLength > Limit
399 ? 0
400 : Limit - TheLine->Last->TotalLength;
401
402 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
403 return 0;
404
405 if (TheLine->Last->is(tok::l_brace)) {
406 return tryMergeSimpleBlock(I, E, Limit);
407 } else if (Style.AllowShortIfStatementsOnASingleLine &&
408 TheLine->First->is(tok::kw_if)) {
409 return tryMergeSimpleControlStatement(I, E, Limit);
410 } else if (Style.AllowShortLoopsOnASingleLine &&
411 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
412 return tryMergeSimpleControlStatement(I, E, Limit);
413 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
414 TheLine->First->IsFirst)) {
415 return tryMergeSimplePPDirective(I, E, Limit);
416 }
417 return 0;
418 }
419
420private:
421 unsigned
422 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
423 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
424 unsigned Limit) {
425 if (Limit == 0)
426 return 0;
427 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
428 return 0;
429 if (I + 2 != E && (*(I + 2))->InPPDirective &&
430 !(*(I + 2))->First->HasUnescapedNewline)
431 return 0;
432 if (1 + (*(I + 1))->Last->TotalLength > Limit)
433 return 0;
434 return 1;
435 }
436
437 unsigned tryMergeSimpleControlStatement(
438 SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
439 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
440 if (Limit == 0)
441 return 0;
442 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
443 (*(I + 1))->First->is(tok::l_brace))
444 return 0;
445 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
446 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
447 return 0;
448 AnnotatedLine &Line = **I;
449 if (Line.Last->isNot(tok::r_paren))
450 return 0;
451 if (1 + (*(I + 1))->Last->TotalLength > Limit)
452 return 0;
453 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
454 tok::kw_while) ||
455 (*(I + 1))->First->Type == TT_LineComment)
456 return 0;
457 // Only inline simple if's (no nested if or else).
458 if (I + 2 != E && Line.First->is(tok::kw_if) &&
459 (*(I + 2))->First->is(tok::kw_else))
460 return 0;
461 return 1;
462 }
463
464 unsigned
465 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
466 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
467 unsigned Limit) {
468 // No merging if the brace already is on the next line.
469 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
470 return 0;
471
472 // First, check that the current line allows merging. This is the case if
473 // we're not in a control flow statement and the last token is an opening
474 // brace.
475 AnnotatedLine &Line = **I;
476 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
477 tok::kw_else, tok::kw_try, tok::kw_catch,
478 tok::kw_for,
479 // This gets rid of all ObjC @ keywords and methods.
480 tok::at, tok::minus, tok::plus))
481 return 0;
482
483 FormatToken *Tok = (*(I + 1))->First;
484 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
485 (Tok->getNextNonComment() == NULL ||
486 Tok->getNextNonComment()->is(tok::semi))) {
487 // We merge empty blocks even if the line exceeds the column limit.
488 Tok->SpacesRequiredBefore = 0;
489 Tok->CanBreakBefore = true;
490 return 1;
491 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
492 // Check that we still have three lines and they fit into the limit.
493 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid)
494 return 0;
495
496 if (!nextTwoLinesFitInto(I, Limit))
497 return 0;
498
499 // Second, check that the next line does not contain any braces - if it
500 // does, readability declines when putting it into a single line.
501 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
502 return 0;
503 do {
504 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
505 return 0;
506 Tok = Tok->Next;
507 } while (Tok != NULL);
508
509 // Last, check that the third line contains a single closing brace.
510 Tok = (*(I + 2))->First;
511 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
512 Tok->MustBreakBefore)
513 return 0;
514
515 return 2;
516 }
517 return 0;
518 }
519
520 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
521 unsigned Limit) {
522 return 1 + (*(I + 1))->Last->TotalLength + 1 +
523 (*(I + 2))->Last->TotalLength <=
524 Limit;
525 }
526
527 const FormatStyle &Style;
528};
529
Daniel Jasperbac016b2012-12-03 18:12:45 +0000530class UnwrappedLineFormatter {
531public:
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000532 UnwrappedLineFormatter(SourceManager &SourceMgr,
533 SmallVectorImpl<CharSourceRange> &Ranges,
534 ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000535 WhitespaceManager *Whitespaces,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000536 const FormatStyle &Style)
537 : SourceMgr(SourceMgr), Ranges(Ranges), Indenter(Indenter),
Daniel Jasper4281d732013-11-06 23:12:09 +0000538 Whitespaces(Whitespaces), Style(Style), Joiner(Style) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000539
Daniel Jasper4281d732013-11-06 23:12:09 +0000540 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000541 int AdditionalIndent = 0) {
542 assert(!Lines.empty());
543 unsigned Penalty = 0;
544 std::vector<int> IndentForLevel;
545 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
546 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
547 bool PreviousLineWasTouched = false;
548 const AnnotatedLine *PreviousLine = NULL;
549 bool FormatPPDirective = false;
Daniel Jasper4281d732013-11-06 23:12:09 +0000550 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
551 E = Lines.end();
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000552 I != E; ++I) {
553 const AnnotatedLine &TheLine = **I;
554 const FormatToken *FirstTok = TheLine.First;
555 int Offset = getIndentOffset(*FirstTok);
556
557 // Check whether this line is part of a formatted preprocessor directive.
558 if (FirstTok->HasUnescapedNewline)
559 FormatPPDirective = false;
560 if (!FormatPPDirective && TheLine.InPPDirective &&
561 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
562 FormatPPDirective = true;
563
564 // Determine indent and try to merge multiple unwrapped lines.
565 while (IndentForLevel.size() <= TheLine.Level)
566 IndentForLevel.push_back(-1);
567 IndentForLevel.resize(TheLine.Level + 1);
568 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
569 if (static_cast<int>(Indent) + Offset >= 0)
570 Indent += Offset;
Daniel Jasper4281d732013-11-06 23:12:09 +0000571 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
572 if (!DryRun) {
573 for (unsigned i = 0; i < MergedLines; ++i) {
574 join(**(I + i), **(I + i + 1));
575 }
576 }
577 I += MergedLines;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000578
579 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
580 if (TheLine.First->is(tok::eof)) {
581 if (PreviousLineWasTouched && !DryRun) {
582 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
583 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
584 /*IndentLevel=*/0, /*Spaces=*/0,
585 /*TargetColumn=*/0);
586 }
587 } else if (TheLine.Type != LT_Invalid &&
588 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
589 unsigned LevelIndent =
590 getIndent(IndentForLevel, TheLine.Level);
591 if (FirstTok->WhitespaceRange.isValid()) {
592 if (!DryRun)
593 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
594 Indent, TheLine.InPPDirective);
595 } else {
596 Indent = LevelIndent = FirstTok->OriginalColumn;
597 }
598
599 // If everything fits on a single line, just put it there.
600 unsigned ColumnLimit = Style.ColumnLimit;
601 if (I + 1 != E) {
602 AnnotatedLine *NextLine = *(I + 1);
603 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
604 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
605 }
606
607 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
608 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
609 while (State.NextToken != NULL)
610 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
611 } else if (Style.ColumnLimit == 0) {
612 NoColumnLimitFormatter Formatter(Indenter);
613 if (!DryRun)
614 Formatter.format(Indent, &TheLine);
615 } else {
616 Penalty += format(TheLine, Indent, DryRun);
617 }
618
619 IndentForLevel[TheLine.Level] = LevelIndent;
620 PreviousLineWasTouched = true;
621 } else {
622 // Format the first token if necessary, and notify the WhitespaceManager
623 // about the unchanged whitespace.
624 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
625 if (Tok == TheLine.First &&
626 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
627 unsigned LevelIndent = Tok->OriginalColumn;
628 if (!DryRun) {
629 // Remove trailing whitespace of the previous line if it was
630 // touched.
631 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
632 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
633 TheLine.InPPDirective);
634 } else {
635 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
636 }
637 }
638
639 if (static_cast<int>(LevelIndent) - Offset >= 0)
640 LevelIndent -= Offset;
641 if (Tok->isNot(tok::comment))
642 IndentForLevel[TheLine.Level] = LevelIndent;
643 } else if (!DryRun) {
644 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
645 }
646 }
647 // If we did not reformat this unwrapped line, the column at the end of
648 // the last token is unchanged - thus, we can calculate the end of the
649 // last token.
650 PreviousLineWasTouched = false;
651 }
652 if (!DryRun) {
653 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
654 Tok->Finalized = true;
655 }
656 }
657 PreviousLine = *I;
658 }
659 return Penalty;
660 }
661
662private:
663 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000664 ///
665 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000666 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
667 bool DryRun) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000668 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000669
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000670 // If the ObjC method declaration does not fit on a line, we should format
671 // it with one arg per line.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000672 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000673 State.Stack.back().BreakBeforeParameter = true;
674
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000675 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000676 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000677 }
678
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000679 /// \brief An edge in the solution space from \c Previous->State to \c State,
680 /// inserting a newline dependent on the \c NewLine.
681 struct StateNode {
682 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000683 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000684 LineState State;
685 bool NewLine;
686 StateNode *Previous;
687 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000688
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000689 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
690 ///
691 /// In case of equal penalties, we want to prefer states that were inserted
692 /// first. During state generation we make sure that we insert states first
693 /// that break the line as late as possible.
694 typedef std::pair<unsigned, unsigned> OrderedPenalty;
695
696 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
697 /// \c State has the given \c OrderedPenalty.
698 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
699
700 /// \brief The BFS queue type.
701 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
702 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000703
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000704 /// \brief Get the offset of the line relatively to the level.
705 ///
706 /// For example, 'public:' labels in classes are offset by 1 or 2
707 /// characters to the left from their level.
708 int getIndentOffset(const FormatToken &RootToken) {
709 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
710 return Style.AccessModifierOffset;
711 return 0;
712 }
713
714 /// \brief Add a new line and the required indent before the first Token
715 /// of the \c UnwrappedLine if there was no structural parsing error.
716 void formatFirstToken(FormatToken &RootToken,
717 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
718 unsigned Indent, bool InPPDirective) {
719 unsigned Newlines =
720 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
721 // Remove empty lines before "}" where applicable.
722 if (RootToken.is(tok::r_brace) &&
723 (!RootToken.Next ||
724 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
725 Newlines = std::min(Newlines, 1u);
726 if (Newlines == 0 && !RootToken.IsFirst)
727 Newlines = 1;
728
729 // Insert extra new line before access specifiers.
730 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
731 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
732 ++Newlines;
733
734 // Remove empty lines after access specifiers.
735 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
736 Newlines = std::min(1u, Newlines);
737
738 Whitespaces->replaceWhitespace(
739 RootToken, Newlines, IndentLevel, Indent, Indent,
740 InPPDirective && !RootToken.HasUnescapedNewline);
741 }
742
743 /// \brief Get the indent of \p Level from \p IndentForLevel.
744 ///
745 /// \p IndentForLevel must contain the indent for the level \c l
746 /// at \p IndentForLevel[l], or a value < 0 if the indent for
747 /// that level is unknown.
748 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
749 if (IndentForLevel[Level] != -1)
750 return IndentForLevel[Level];
751 if (Level == 0)
752 return 0;
753 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
754 }
755
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000756 void join(AnnotatedLine &A, const AnnotatedLine &B) {
757 assert(!A.Last->Next);
758 assert(!B.First->Previous);
759 A.Last->Next = B.First;
760 B.First->Previous = A.Last;
Daniel Jasperc2e03292013-11-08 17:33:27 +0000761 B.First->CanBreakBefore = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000762 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
763 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
764 Tok->TotalLength += LengthA;
765 A.Last = Tok;
766 }
767 }
768
769 unsigned getColumnLimit(bool InPPDirective) const {
770 // In preprocessor directives reserve two chars for trailing " \"
771 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
772 }
773
774 bool touchesRanges(const CharSourceRange &Range) {
775 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
776 E = Ranges.end();
777 I != E; ++I) {
778 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
779 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
780 return true;
781 }
782 return false;
783 }
784
785 bool touchesLine(const AnnotatedLine &TheLine) {
786 const FormatToken *First = TheLine.First;
787 const FormatToken *Last = TheLine.Last;
788 CharSourceRange LineRange = CharSourceRange::getCharRange(
789 First->WhitespaceRange.getBegin().getLocWithOffset(
790 First->LastNewlineOffset),
791 Last->getStartOfNonWhitespace().getLocWithOffset(
792 Last->TokenText.size() - 1));
793 return touchesRanges(LineRange);
794 }
795
796 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
797 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
798 for (; I != E; ++I) {
799 if ((*I)->First->HasUnescapedNewline)
800 return false;
801 if (touchesLine(**I))
802 return true;
803 }
804 return false;
805 }
806
807 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
808 const FormatToken *First = TheLine.First;
809 CharSourceRange LineRange = CharSourceRange::getCharRange(
810 First->WhitespaceRange.getBegin(),
811 First->WhitespaceRange.getBegin().getLocWithOffset(
812 First->LastNewlineOffset));
813 return touchesRanges(LineRange);
814 }
815
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000816 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000817 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000818 /// This implements a variant of Dijkstra's algorithm on the graph that spans
819 /// the solution space (\c LineStates are the nodes). The algorithm tries to
820 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000821 /// to a state where all tokens are placed. Returns the penalty.
822 ///
823 /// If \p DryRun is \c false, directly applies the changes.
824 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000825 std::set<LineState> Seen;
826
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000827 // Increasing count of \c StateNode items we have created. This is used to
828 // create a deterministic order independent of the container.
829 unsigned Count = 0;
830 QueueType Queue;
831
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000832 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000833 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000834 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
835 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
836 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000837
Daniel Jasper567dcf92013-09-05 09:29:45 +0000838 unsigned Penalty = 0;
839
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000840 // While not empty, take first element and follow edges.
841 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000842 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000843 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000844 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000845 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000846 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000847 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000848 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000849
Daniel Jasper54b4e442013-05-22 05:27:42 +0000850 // Cut off the analysis of certain solutions if the analysis gets too
851 // complex. See description of IgnoreStackForComparison.
852 if (Count > 10000)
853 Node->State.IgnoreStackForComparison = true;
854
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000855 if (!Seen.insert(Node->State).second)
856 // State already examined with lower penalty.
857 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000858
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000859 FormatDecision LastFormat = Node->State.NextToken->Decision;
860 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000861 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000862 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000863 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000864 }
865
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000866 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000867 // We were unable to find a solution, do nothing.
868 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000869 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000870 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000871 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000872
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000873 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000874 if (!DryRun)
875 reconstructPath(InitialState, Queue.top().second);
876
Alexander Kornienkodd256312013-05-10 11:56:10 +0000877 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
878 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000879
880 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000881 }
882
883 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000884 std::deque<StateNode *> Path;
885 // We do not need a break before the initial token.
886 while (Current->Previous) {
887 Path.push_front(Current);
888 Current = Current->Previous;
889 }
890 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
891 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000892 unsigned Penalty = 0;
893 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
894 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
895
Manuel Klimek9c333b92013-05-29 15:10:11 +0000896 DEBUG({
897 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000898 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000899 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000900 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000901 }
902 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000903 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000904 }
905
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000906 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000907 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000908 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000909 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000910 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000911 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000912 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000913 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000914 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000915 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000916
917 StateNode *Node = new (Allocator.Allocate())
918 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000919 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
920 return;
921
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000922 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000923
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000924 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
925 ++(*Count);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000926 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000927
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000928 /// \brief If the \p State's next token is an r_brace closing a nested block,
929 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000930 ///
931 /// Returns \c true if all children could be placed successfully and adapts
932 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
933 /// creates changes using \c Whitespaces.
934 ///
935 /// The crucial idea here is that children always get formatted upon
936 /// encountering the closing brace right after the nested block. Now, if we
937 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
938 /// \c false), the entire block has to be kept on the same line (which is only
939 /// possible if it fits on the line, only contains a single statement, etc.
940 ///
941 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
942 /// break after the "{", format all lines with correct indentation and the put
943 /// the closing "}" on yet another new line.
944 ///
945 /// This enables us to keep the simple structure of the
946 /// \c UnwrappedLineFormatter, where we only have two options for each token:
947 /// break or don't break.
948 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
949 unsigned &Penalty) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000950 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper15eef852013-10-20 17:28:32 +0000951 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
952 if (!LBrace || LBrace->isNot(tok::l_brace) ||
953 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000954 // The previous token does not open a block. Nothing to do. We don't
955 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000956 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000957
958 if (NewLine) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000959 int AdditionalIndent = State.Stack.back().Indent -
960 Previous.Children[0]->Level * Style.IndentWidth;
961 Penalty += format(Previous.Children, DryRun, AdditionalIndent);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000962 return true;
963 }
964
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000965 // Cannot merge multiple statements into a single line.
Daniel Jasper15eef852013-10-20 17:28:32 +0000966 if (Previous.Children.size() > 1)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000967 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000968
969 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +0000970 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +0000971 return false;
972
973 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000974 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +0000975 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000976 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000977 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000978 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000979 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000980
Daniel Jasper15eef852013-10-20 17:28:32 +0000981 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000982 return true;
983 }
984
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000985 SourceManager &SourceMgr;
986 SmallVectorImpl<CharSourceRange> &Ranges;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000987 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000988 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000989 FormatStyle Style;
Daniel Jasper4281d732013-11-06 23:12:09 +0000990 LineJoiner Joiner;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000991
992 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000993};
994
Manuel Klimek96e888b2013-05-28 11:55:06 +0000995class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000996public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000997 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000998 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000999 : FormatTok(NULL), GreaterStashed(false), Column(0),
1000 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1001 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001002 Lex.SetKeepWhitespaceMode(true);
1003 }
1004
Manuel Klimek96e888b2013-05-28 11:55:06 +00001005 ArrayRef<FormatToken *> lex() {
1006 assert(Tokens.empty());
1007 do {
1008 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001009 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +00001010 } while (Tokens.back()->Tok.isNot(tok::eof));
1011 return Tokens;
1012 }
1013
1014 IdentifierTable &getIdentTable() { return IdentTable; }
1015
1016private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001017 void maybeJoinPreviousTokens() {
1018 if (Tokens.size() < 4)
1019 return;
1020 FormatToken *Last = Tokens.back();
1021 if (!Last->is(tok::r_paren))
1022 return;
1023
1024 FormatToken *String = Tokens[Tokens.size() - 2];
1025 if (!String->is(tok::string_literal) || String->IsMultiline)
1026 return;
1027
1028 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1029 return;
1030
1031 FormatToken *Macro = Tokens[Tokens.size() - 4];
1032 if (Macro->TokenText != "_T")
1033 return;
1034
1035 const char *Start = Macro->TokenText.data();
1036 const char *End = Last->TokenText.data() + Last->TokenText.size();
1037 String->TokenText = StringRef(Start, End - Start);
1038 String->IsFirst = Macro->IsFirst;
1039 String->LastNewlineOffset = Macro->LastNewlineOffset;
1040 String->WhitespaceRange = Macro->WhitespaceRange;
1041 String->OriginalColumn = Macro->OriginalColumn;
1042 String->ColumnWidth = encoding::columnWidthWithTabs(
1043 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1044
1045 Tokens.pop_back();
1046 Tokens.pop_back();
1047 Tokens.pop_back();
1048 Tokens.back() = String;
1049 }
1050
Manuel Klimek96e888b2013-05-28 11:55:06 +00001051 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001052 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001053 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +00001054 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001055 Token Greater = FormatTok->Tok;
1056 FormatTok = new (Allocator.Allocate()) FormatToken;
1057 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001058 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001059 FormatTok->Tok.getLocation().getLocWithOffset(1);
1060 FormatTok->WhitespaceRange =
1061 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001062 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001063 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001064 GreaterStashed = false;
1065 return FormatTok;
1066 }
1067
Manuel Klimek96e888b2013-05-28 11:55:06 +00001068 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001069 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001070 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001071 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001072 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001073 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001074
1075 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001076 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001077 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001078 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1079 switch (FormatTok->TokenText[i]) {
1080 case '\n':
1081 ++FormatTok->NewlinesBefore;
1082 // FIXME: This is technically incorrect, as it could also
1083 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001084 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1085 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1086 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +00001087 FormatTok->HasUnescapedNewline = true;
1088 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1089 Column = 0;
1090 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001091 case '\r':
1092 case '\f':
1093 case '\v':
1094 Column = 0;
1095 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001096 case ' ':
1097 ++Column;
1098 break;
1099 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +00001100 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001101 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001102 case '\\':
1103 ++Column;
1104 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1105 FormatTok->TokenText[i + 1] != '\n'))
1106 FormatTok->Type = TT_ImplicitStringLiteral;
1107 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001108 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001109 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001110 ++Column;
1111 break;
1112 }
1113 }
1114
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001115 if (FormatTok->Type == TT_ImplicitStringLiteral)
1116 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001117 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001118
Daniel Jasper561211d2013-07-16 20:28:33 +00001119 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001120 }
Manuel Klimek95419382013-01-07 07:56:50 +00001121
Manuel Klimekd4397b92013-01-04 23:34:14 +00001122 // In case the token starts with escaped newlines, we want to
1123 // take them into account as whitespace - this pattern is quite frequent
1124 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +00001125 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001126 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1127 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001128 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001129 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001130 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +00001131 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001132 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001133
1134 FormatTok->WhitespaceRange = SourceRange(
1135 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1136
Manuel Klimekc41e8192013-08-29 15:21:40 +00001137 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001138
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001139 TrailingWhitespace = 0;
1140 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001141 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +00001142 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +00001143 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +00001144 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001145 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001146 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001147 FormatTok->Tok.setIdentifierInfo(&Info);
1148 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001149 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001150 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001151 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001152 GreaterStashed = true;
1153 }
1154
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001155 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +00001156
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001157 StringRef Text = FormatTok->TokenText;
1158 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001159 if (FirstNewlinePos == StringRef::npos) {
1160 // FIXME: ColumnWidth actually depends on the start column, we need to
1161 // take this into account when the token is moved.
1162 FormatTok->ColumnWidth =
1163 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1164 Column += FormatTok->ColumnWidth;
1165 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001166 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001167 // FIXME: ColumnWidth actually depends on the start column, we need to
1168 // take this into account when the token is moved.
1169 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1170 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1171
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001172 // The last line of the token always starts in column 0.
1173 // Thus, the length can be precomputed even in the presence of tabs.
1174 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1175 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1176 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001177 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +00001178 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001179
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001180 return FormatTok;
1181 }
1182
Manuel Klimek96e888b2013-05-28 11:55:06 +00001183 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001184 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001185 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +00001186 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001187 Lexer &Lex;
1188 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001189 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001190 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001191 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001192 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1193 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001194
Daniel Jasper561211d2013-07-16 20:28:33 +00001195 void readRawToken(FormatToken &Tok) {
1196 Lex.LexFromRawLexer(Tok.Tok);
1197 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1198 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +00001199 // For formatting, treat unterminated string literals like normal string
1200 // literals.
1201 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1202 Tok.TokenText[0] == '"') {
1203 Tok.Tok.setKind(tok::string_literal);
1204 Tok.IsUnterminatedLiteral = true;
1205 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001206 }
1207};
1208
Daniel Jasperbac016b2012-12-03 18:12:45 +00001209class Formatter : public UnwrappedLineConsumer {
1210public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001211 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001212 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001213 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001214 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001215 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001216 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001217 DEBUG(llvm::dbgs() << "File encoding: "
1218 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1219 : "unknown")
1220 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001221 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001222
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001223 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001224 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001225 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001226
1227 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001228 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001229 assert(UnwrappedLines.rbegin()->empty());
1230 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1231 ++Run) {
1232 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1233 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1234 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1235 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1236 }
1237 tooling::Replacements RunResult =
1238 format(AnnotatedLines, StructuralError, Tokens);
1239 DEBUG({
1240 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1241 for (tooling::Replacements::iterator I = RunResult.begin(),
1242 E = RunResult.end();
1243 I != E; ++I) {
1244 llvm::dbgs() << I->toString() << "\n";
1245 }
1246 });
1247 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1248 delete AnnotatedLines[i];
1249 }
1250 Result.insert(RunResult.begin(), RunResult.end());
1251 Whitespaces.reset();
1252 }
1253 return Result;
1254 }
1255
1256 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1257 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +00001258 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001259 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001260 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001261 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001262 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001263 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001264 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001265 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001266
Daniel Jasperb77d7412013-09-06 07:54:20 +00001267 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001268 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1269 BinPackInconclusiveFunctions);
1270 UnwrappedLineFormatter Formatter(SourceMgr, Ranges, &Indenter, &Whitespaces,
1271 Style);
1272 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001273 return Whitespaces.generateReplacements();
1274 }
1275
1276private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001277 static bool inputUsesCRLF(StringRef Text) {
1278 return Text.count('\r') * 2 > Text.count('\n');
1279 }
1280
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001281 void
1282 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001283 unsigned CountBoundToVariable = 0;
1284 unsigned CountBoundToType = 0;
1285 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001286 bool HasBinPackedFunction = false;
1287 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001288 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001289 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001290 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001291 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001292 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001293 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001294 bool SpacesBefore =
1295 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1296 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1297 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001298 if (SpacesBefore && !SpacesAfter)
1299 ++CountBoundToVariable;
1300 else if (!SpacesBefore && SpacesAfter)
1301 ++CountBoundToType;
1302 }
1303
Daniel Jasper78a4e612013-10-12 05:16:06 +00001304 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1305 if (Tok->is(tok::coloncolon) &&
1306 Tok->Previous->Type == TT_TemplateOpener)
1307 HasCpp03IncompatibleFormat = true;
1308 if (Tok->Type == TT_TemplateCloser &&
1309 Tok->Previous->Type == TT_TemplateCloser)
1310 HasCpp03IncompatibleFormat = true;
1311 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001312
1313 if (Tok->PackingKind == PPK_BinPacked)
1314 HasBinPackedFunction = true;
1315 if (Tok->PackingKind == PPK_OnePerLine)
1316 HasOnePerLineFunction = true;
1317
Manuel Klimekb3987012013-05-29 14:47:47 +00001318 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001319 }
1320 }
1321 if (Style.DerivePointerBinding) {
1322 if (CountBoundToType > CountBoundToVariable)
1323 Style.PointerBindsToType = true;
1324 else if (CountBoundToType < CountBoundToVariable)
1325 Style.PointerBindsToType = false;
1326 }
1327 if (Style.Standard == FormatStyle::LS_Auto) {
1328 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1329 : FormatStyle::LS_Cpp03;
1330 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001331 BinPackInconclusiveFunctions =
1332 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001333 }
1334
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001335 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001336 assert(!UnwrappedLines.empty());
1337 UnwrappedLines.back().push_back(TheLine);
1338 }
1339
1340 virtual void finishRun() {
1341 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001342 }
1343
1344 FormatStyle Style;
1345 Lexer &Lex;
1346 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001347 WhitespaceManager Whitespaces;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001348 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001349 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001350
1351 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001352 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001353};
1354
Craig Topper83f81d72013-06-30 22:29:28 +00001355} // end anonymous namespace
1356
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001357tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1358 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001359 std::vector<CharSourceRange> Ranges) {
1360 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001361 return formatter.format();
1362}
1363
Daniel Jasper8a999452013-05-16 10:40:07 +00001364tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1365 std::vector<tooling::Range> Ranges,
1366 StringRef FileName) {
1367 FileManager Files((FileSystemOptions()));
1368 DiagnosticsEngine Diagnostics(
1369 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1370 new DiagnosticOptions);
1371 SourceManager SourceMgr(Diagnostics, Files);
1372 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1373 const clang::FileEntry *Entry =
1374 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1375 SourceMgr.overrideFileContents(Entry, Buf);
1376 FileID ID =
1377 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001378 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1379 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001380 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1381 std::vector<CharSourceRange> CharRanges;
1382 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1383 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1384 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1385 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1386 }
1387 return reformat(Style, Lex, SourceMgr, CharRanges);
1388}
1389
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001390LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001391 LangOptions LangOpts;
1392 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001393 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001394 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001395 LangOpts.Bool = 1;
1396 LangOpts.ObjC1 = 1;
1397 LangOpts.ObjC2 = 1;
1398 return LangOpts;
1399}
1400
Edwin Vanef4e12c82013-09-30 13:31:48 +00001401const char *StyleOptionHelpDescription =
1402 "Coding style, currently supports:\n"
1403 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1404 "Use -style=file to load style configuration from\n"
1405 ".clang-format file located in one of the parent\n"
1406 "directories of the source file (or current\n"
1407 "directory for stdin).\n"
1408 "Use -style=\"{key: value, ...}\" to set specific\n"
1409 "parameters, e.g.:\n"
1410 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1411
1412FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1413 // Fallback style in case the rest of this function can't determine a style.
1414 StringRef FallbackStyle = "LLVM";
1415 FormatStyle Style;
1416 getPredefinedStyle(FallbackStyle, &Style);
1417
1418 if (StyleName.startswith("{")) {
1419 // Parse YAML/JSON style from the command line.
1420 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001421 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1422 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00001423 }
1424 return Style;
1425 }
1426
1427 if (!StyleName.equals_lower("file")) {
1428 if (!getPredefinedStyle(StyleName, &Style))
1429 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1430 << " style\n";
1431 return Style;
1432 }
1433
1434 SmallString<128> Path(FileName);
1435 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001436 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00001437 Directory = llvm::sys::path::parent_path(Directory)) {
1438 if (!llvm::sys::fs::is_directory(Directory))
1439 continue;
1440 SmallString<128> ConfigFile(Directory);
1441
1442 llvm::sys::path::append(ConfigFile, ".clang-format");
1443 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1444 bool IsFile = false;
1445 // Ignore errors from is_regular_file: we only need to know if we can read
1446 // the file or not.
1447 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1448
1449 if (!IsFile) {
1450 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1451 ConfigFile = Directory;
1452 llvm::sys::path::append(ConfigFile, "_clang-format");
1453 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1454 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1455 }
1456
1457 if (IsFile) {
1458 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola28ce23a2013-10-25 19:00:49 +00001459 if (llvm::error_code ec =
1460 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vanef4e12c82013-09-30 13:31:48 +00001461 llvm::errs() << ec.message() << "\n";
1462 continue;
1463 }
1464 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1465 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1466 << "\n";
1467 continue;
1468 }
1469 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1470 return Style;
1471 }
1472 }
1473 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1474 << " style\n";
1475 return Style;
1476}
1477
Daniel Jaspercd162382013-01-07 13:26:07 +00001478} // namespace format
1479} // namespace clang