blob: 01c122ecc7bf77a5a8149934461b5540de24a54a [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
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000402 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper4281d732013-11-06 23:12:09 +0000403 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;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000427 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000428 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000429 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000430 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000431 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000432 return 0;
433 return 1;
434 }
435
436 unsigned tryMergeSimpleControlStatement(
437 SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
438 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
439 if (Limit == 0)
440 return 0;
441 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000442 I[1]->First->is(tok::l_brace))
Daniel Jasper4281d732013-11-06 23:12:09 +0000443 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000444 if (I[1]->InPPDirective != (*I)->InPPDirective ||
445 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper4281d732013-11-06 23:12:09 +0000446 return 0;
447 AnnotatedLine &Line = **I;
448 if (Line.Last->isNot(tok::r_paren))
449 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000450 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000451 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000452 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Daniel Jasper4281d732013-11-06 23:12:09 +0000453 tok::kw_while) ||
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000454 I[1]->First->Type == TT_LineComment)
Daniel Jasper4281d732013-11-06 23:12:09 +0000455 return 0;
456 // Only inline simple if's (no nested if or else).
457 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000458 I[2]->First->is(tok::kw_else))
Daniel Jasper4281d732013-11-06 23:12:09 +0000459 return 0;
460 return 1;
461 }
462
463 unsigned
464 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator &I,
465 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
466 unsigned Limit) {
467 // No merging if the brace already is on the next line.
468 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
469 return 0;
470
471 // First, check that the current line allows merging. This is the case if
472 // we're not in a control flow statement and the last token is an opening
473 // brace.
474 AnnotatedLine &Line = **I;
475 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
476 tok::kw_else, tok::kw_try, tok::kw_catch,
477 tok::kw_for,
478 // This gets rid of all ObjC @ keywords and methods.
479 tok::at, tok::minus, tok::plus))
480 return 0;
481
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000482 FormatToken *Tok = I[1]->First;
Daniel Jasper4281d732013-11-06 23:12:09 +0000483 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
484 (Tok->getNextNonComment() == NULL ||
485 Tok->getNextNonComment()->is(tok::semi))) {
486 // We merge empty blocks even if the line exceeds the column limit.
487 Tok->SpacesRequiredBefore = 0;
488 Tok->CanBreakBefore = true;
489 return 1;
490 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
491 // Check that we still have three lines and they fit into the limit.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000492 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper4281d732013-11-06 23:12:09 +0000493 return 0;
494
495 if (!nextTwoLinesFitInto(I, Limit))
496 return 0;
497
498 // Second, check that the next line does not contain any braces - if it
499 // does, readability declines when putting it into a single line.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000500 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper4281d732013-11-06 23:12:09 +0000501 return 0;
502 do {
503 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
504 return 0;
505 Tok = Tok->Next;
506 } while (Tok != NULL);
507
508 // Last, check that the third line contains a single closing brace.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000509 Tok = I[2]->First;
Daniel Jasper4281d732013-11-06 23:12:09 +0000510 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
511 Tok->MustBreakBefore)
512 return 0;
513
514 return 2;
515 }
516 return 0;
517 }
518
519 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
520 unsigned Limit) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000521 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper4281d732013-11-06 23:12:09 +0000522 }
523
524 const FormatStyle &Style;
525};
526
Daniel Jasperbac016b2012-12-03 18:12:45 +0000527class UnwrappedLineFormatter {
528public:
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000529 UnwrappedLineFormatter(SourceManager &SourceMgr,
530 SmallVectorImpl<CharSourceRange> &Ranges,
531 ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000532 WhitespaceManager *Whitespaces,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000533 const FormatStyle &Style)
534 : SourceMgr(SourceMgr), Ranges(Ranges), Indenter(Indenter),
Daniel Jasper4281d732013-11-06 23:12:09 +0000535 Whitespaces(Whitespaces), Style(Style), Joiner(Style) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000536
Daniel Jasper4281d732013-11-06 23:12:09 +0000537 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000538 int AdditionalIndent = 0) {
539 assert(!Lines.empty());
540 unsigned Penalty = 0;
541 std::vector<int> IndentForLevel;
542 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
543 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
544 bool PreviousLineWasTouched = false;
545 const AnnotatedLine *PreviousLine = NULL;
546 bool FormatPPDirective = false;
Daniel Jasper4281d732013-11-06 23:12:09 +0000547 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
548 E = Lines.end();
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000549 I != E; ++I) {
550 const AnnotatedLine &TheLine = **I;
551 const FormatToken *FirstTok = TheLine.First;
552 int Offset = getIndentOffset(*FirstTok);
553
554 // Check whether this line is part of a formatted preprocessor directive.
555 if (FirstTok->HasUnescapedNewline)
556 FormatPPDirective = false;
557 if (!FormatPPDirective && TheLine.InPPDirective &&
558 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
559 FormatPPDirective = true;
560
561 // Determine indent and try to merge multiple unwrapped lines.
562 while (IndentForLevel.size() <= TheLine.Level)
563 IndentForLevel.push_back(-1);
564 IndentForLevel.resize(TheLine.Level + 1);
565 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
566 if (static_cast<int>(Indent) + Offset >= 0)
567 Indent += Offset;
Daniel Jasper4281d732013-11-06 23:12:09 +0000568 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
569 if (!DryRun) {
570 for (unsigned i = 0; i < MergedLines; ++i) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000571 join(*I[i], *I[i + 1]);
Daniel Jasper4281d732013-11-06 23:12:09 +0000572 }
573 }
574 I += MergedLines;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000575
576 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
577 if (TheLine.First->is(tok::eof)) {
578 if (PreviousLineWasTouched && !DryRun) {
579 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
580 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
581 /*IndentLevel=*/0, /*Spaces=*/0,
582 /*TargetColumn=*/0);
583 }
584 } else if (TheLine.Type != LT_Invalid &&
585 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
586 unsigned LevelIndent =
587 getIndent(IndentForLevel, TheLine.Level);
588 if (FirstTok->WhitespaceRange.isValid()) {
589 if (!DryRun)
590 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
591 Indent, TheLine.InPPDirective);
592 } else {
593 Indent = LevelIndent = FirstTok->OriginalColumn;
594 }
595
596 // If everything fits on a single line, just put it there.
597 unsigned ColumnLimit = Style.ColumnLimit;
598 if (I + 1 != E) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000599 AnnotatedLine *NextLine = I[1];
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000600 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
601 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
602 }
603
604 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
605 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
606 while (State.NextToken != NULL)
607 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
608 } else if (Style.ColumnLimit == 0) {
609 NoColumnLimitFormatter Formatter(Indenter);
610 if (!DryRun)
611 Formatter.format(Indent, &TheLine);
612 } else {
613 Penalty += format(TheLine, Indent, DryRun);
614 }
615
616 IndentForLevel[TheLine.Level] = LevelIndent;
617 PreviousLineWasTouched = true;
618 } else {
619 // Format the first token if necessary, and notify the WhitespaceManager
620 // about the unchanged whitespace.
621 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
622 if (Tok == TheLine.First &&
623 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
624 unsigned LevelIndent = Tok->OriginalColumn;
625 if (!DryRun) {
626 // Remove trailing whitespace of the previous line if it was
627 // touched.
628 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
629 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
630 TheLine.InPPDirective);
631 } else {
632 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
633 }
634 }
635
636 if (static_cast<int>(LevelIndent) - Offset >= 0)
637 LevelIndent -= Offset;
638 if (Tok->isNot(tok::comment))
639 IndentForLevel[TheLine.Level] = LevelIndent;
640 } else if (!DryRun) {
641 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
642 }
643 }
644 // If we did not reformat this unwrapped line, the column at the end of
645 // the last token is unchanged - thus, we can calculate the end of the
646 // last token.
647 PreviousLineWasTouched = false;
648 }
649 if (!DryRun) {
650 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
651 Tok->Finalized = true;
652 }
653 }
654 PreviousLine = *I;
655 }
656 return Penalty;
657 }
658
659private:
660 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000661 ///
662 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000663 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
664 bool DryRun) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000665 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000666
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000667 // If the ObjC method declaration does not fit on a line, we should format
668 // it with one arg per line.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000669 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000670 State.Stack.back().BreakBeforeParameter = true;
671
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000672 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000673 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000674 }
675
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000676 /// \brief An edge in the solution space from \c Previous->State to \c State,
677 /// inserting a newline dependent on the \c NewLine.
678 struct StateNode {
679 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000680 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000681 LineState State;
682 bool NewLine;
683 StateNode *Previous;
684 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000685
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000686 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
687 ///
688 /// In case of equal penalties, we want to prefer states that were inserted
689 /// first. During state generation we make sure that we insert states first
690 /// that break the line as late as possible.
691 typedef std::pair<unsigned, unsigned> OrderedPenalty;
692
693 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
694 /// \c State has the given \c OrderedPenalty.
695 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
696
697 /// \brief The BFS queue type.
698 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
699 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000700
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000701 /// \brief Get the offset of the line relatively to the level.
702 ///
703 /// For example, 'public:' labels in classes are offset by 1 or 2
704 /// characters to the left from their level.
705 int getIndentOffset(const FormatToken &RootToken) {
706 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
707 return Style.AccessModifierOffset;
708 return 0;
709 }
710
711 /// \brief Add a new line and the required indent before the first Token
712 /// of the \c UnwrappedLine if there was no structural parsing error.
713 void formatFirstToken(FormatToken &RootToken,
714 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
715 unsigned Indent, bool InPPDirective) {
716 unsigned Newlines =
717 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
718 // Remove empty lines before "}" where applicable.
719 if (RootToken.is(tok::r_brace) &&
720 (!RootToken.Next ||
721 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
722 Newlines = std::min(Newlines, 1u);
723 if (Newlines == 0 && !RootToken.IsFirst)
724 Newlines = 1;
725
726 // Insert extra new line before access specifiers.
727 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
728 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
729 ++Newlines;
730
731 // Remove empty lines after access specifiers.
732 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
733 Newlines = std::min(1u, Newlines);
734
735 Whitespaces->replaceWhitespace(
736 RootToken, Newlines, IndentLevel, Indent, Indent,
737 InPPDirective && !RootToken.HasUnescapedNewline);
738 }
739
740 /// \brief Get the indent of \p Level from \p IndentForLevel.
741 ///
742 /// \p IndentForLevel must contain the indent for the level \c l
743 /// at \p IndentForLevel[l], or a value < 0 if the indent for
744 /// that level is unknown.
745 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
746 if (IndentForLevel[Level] != -1)
747 return IndentForLevel[Level];
748 if (Level == 0)
749 return 0;
750 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
751 }
752
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000753 void join(AnnotatedLine &A, const AnnotatedLine &B) {
754 assert(!A.Last->Next);
755 assert(!B.First->Previous);
756 A.Last->Next = B.First;
757 B.First->Previous = A.Last;
Daniel Jasperc2e03292013-11-08 17:33:27 +0000758 B.First->CanBreakBefore = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000759 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
760 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
761 Tok->TotalLength += LengthA;
762 A.Last = Tok;
763 }
764 }
765
766 unsigned getColumnLimit(bool InPPDirective) const {
767 // In preprocessor directives reserve two chars for trailing " \"
768 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
769 }
770
771 bool touchesRanges(const CharSourceRange &Range) {
772 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
773 E = Ranges.end();
774 I != E; ++I) {
775 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
776 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
777 return true;
778 }
779 return false;
780 }
781
782 bool touchesLine(const AnnotatedLine &TheLine) {
783 const FormatToken *First = TheLine.First;
784 const FormatToken *Last = TheLine.Last;
785 CharSourceRange LineRange = CharSourceRange::getCharRange(
786 First->WhitespaceRange.getBegin().getLocWithOffset(
787 First->LastNewlineOffset),
788 Last->getStartOfNonWhitespace().getLocWithOffset(
789 Last->TokenText.size() - 1));
790 return touchesRanges(LineRange);
791 }
792
793 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
794 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
795 for (; I != E; ++I) {
796 if ((*I)->First->HasUnescapedNewline)
797 return false;
798 if (touchesLine(**I))
799 return true;
800 }
801 return false;
802 }
803
804 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
805 const FormatToken *First = TheLine.First;
806 CharSourceRange LineRange = CharSourceRange::getCharRange(
807 First->WhitespaceRange.getBegin(),
808 First->WhitespaceRange.getBegin().getLocWithOffset(
809 First->LastNewlineOffset));
810 return touchesRanges(LineRange);
811 }
812
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000813 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000814 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000815 /// This implements a variant of Dijkstra's algorithm on the graph that spans
816 /// the solution space (\c LineStates are the nodes). The algorithm tries to
817 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000818 /// to a state where all tokens are placed. Returns the penalty.
819 ///
820 /// If \p DryRun is \c false, directly applies the changes.
821 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000822 std::set<LineState> Seen;
823
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000824 // Increasing count of \c StateNode items we have created. This is used to
825 // create a deterministic order independent of the container.
826 unsigned Count = 0;
827 QueueType Queue;
828
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000829 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000830 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000831 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
832 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
833 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000834
Daniel Jasper567dcf92013-09-05 09:29:45 +0000835 unsigned Penalty = 0;
836
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000837 // While not empty, take first element and follow edges.
838 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000839 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000840 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000841 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000842 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000843 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000844 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000845 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000846
Daniel Jasper54b4e442013-05-22 05:27:42 +0000847 // Cut off the analysis of certain solutions if the analysis gets too
848 // complex. See description of IgnoreStackForComparison.
849 if (Count > 10000)
850 Node->State.IgnoreStackForComparison = true;
851
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000852 if (!Seen.insert(Node->State).second)
853 // State already examined with lower penalty.
854 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000855
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000856 FormatDecision LastFormat = Node->State.NextToken->Decision;
857 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000858 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000859 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000860 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000861 }
862
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000863 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000864 // We were unable to find a solution, do nothing.
865 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000866 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000867 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000868 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000869
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000870 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000871 if (!DryRun)
872 reconstructPath(InitialState, Queue.top().second);
873
Alexander Kornienkodd256312013-05-10 11:56:10 +0000874 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
875 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000876
877 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000878 }
879
880 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000881 std::deque<StateNode *> Path;
882 // We do not need a break before the initial token.
883 while (Current->Previous) {
884 Path.push_front(Current);
885 Current = Current->Previous;
886 }
887 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
888 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000889 unsigned Penalty = 0;
890 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
891 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
892
Manuel Klimek9c333b92013-05-29 15:10:11 +0000893 DEBUG({
894 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000895 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000896 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000897 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000898 }
899 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000900 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000901 }
902
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000903 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000904 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000905 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000906 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000907 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000908 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000909 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000910 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000911 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000912 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000913
914 StateNode *Node = new (Allocator.Allocate())
915 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000916 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
917 return;
918
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000919 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000920
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000921 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
922 ++(*Count);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000923 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000924
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000925 /// \brief If the \p State's next token is an r_brace closing a nested block,
926 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000927 ///
928 /// Returns \c true if all children could be placed successfully and adapts
929 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
930 /// creates changes using \c Whitespaces.
931 ///
932 /// The crucial idea here is that children always get formatted upon
933 /// encountering the closing brace right after the nested block. Now, if we
934 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
935 /// \c false), the entire block has to be kept on the same line (which is only
936 /// possible if it fits on the line, only contains a single statement, etc.
937 ///
938 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
939 /// break after the "{", format all lines with correct indentation and the put
940 /// the closing "}" on yet another new line.
941 ///
942 /// This enables us to keep the simple structure of the
943 /// \c UnwrappedLineFormatter, where we only have two options for each token:
944 /// break or don't break.
945 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
946 unsigned &Penalty) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000947 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper15eef852013-10-20 17:28:32 +0000948 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
949 if (!LBrace || LBrace->isNot(tok::l_brace) ||
950 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000951 // The previous token does not open a block. Nothing to do. We don't
952 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000953 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000954
955 if (NewLine) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000956 int AdditionalIndent = State.Stack.back().Indent -
957 Previous.Children[0]->Level * Style.IndentWidth;
958 Penalty += format(Previous.Children, DryRun, AdditionalIndent);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000959 return true;
960 }
961
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000962 // Cannot merge multiple statements into a single line.
Daniel Jasper15eef852013-10-20 17:28:32 +0000963 if (Previous.Children.size() > 1)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000964 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000965
966 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +0000967 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +0000968 return false;
969
970 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000971 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +0000972 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000973 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000974 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000975 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000976 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000977
Daniel Jasper15eef852013-10-20 17:28:32 +0000978 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000979 return true;
980 }
981
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000982 SourceManager &SourceMgr;
983 SmallVectorImpl<CharSourceRange> &Ranges;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000984 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000985 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000986 FormatStyle Style;
Daniel Jasper4281d732013-11-06 23:12:09 +0000987 LineJoiner Joiner;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000988
989 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000990};
991
Manuel Klimek96e888b2013-05-28 11:55:06 +0000992class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000993public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000994 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000995 encoding::Encoding Encoding)
Alexander Kornienkoa9f28092013-11-13 14:04:17 +0000996 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimekc41e8192013-08-29 15:21:40 +0000997 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
998 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000999 Lex.SetKeepWhitespaceMode(true);
1000 }
1001
Manuel Klimek96e888b2013-05-28 11:55:06 +00001002 ArrayRef<FormatToken *> lex() {
1003 assert(Tokens.empty());
1004 do {
1005 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001006 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +00001007 } while (Tokens.back()->Tok.isNot(tok::eof));
1008 return Tokens;
1009 }
1010
1011 IdentifierTable &getIdentTable() { return IdentTable; }
1012
1013private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001014 void maybeJoinPreviousTokens() {
1015 if (Tokens.size() < 4)
1016 return;
1017 FormatToken *Last = Tokens.back();
1018 if (!Last->is(tok::r_paren))
1019 return;
1020
1021 FormatToken *String = Tokens[Tokens.size() - 2];
1022 if (!String->is(tok::string_literal) || String->IsMultiline)
1023 return;
1024
1025 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1026 return;
1027
1028 FormatToken *Macro = Tokens[Tokens.size() - 4];
1029 if (Macro->TokenText != "_T")
1030 return;
1031
1032 const char *Start = Macro->TokenText.data();
1033 const char *End = Last->TokenText.data() + Last->TokenText.size();
1034 String->TokenText = StringRef(Start, End - Start);
1035 String->IsFirst = Macro->IsFirst;
1036 String->LastNewlineOffset = Macro->LastNewlineOffset;
1037 String->WhitespaceRange = Macro->WhitespaceRange;
1038 String->OriginalColumn = Macro->OriginalColumn;
1039 String->ColumnWidth = encoding::columnWidthWithTabs(
1040 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1041
1042 Tokens.pop_back();
1043 Tokens.pop_back();
1044 Tokens.pop_back();
1045 Tokens.back() = String;
1046 }
1047
Manuel Klimek96e888b2013-05-28 11:55:06 +00001048 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001049 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001050 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +00001051 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001052 Token Greater = FormatTok->Tok;
1053 FormatTok = new (Allocator.Allocate()) FormatToken;
1054 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001055 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001056 FormatTok->Tok.getLocation().getLocWithOffset(1);
1057 FormatTok->WhitespaceRange =
1058 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001059 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001060 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001061 GreaterStashed = false;
1062 return FormatTok;
1063 }
1064
Manuel Klimek96e888b2013-05-28 11:55:06 +00001065 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001066 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001067 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001068 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001069 FormatTok->IsFirst = IsFirstToken;
1070 IsFirstToken = false;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001071
1072 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001073 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001074 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001075 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1076 switch (FormatTok->TokenText[i]) {
1077 case '\n':
1078 ++FormatTok->NewlinesBefore;
1079 // FIXME: This is technically incorrect, as it could also
1080 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001081 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1082 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1083 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +00001084 FormatTok->HasUnescapedNewline = true;
1085 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1086 Column = 0;
1087 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001088 case '\r':
1089 case '\f':
1090 case '\v':
1091 Column = 0;
1092 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001093 case ' ':
1094 ++Column;
1095 break;
1096 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +00001097 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001098 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001099 case '\\':
1100 ++Column;
1101 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1102 FormatTok->TokenText[i + 1] != '\n'))
1103 FormatTok->Type = TT_ImplicitStringLiteral;
1104 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001105 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001106 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001107 ++Column;
1108 break;
1109 }
1110 }
1111
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001112 if (FormatTok->Type == TT_ImplicitStringLiteral)
1113 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001114 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001115
Daniel Jasper561211d2013-07-16 20:28:33 +00001116 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001117 }
Manuel Klimek95419382013-01-07 07:56:50 +00001118
Manuel Klimekd4397b92013-01-04 23:34:14 +00001119 // In case the token starts with escaped newlines, we want to
1120 // take them into account as whitespace - this pattern is quite frequent
1121 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +00001122 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001123 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1124 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001125 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001126 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001127 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +00001128 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001129 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001130
1131 FormatTok->WhitespaceRange = SourceRange(
1132 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1133
Manuel Klimekc41e8192013-08-29 15:21:40 +00001134 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001135
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001136 TrailingWhitespace = 0;
1137 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001138 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +00001139 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +00001140 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +00001141 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001142 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001143 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001144 FormatTok->Tok.setIdentifierInfo(&Info);
1145 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001146 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001147 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001148 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001149 GreaterStashed = true;
1150 }
1151
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001152 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +00001153
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001154 StringRef Text = FormatTok->TokenText;
1155 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001156 if (FirstNewlinePos == StringRef::npos) {
1157 // FIXME: ColumnWidth actually depends on the start column, we need to
1158 // take this into account when the token is moved.
1159 FormatTok->ColumnWidth =
1160 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1161 Column += FormatTok->ColumnWidth;
1162 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001163 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001164 // FIXME: ColumnWidth actually depends on the start column, we need to
1165 // take this into account when the token is moved.
1166 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1167 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1168
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001169 // The last line of the token always starts in column 0.
1170 // Thus, the length can be precomputed even in the presence of tabs.
1171 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1172 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1173 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001174 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +00001175 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001176
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001177 return FormatTok;
1178 }
1179
Manuel Klimek96e888b2013-05-28 11:55:06 +00001180 FormatToken *FormatTok;
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001181 bool IsFirstToken;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001182 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001183 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +00001184 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001185 Lexer &Lex;
1186 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001187 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001188 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001189 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001190 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1191 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001192
Daniel Jasper561211d2013-07-16 20:28:33 +00001193 void readRawToken(FormatToken &Tok) {
1194 Lex.LexFromRawLexer(Tok.Tok);
1195 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1196 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +00001197 // For formatting, treat unterminated string literals like normal string
1198 // literals.
1199 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1200 Tok.TokenText[0] == '"') {
1201 Tok.Tok.setKind(tok::string_literal);
1202 Tok.IsUnterminatedLiteral = true;
1203 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001204 }
1205};
1206
Daniel Jasperbac016b2012-12-03 18:12:45 +00001207class Formatter : public UnwrappedLineConsumer {
1208public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001209 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001210 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001211 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001212 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001213 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001214 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001215 DEBUG(llvm::dbgs() << "File encoding: "
1216 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1217 : "unknown")
1218 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001219 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001220
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001221 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001222 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001223 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001224
1225 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001226 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001227 assert(UnwrappedLines.rbegin()->empty());
1228 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1229 ++Run) {
1230 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1231 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1232 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1233 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1234 }
1235 tooling::Replacements RunResult =
1236 format(AnnotatedLines, StructuralError, Tokens);
1237 DEBUG({
1238 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1239 for (tooling::Replacements::iterator I = RunResult.begin(),
1240 E = RunResult.end();
1241 I != E; ++I) {
1242 llvm::dbgs() << I->toString() << "\n";
1243 }
1244 });
1245 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1246 delete AnnotatedLines[i];
1247 }
1248 Result.insert(RunResult.begin(), RunResult.end());
1249 Whitespaces.reset();
1250 }
1251 return Result;
1252 }
1253
1254 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1255 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +00001256 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
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.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001259 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001260 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001261 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001262 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001263 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001264
Daniel Jasperb77d7412013-09-06 07:54:20 +00001265 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001266 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1267 BinPackInconclusiveFunctions);
1268 UnwrappedLineFormatter Formatter(SourceMgr, Ranges, &Indenter, &Whitespaces,
1269 Style);
1270 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001271 return Whitespaces.generateReplacements();
1272 }
1273
1274private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001275 static bool inputUsesCRLF(StringRef Text) {
1276 return Text.count('\r') * 2 > Text.count('\n');
1277 }
1278
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001279 void
1280 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001281 unsigned CountBoundToVariable = 0;
1282 unsigned CountBoundToType = 0;
1283 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001284 bool HasBinPackedFunction = false;
1285 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001286 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001287 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001288 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001289 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001290 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001291 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001292 bool SpacesBefore =
1293 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1294 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1295 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001296 if (SpacesBefore && !SpacesAfter)
1297 ++CountBoundToVariable;
1298 else if (!SpacesBefore && SpacesAfter)
1299 ++CountBoundToType;
1300 }
1301
Daniel Jasper78a4e612013-10-12 05:16:06 +00001302 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1303 if (Tok->is(tok::coloncolon) &&
1304 Tok->Previous->Type == TT_TemplateOpener)
1305 HasCpp03IncompatibleFormat = true;
1306 if (Tok->Type == TT_TemplateCloser &&
1307 Tok->Previous->Type == TT_TemplateCloser)
1308 HasCpp03IncompatibleFormat = true;
1309 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001310
1311 if (Tok->PackingKind == PPK_BinPacked)
1312 HasBinPackedFunction = true;
1313 if (Tok->PackingKind == PPK_OnePerLine)
1314 HasOnePerLineFunction = true;
1315
Manuel Klimekb3987012013-05-29 14:47:47 +00001316 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001317 }
1318 }
1319 if (Style.DerivePointerBinding) {
1320 if (CountBoundToType > CountBoundToVariable)
1321 Style.PointerBindsToType = true;
1322 else if (CountBoundToType < CountBoundToVariable)
1323 Style.PointerBindsToType = false;
1324 }
1325 if (Style.Standard == FormatStyle::LS_Auto) {
1326 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1327 : FormatStyle::LS_Cpp03;
1328 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001329 BinPackInconclusiveFunctions =
1330 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001331 }
1332
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001333 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001334 assert(!UnwrappedLines.empty());
1335 UnwrappedLines.back().push_back(TheLine);
1336 }
1337
1338 virtual void finishRun() {
1339 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001340 }
1341
1342 FormatStyle Style;
1343 Lexer &Lex;
1344 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001345 WhitespaceManager Whitespaces;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001346 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001347 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001348
1349 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001350 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001351};
1352
Craig Topper83f81d72013-06-30 22:29:28 +00001353} // end anonymous namespace
1354
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001355tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1356 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001357 std::vector<CharSourceRange> Ranges) {
1358 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001359 return formatter.format();
1360}
1361
Daniel Jasper8a999452013-05-16 10:40:07 +00001362tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1363 std::vector<tooling::Range> Ranges,
1364 StringRef FileName) {
1365 FileManager Files((FileSystemOptions()));
1366 DiagnosticsEngine Diagnostics(
1367 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1368 new DiagnosticOptions);
1369 SourceManager SourceMgr(Diagnostics, Files);
1370 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1371 const clang::FileEntry *Entry =
1372 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1373 SourceMgr.overrideFileContents(Entry, Buf);
1374 FileID ID =
1375 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001376 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1377 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001378 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1379 std::vector<CharSourceRange> CharRanges;
1380 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1381 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1382 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1383 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1384 }
1385 return reformat(Style, Lex, SourceMgr, CharRanges);
1386}
1387
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001388LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001389 LangOptions LangOpts;
1390 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001391 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001392 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001393 LangOpts.Bool = 1;
1394 LangOpts.ObjC1 = 1;
1395 LangOpts.ObjC2 = 1;
1396 return LangOpts;
1397}
1398
Edwin Vanef4e12c82013-09-30 13:31:48 +00001399const char *StyleOptionHelpDescription =
1400 "Coding style, currently supports:\n"
1401 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1402 "Use -style=file to load style configuration from\n"
1403 ".clang-format file located in one of the parent\n"
1404 "directories of the source file (or current\n"
1405 "directory for stdin).\n"
1406 "Use -style=\"{key: value, ...}\" to set specific\n"
1407 "parameters, e.g.:\n"
1408 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1409
1410FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1411 // Fallback style in case the rest of this function can't determine a style.
1412 StringRef FallbackStyle = "LLVM";
1413 FormatStyle Style;
1414 getPredefinedStyle(FallbackStyle, &Style);
1415
1416 if (StyleName.startswith("{")) {
1417 // Parse YAML/JSON style from the command line.
1418 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001419 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1420 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00001421 }
1422 return Style;
1423 }
1424
1425 if (!StyleName.equals_lower("file")) {
1426 if (!getPredefinedStyle(StyleName, &Style))
1427 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1428 << " style\n";
1429 return Style;
1430 }
1431
1432 SmallString<128> Path(FileName);
1433 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001434 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00001435 Directory = llvm::sys::path::parent_path(Directory)) {
1436 if (!llvm::sys::fs::is_directory(Directory))
1437 continue;
1438 SmallString<128> ConfigFile(Directory);
1439
1440 llvm::sys::path::append(ConfigFile, ".clang-format");
1441 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1442 bool IsFile = false;
1443 // Ignore errors from is_regular_file: we only need to know if we can read
1444 // the file or not.
1445 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1446
1447 if (!IsFile) {
1448 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1449 ConfigFile = Directory;
1450 llvm::sys::path::append(ConfigFile, "_clang-format");
1451 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1452 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1453 }
1454
1455 if (IsFile) {
1456 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola28ce23a2013-10-25 19:00:49 +00001457 if (llvm::error_code ec =
1458 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vanef4e12c82013-09-30 13:31:48 +00001459 llvm::errs() << ec.message() << "\n";
1460 continue;
1461 }
1462 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1463 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1464 << "\n";
1465 continue;
1466 }
1467 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1468 return Style;
1469 }
1470 }
1471 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1472 << " style\n";
1473 return Style;
1474}
1475
Daniel Jaspercd162382013-01-07 13:26:07 +00001476} // namespace format
1477} // namespace clang