blob: fd84454d9074200c79a9d3f53894d5bd0739cc7c [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper6b2afe42013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Edwin Vanef4e12c82013-09-30 13:31:48 +000030#include "llvm/Support/Path.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod71ec162013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000040 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000041 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000042 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000043 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
44 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
45 }
46};
47
Daniel Jasper1fb8d882013-05-14 09:30:02 +000048template <>
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000049struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +000050 static void enumeration(IO &IO,
51 clang::format::FormatStyle::UseTabStyle &Value) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000052 IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never);
53 IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never);
54 IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always);
55 IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always);
56 IO.enumCase(Value, "ForIndentation",
57 clang::format::FormatStyle::UT_ForIndentation);
58 }
59};
60
61template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000062struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
63 static void
64 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
65 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
66 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
67 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000068 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000069 }
70};
71
Daniel Jaspereff18b92013-07-31 23:16:02 +000072template <>
73struct ScalarEnumerationTraits<
74 clang::format::FormatStyle::NamespaceIndentationKind> {
75 static void
76 enumeration(IO &IO,
77 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
78 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
79 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
80 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
81 }
82};
83
Alexander Kornienkod71ec162013-05-07 15:32:14 +000084template <> struct MappingTraits<clang::format::FormatStyle> {
85 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000086 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000087 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
88 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000089 ArrayRef<StringRef> Styles(StylesArray);
90 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
91 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000092 clang::format::FormatStyle PredefinedStyle;
93 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
94 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000095 IO.mapOptional("# BasedOnStyle", StyleName);
96 break;
97 }
98 }
99 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 StringRef BasedOnStyle;
101 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000102 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000103 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
104 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
105 return;
106 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000107 }
108
109 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +0000110 IO.mapOptional("ConstructorInitializerIndentWidth",
111 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000112 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000113 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
115 Style.AllowAllParametersOfDeclarationOnNextLine);
116 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
117 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000118 IO.mapOptional("AllowShortLoopsOnASingleLine",
119 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000120 IO.mapOptional("AlwaysBreakTemplateDeclarations",
121 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000122 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
123 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000124 IO.mapOptional("BreakBeforeBinaryOperators",
125 Style.BreakBeforeBinaryOperators);
126 IO.mapOptional("BreakConstructorInitializersBeforeComma",
127 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000128 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
129 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
130 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
131 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
132 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000133 IO.mapOptional("ExperimentalAutoDetectBinPacking",
134 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000135 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
136 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000137 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000138 IO.mapOptional("ObjCSpaceBeforeProtocolList",
139 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper47066e42013-10-25 14:29:37 +0000140 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
141 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000142 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
143 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000144 IO.mapOptional("PenaltyBreakFirstLessLess",
145 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000146 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
147 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
148 Style.PenaltyReturnTypeOnItsOwnLine);
149 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
150 IO.mapOptional("SpacesBeforeTrailingComments",
151 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000152 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000153 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000154 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000155 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000156 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000157 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000158 IO.mapOptional("IndentFunctionDeclarationAfterType",
159 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000160 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000161 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000162 IO.mapOptional("SpacesInCStyleCastParentheses",
163 Style.SpacesInCStyleCastParentheses);
164 IO.mapOptional("SpaceAfterControlStatementKeyword",
165 Style.SpaceAfterControlStatementKeyword);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000166 IO.mapOptional("SpaceBeforeAssignmentOperators",
167 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000168 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000169 }
170};
171}
172}
173
Daniel Jasperbac016b2012-12-03 18:12:45 +0000174namespace clang {
175namespace format {
176
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000177void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000178 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000179 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000180 Style.PenaltyBreakString = 1000;
181 Style.PenaltyExcessCharacter = 1000000;
182}
183
Daniel Jasperbac016b2012-12-03 18:12:45 +0000184FormatStyle getLLVMStyle() {
185 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000187 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000188 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000189 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000190 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000191 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000192 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000193 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000194 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000195 LLVMStyle.BreakBeforeBinaryOperators = false;
196 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
197 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000198 LLVMStyle.ColumnLimit = 80;
199 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000200 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000201 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000202 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000203 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000204 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000205 LLVMStyle.IndentFunctionDeclarationAfterType = false;
206 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000207 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000208 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000209 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000210 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000211 LLVMStyle.PointerBindsToType = false;
212 LLVMStyle.SpacesBeforeTrailingComments = 1;
213 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000214 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000215 LLVMStyle.SpacesInParentheses = false;
216 LLVMStyle.SpaceInEmptyParentheses = false;
217 LLVMStyle.SpacesInCStyleCastParentheses = false;
218 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000219 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000220 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000221
222 setDefaultPenalties(LLVMStyle);
223 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper47066e42013-10-25 14:29:37 +0000224 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000225
Daniel Jasperbac016b2012-12-03 18:12:45 +0000226 return LLVMStyle;
227}
228
229FormatStyle getGoogleStyle() {
230 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000231 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000232 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000233 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000234 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000235 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000236 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000237 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000238 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000239 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000240 GoogleStyle.BreakBeforeBinaryOperators = false;
241 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
242 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000243 GoogleStyle.ColumnLimit = 80;
244 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000245 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000246 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000247 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000248 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000249 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000250 GoogleStyle.IndentFunctionDeclarationAfterType = true;
251 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000252 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000253 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000254 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000255 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000256 GoogleStyle.PointerBindsToType = true;
257 GoogleStyle.SpacesBeforeTrailingComments = 2;
258 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000259 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000260 GoogleStyle.SpacesInParentheses = false;
261 GoogleStyle.SpaceInEmptyParentheses = false;
262 GoogleStyle.SpacesInCStyleCastParentheses = false;
263 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000264 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000265 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000266
267 setDefaultPenalties(GoogleStyle);
268 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper47066e42013-10-25 14:29:37 +0000269 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000270
Daniel Jasperbac016b2012-12-03 18:12:45 +0000271 return GoogleStyle;
272}
273
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000274FormatStyle getChromiumStyle() {
275 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000276 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000277 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000278 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000279 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000280 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000281 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000282 return ChromiumStyle;
283}
284
Alexander Kornienkofb594862013-05-06 14:11:27 +0000285FormatStyle getMozillaStyle() {
286 FormatStyle MozillaStyle = getLLVMStyle();
287 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
288 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
289 MozillaStyle.DerivePointerBinding = true;
290 MozillaStyle.IndentCaseLabels = true;
291 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
292 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
293 MozillaStyle.PointerBindsToType = true;
294 return MozillaStyle;
295}
296
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000297FormatStyle getWebKitStyle() {
298 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000299 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000300 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000301 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000302 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000303 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000304 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000305 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000306 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000307 Style.PointerBindsToType = true;
308 return Style;
309}
310
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000311bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000312 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000313 *Style = getLLVMStyle();
314 else if (Name.equals_lower("chromium"))
315 *Style = getChromiumStyle();
316 else if (Name.equals_lower("mozilla"))
317 *Style = getMozillaStyle();
318 else if (Name.equals_lower("google"))
319 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000320 else if (Name.equals_lower("webkit"))
321 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000322 else
323 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000324
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000325 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000326}
327
328llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000329 if (Text.trim().empty())
330 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000331 llvm::yaml::Input Input(Text);
332 Input >> *Style;
333 return Input.error();
334}
335
336std::string configurationAsText(const FormatStyle &Style) {
337 std::string Text;
338 llvm::raw_string_ostream Stream(Text);
339 llvm::yaml::Output Output(Stream);
340 // We use the same mapping method for input and output, so we need a non-const
341 // reference here.
342 FormatStyle NonConstStyle = Style;
343 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000344 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000345}
346
Craig Topper83f81d72013-06-30 22:29:28 +0000347namespace {
348
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000349class NoColumnLimitFormatter {
350public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000351 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000352
353 /// \brief Formats the line starting at \p State, simply keeping all of the
354 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000355 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000356 LineState State =
357 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000358 while (State.NextToken != NULL) {
359 bool Newline =
360 Indenter->mustBreak(State) ||
361 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
362 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
363 }
364 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000365
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000366private:
367 ContinuationIndenter *Indenter;
368};
369
Daniel Jasperbac016b2012-12-03 18:12:45 +0000370class UnwrappedLineFormatter {
371public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000372 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000373 WhitespaceManager *Whitespaces,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000374 const FormatStyle &Style, const AnnotatedLine &Line)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000375 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
376 Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000377
Daniel Jasper567dcf92013-09-05 09:29:45 +0000378 /// \brief Formats an \c UnwrappedLine and returns the penalty.
379 ///
380 /// If \p DryRun is \c false, directly applies the changes.
381 unsigned format(unsigned FirstIndent, bool DryRun = false) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000382 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000383
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000384 // If the ObjC method declaration does not fit on a line, we should format
385 // it with one arg per line.
386 if (Line.Type == LT_ObjCMethodDecl)
387 State.Stack.back().BreakBeforeParameter = true;
388
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000389 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000390 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000391 }
392
393private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000394 /// \brief An edge in the solution space from \c Previous->State to \c State,
395 /// inserting a newline dependent on the \c NewLine.
396 struct StateNode {
397 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000398 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000399 LineState State;
400 bool NewLine;
401 StateNode *Previous;
402 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000403
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000404 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
405 ///
406 /// In case of equal penalties, we want to prefer states that were inserted
407 /// first. During state generation we make sure that we insert states first
408 /// that break the line as late as possible.
409 typedef std::pair<unsigned, unsigned> OrderedPenalty;
410
411 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
412 /// \c State has the given \c OrderedPenalty.
413 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
414
415 /// \brief The BFS queue type.
416 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
417 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000418
419 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000420 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000421 /// This implements a variant of Dijkstra's algorithm on the graph that spans
422 /// the solution space (\c LineStates are the nodes). The algorithm tries to
423 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000424 /// to a state where all tokens are placed. Returns the penalty.
425 ///
426 /// If \p DryRun is \c false, directly applies the changes.
427 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000428 std::set<LineState> Seen;
429
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000430 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000431 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000432 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
433 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
434 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000435
Daniel Jasper567dcf92013-09-05 09:29:45 +0000436 unsigned Penalty = 0;
437
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000438 // While not empty, take first element and follow edges.
439 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000440 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000441 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000442 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000443 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000444 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000445 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000446 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000447
Daniel Jasper54b4e442013-05-22 05:27:42 +0000448 // Cut off the analysis of certain solutions if the analysis gets too
449 // complex. See description of IgnoreStackForComparison.
450 if (Count > 10000)
451 Node->State.IgnoreStackForComparison = true;
452
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000453 if (!Seen.insert(Node->State).second)
454 // State already examined with lower penalty.
455 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000456
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000457 FormatDecision LastFormat = Node->State.NextToken->Decision;
458 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
459 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
460 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
461 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000462 }
463
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000464 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000465 // We were unable to find a solution, do nothing.
466 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000467 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000468 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000469 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000470
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000471 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000472 if (!DryRun)
473 reconstructPath(InitialState, Queue.top().second);
474
Alexander Kornienkodd256312013-05-10 11:56:10 +0000475 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
476 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000477
478 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000479 }
480
481 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000482 std::deque<StateNode *> Path;
483 // We do not need a break before the initial token.
484 while (Current->Previous) {
485 Path.push_front(Current);
486 Current = Current->Previous;
487 }
488 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
489 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000490 unsigned Penalty = 0;
491 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
492 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
493
Manuel Klimek9c333b92013-05-29 15:10:11 +0000494 DEBUG({
495 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000496 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000497 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000498 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000499 }
500 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000501 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000502 }
503
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000504 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000505 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000506 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000507 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000508 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
509 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000510 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000511 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000512 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000513 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000514
515 StateNode *Node = new (Allocator.Allocate())
516 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000517 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
518 return;
519
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000520 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000521
522 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
523 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000524 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000525
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000526 /// \brief If the \p State's next token is an r_brace closing a nested block,
527 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000528 ///
529 /// Returns \c true if all children could be placed successfully and adapts
530 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
531 /// creates changes using \c Whitespaces.
532 ///
533 /// The crucial idea here is that children always get formatted upon
534 /// encountering the closing brace right after the nested block. Now, if we
535 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
536 /// \c false), the entire block has to be kept on the same line (which is only
537 /// possible if it fits on the line, only contains a single statement, etc.
538 ///
539 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
540 /// break after the "{", format all lines with correct indentation and the put
541 /// the closing "}" on yet another new line.
542 ///
543 /// This enables us to keep the simple structure of the
544 /// \c UnwrappedLineFormatter, where we only have two options for each token:
545 /// break or don't break.
546 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
547 unsigned &Penalty) {
Daniel Jasper15eef852013-10-20 17:28:32 +0000548 const FormatToken &Previous = *State.NextToken->Previous;
549 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
550 if (!LBrace || LBrace->isNot(tok::l_brace) ||
551 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000552 // The previous token does not open a block. Nothing to do. We don't
553 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000554 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000555
556 if (NewLine) {
557 unsigned ParentIndent = State.Stack.back().Indent;
558 for (SmallVector<AnnotatedLine *, 1>::const_iterator
Daniel Jasper15eef852013-10-20 17:28:32 +0000559 I = Previous.Children.begin(),
560 E = Previous.Children.end();
Daniel Jasper567dcf92013-09-05 09:29:45 +0000561 I != E; ++I) {
562 unsigned Indent =
Daniel Jasper57981202013-09-13 09:20:45 +0000563 ParentIndent + ((*I)->Level - Line.Level - 1) * Style.IndentWidth;
Daniel Jasper14e25c02013-09-08 14:07:57 +0000564 if (!DryRun) {
565 unsigned Newlines = std::min((*I)->First->NewlinesBefore,
566 Style.MaxEmptyLinesToKeep + 1);
567 Newlines = std::max(1u, Newlines);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000568 Whitespaces->replaceWhitespace(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000569 *(*I)->First, Newlines, (*I)->Level, /*Spaces=*/Indent,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000570 /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000571 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000572 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
573 Penalty += Formatter.format(Indent, DryRun);
574 }
575 return true;
576 }
577
Daniel Jasper15eef852013-10-20 17:28:32 +0000578 if (Previous.Children.size() > 1)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000579 return false; // Cannot merge multiple statements into a single line.
580
581 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +0000582 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +0000583 return false;
584
585 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000586 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +0000587 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000588 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000589 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000590 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style,
Daniel Jasper15eef852013-10-20 17:28:32 +0000591 *Previous.Children[0]);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000592 Penalty += Formatter.format(State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000593 }
594
Daniel Jasper15eef852013-10-20 17:28:32 +0000595 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000596 return true;
597 }
598
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000599 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000600 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000602 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000603
604 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
605 QueueType Queue;
606 // Increasing count of \c StateNode items we have created. This is used
607 // to create a deterministic order independent of the container.
608 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000609};
610
Manuel Klimek96e888b2013-05-28 11:55:06 +0000611class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000612public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000613 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000614 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000615 : FormatTok(NULL), GreaterStashed(false), Column(0),
616 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
617 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000618 Lex.SetKeepWhitespaceMode(true);
619 }
620
Manuel Klimek96e888b2013-05-28 11:55:06 +0000621 ArrayRef<FormatToken *> lex() {
622 assert(Tokens.empty());
623 do {
624 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000625 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +0000626 } while (Tokens.back()->Tok.isNot(tok::eof));
627 return Tokens;
628 }
629
630 IdentifierTable &getIdentTable() { return IdentTable; }
631
632private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000633 void maybeJoinPreviousTokens() {
634 if (Tokens.size() < 4)
635 return;
636 FormatToken *Last = Tokens.back();
637 if (!Last->is(tok::r_paren))
638 return;
639
640 FormatToken *String = Tokens[Tokens.size() - 2];
641 if (!String->is(tok::string_literal) || String->IsMultiline)
642 return;
643
644 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
645 return;
646
647 FormatToken *Macro = Tokens[Tokens.size() - 4];
648 if (Macro->TokenText != "_T")
649 return;
650
651 const char *Start = Macro->TokenText.data();
652 const char *End = Last->TokenText.data() + Last->TokenText.size();
653 String->TokenText = StringRef(Start, End - Start);
654 String->IsFirst = Macro->IsFirst;
655 String->LastNewlineOffset = Macro->LastNewlineOffset;
656 String->WhitespaceRange = Macro->WhitespaceRange;
657 String->OriginalColumn = Macro->OriginalColumn;
658 String->ColumnWidth = encoding::columnWidthWithTabs(
659 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
660
661 Tokens.pop_back();
662 Tokens.pop_back();
663 Tokens.pop_back();
664 Tokens.back() = String;
665 }
666
Manuel Klimek96e888b2013-05-28 11:55:06 +0000667 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000668 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000669 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000670 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000671 Token Greater = FormatTok->Tok;
672 FormatTok = new (Allocator.Allocate()) FormatToken;
673 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000674 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000675 FormatTok->Tok.getLocation().getLocWithOffset(1);
676 FormatTok->WhitespaceRange =
677 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000678 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000679 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000680 GreaterStashed = false;
681 return FormatTok;
682 }
683
Manuel Klimek96e888b2013-05-28 11:55:06 +0000684 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000685 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000686 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000687 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000688 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000689 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000690
691 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000692 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000693 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000694 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
695 switch (FormatTok->TokenText[i]) {
696 case '\n':
697 ++FormatTok->NewlinesBefore;
698 // FIXME: This is technically incorrect, as it could also
699 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000700 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
701 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
702 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +0000703 FormatTok->HasUnescapedNewline = true;
704 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
705 Column = 0;
706 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000707 case '\r':
708 case '\f':
709 case '\v':
710 Column = 0;
711 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000712 case ' ':
713 ++Column;
714 break;
715 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000716 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000717 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000718 case '\\':
719 ++Column;
720 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
721 FormatTok->TokenText[i + 1] != '\n'))
722 FormatTok->Type = TT_ImplicitStringLiteral;
723 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000724 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000725 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000726 ++Column;
727 break;
728 }
729 }
730
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000731 if (FormatTok->Type == TT_ImplicitStringLiteral)
732 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000733 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000734
Daniel Jasper561211d2013-07-16 20:28:33 +0000735 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000736 }
Manuel Klimek95419382013-01-07 07:56:50 +0000737
Manuel Klimekd4397b92013-01-04 23:34:14 +0000738 // In case the token starts with escaped newlines, we want to
739 // take them into account as whitespace - this pattern is quite frequent
740 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +0000741 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000742 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
743 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000744 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000745 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000746 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000747 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000748 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000749
750 FormatTok->WhitespaceRange = SourceRange(
751 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
752
Manuel Klimekc41e8192013-08-29 15:21:40 +0000753 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000754
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000755 TrailingWhitespace = 0;
756 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000757 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000758 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +0000759 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +0000760 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000761 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000762 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000763 FormatTok->Tok.setIdentifierInfo(&Info);
764 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000765 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000766 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000767 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000768 GreaterStashed = true;
769 }
770
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000771 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +0000772
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000773 StringRef Text = FormatTok->TokenText;
774 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000775 if (FirstNewlinePos == StringRef::npos) {
776 // FIXME: ColumnWidth actually depends on the start column, we need to
777 // take this into account when the token is moved.
778 FormatTok->ColumnWidth =
779 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
780 Column += FormatTok->ColumnWidth;
781 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000782 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000783 // FIXME: ColumnWidth actually depends on the start column, we need to
784 // take this into account when the token is moved.
785 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
786 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
787
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000788 // The last line of the token always starts in column 0.
789 // Thus, the length can be precomputed even in the presence of tabs.
790 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
791 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
792 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000793 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000794 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000795
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000796 return FormatTok;
797 }
798
Manuel Klimek96e888b2013-05-28 11:55:06 +0000799 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000800 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000801 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000802 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000803 Lexer &Lex;
804 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000805 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000806 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000807 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000808 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
809 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000810
Daniel Jasper561211d2013-07-16 20:28:33 +0000811 void readRawToken(FormatToken &Tok) {
812 Lex.LexFromRawLexer(Tok.Tok);
813 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
814 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000815 // For formatting, treat unterminated string literals like normal string
816 // literals.
817 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
818 Tok.TokenText[0] == '"') {
819 Tok.Tok.setKind(tok::string_literal);
820 Tok.IsUnterminatedLiteral = true;
821 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000822 }
823};
824
Daniel Jasperbac016b2012-12-03 18:12:45 +0000825class Formatter : public UnwrappedLineConsumer {
826public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000827 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000828 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000829 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000830 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000831 Ranges(Ranges), UnwrappedLines(1),
832 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000833 DEBUG(llvm::dbgs() << "File encoding: "
834 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
835 : "unknown")
836 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000837 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000838
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000839 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000840 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000841 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000842
843 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000844 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000845 assert(UnwrappedLines.rbegin()->empty());
846 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
847 ++Run) {
848 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
849 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
850 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
851 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
852 }
853 tooling::Replacements RunResult =
854 format(AnnotatedLines, StructuralError, Tokens);
855 DEBUG({
856 llvm::dbgs() << "Replacements for run " << Run << ":\n";
857 for (tooling::Replacements::iterator I = RunResult.begin(),
858 E = RunResult.end();
859 I != E; ++I) {
860 llvm::dbgs() << I->toString() << "\n";
861 }
862 });
863 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
864 delete AnnotatedLines[i];
865 }
866 Result.insert(RunResult.begin(), RunResult.end());
867 Whitespaces.reset();
868 }
869 return Result;
870 }
871
872 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
873 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000874 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000875 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000876 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000877 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000878 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000879 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000880 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000881 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000882
Daniel Jasperb77d7412013-09-06 07:54:20 +0000883 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper5999f762013-04-09 17:46:55 +0000884
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000885 std::vector<int> IndentForLevel;
886 bool PreviousLineWasTouched = false;
Daniel Jasper63cfb892013-10-06 11:40:08 +0000887 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000888 bool FormatPPDirective = false;
Daniel Jasperb77d7412013-09-06 07:54:20 +0000889 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
890 E = AnnotatedLines.end();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000891 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000892 const AnnotatedLine &TheLine = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000893 const FormatToken *FirstTok = TheLine.First;
894 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000895
896 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000897 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000898 FormatPPDirective = false;
899 if (!FormatPPDirective && TheLine.InPPDirective &&
900 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
901 FormatPPDirective = true;
902
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000903 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000904 while (IndentForLevel.size() <= TheLine.Level)
905 IndentForLevel.push_back(-1);
906 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000907 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
908 if (static_cast<int>(Indent) + Offset >= 0)
909 Indent += Offset;
910 tryFitMultipleLinesInOne(Indent, I, E);
911
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000912 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000913 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000914 if (PreviousLineWasTouched) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000915 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
916 Whitespaces.replaceWhitespace(*TheLine.First, Newlines,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000917 /*IndentLevel=*/0, /*Spaces=*/0,
918 /*TargetColumn=*/0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000919 }
920 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000921 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000922 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Daniel Jasper0baf33b2013-10-18 17:20:57 +0000923 if (FirstTok->WhitespaceRange.isValid()) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000924 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000925 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000926 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000927 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000928 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000929 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000930 BinPackInconclusiveFunctions);
931
932 // If everything fits on a single line, just put it there.
933 unsigned ColumnLimit = Style.ColumnLimit;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000934 AnnotatedLine *NextLine = *(I + 1);
935 if ((I + 1) != E && NextLine->InPPDirective &&
936 !NextLine->First->HasUnescapedNewline)
937 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000938
Daniel Jasper567dcf92013-09-05 09:29:45 +0000939 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000940 LineState State =
941 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000942 while (State.NextToken != NULL)
943 Indenter.addTokenToState(State, false, false);
944 } else if (Style.ColumnLimit == 0) {
945 NoColumnLimitFormatter Formatter(&Indenter);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000946 Formatter.format(Indent, &TheLine);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000947 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000948 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
949 TheLine);
950 Formatter.format(Indent);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000951 }
952
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000953 IndentForLevel[TheLine.Level] = LevelIndent;
954 PreviousLineWasTouched = true;
955 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000956 // Format the first token if necessary, and notify the WhitespaceManager
957 // about the unchanged whitespace.
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000958 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000959 if (Tok == TheLine.First &&
960 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000961 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000962 // Remove trailing whitespace of the previous line if it was
963 // touched.
964 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000965 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000966 TheLine.InPPDirective);
967 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000968 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000969 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000970
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000971 if (static_cast<int>(LevelIndent) - Offset >= 0)
972 LevelIndent -= Offset;
973 if (Tok->isNot(tok::comment))
974 IndentForLevel[TheLine.Level] = LevelIndent;
975 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000976 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000977 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000978 }
979 // If we did not reformat this unwrapped line, the column at the end of
980 // the last token is unchanged - thus, we can calculate the end of the
981 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000982 PreviousLineWasTouched = false;
983 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000984 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
985 Tok->Finalized = true;
986 }
Daniel Jasper63cfb892013-10-06 11:40:08 +0000987 PreviousLine = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000988 }
989 return Whitespaces.generateReplacements();
990 }
991
992private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000993 static bool inputUsesCRLF(StringRef Text) {
994 return Text.count('\r') * 2 > Text.count('\n');
995 }
996
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000997 void
998 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000999 unsigned CountBoundToVariable = 0;
1000 unsigned CountBoundToType = 0;
1001 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001002 bool HasBinPackedFunction = false;
1003 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001004 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001005 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001006 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001007 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001008 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001009 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001010 bool SpacesBefore =
1011 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1012 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1013 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001014 if (SpacesBefore && !SpacesAfter)
1015 ++CountBoundToVariable;
1016 else if (!SpacesBefore && SpacesAfter)
1017 ++CountBoundToType;
1018 }
1019
Daniel Jasper78a4e612013-10-12 05:16:06 +00001020 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1021 if (Tok->is(tok::coloncolon) &&
1022 Tok->Previous->Type == TT_TemplateOpener)
1023 HasCpp03IncompatibleFormat = true;
1024 if (Tok->Type == TT_TemplateCloser &&
1025 Tok->Previous->Type == TT_TemplateCloser)
1026 HasCpp03IncompatibleFormat = true;
1027 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001028
1029 if (Tok->PackingKind == PPK_BinPacked)
1030 HasBinPackedFunction = true;
1031 if (Tok->PackingKind == PPK_OnePerLine)
1032 HasOnePerLineFunction = true;
1033
Manuel Klimekb3987012013-05-29 14:47:47 +00001034 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001035 }
1036 }
1037 if (Style.DerivePointerBinding) {
1038 if (CountBoundToType > CountBoundToVariable)
1039 Style.PointerBindsToType = true;
1040 else if (CountBoundToType < CountBoundToVariable)
1041 Style.PointerBindsToType = false;
1042 }
1043 if (Style.Standard == FormatStyle::LS_Auto) {
1044 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1045 : FormatStyle::LS_Cpp03;
1046 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001047 BinPackInconclusiveFunctions =
1048 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001049 }
1050
Manuel Klimek547d5db2013-02-08 17:38:27 +00001051 /// \brief Get the indent of \p Level from \p IndentForLevel.
1052 ///
1053 /// \p IndentForLevel must contain the indent for the level \c l
1054 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1055 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001056 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001057 if (IndentForLevel[Level] != -1)
1058 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001059 if (Level == 0)
1060 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001061 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001062 }
1063
1064 /// \brief Get the offset of the line relatively to the level.
1065 ///
1066 /// For example, 'public:' labels in classes are offset by 1 or 2
1067 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001068 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001069 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001070 return Style.AccessModifierOffset;
1071 return 0;
1072 }
1073
Manuel Klimek517e8942013-01-11 17:54:10 +00001074 /// \brief Tries to merge lines into one.
1075 ///
1076 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1077 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001078 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperb77d7412013-09-06 07:54:20 +00001079 SmallVectorImpl<AnnotatedLine *>::iterator &I,
1080 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001081 // We can never merge stuff if there are trailing line comments.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001082 AnnotatedLine *TheLine = *I;
1083 if (TheLine->Last->Type == TT_LineComment)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001084 return;
1085
Daniel Jaspere05dc6d2013-07-24 13:10:59 +00001086 if (Indent > Style.ColumnLimit)
1087 return;
1088
Daniel Jaspera4d46212013-02-28 11:05:57 +00001089 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001090 // If we already exceed the column limit, we set 'Limit' to 0. The different
1091 // tryMerge..() functions can then decide whether to still do merging.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001092 Limit = TheLine->Last->TotalLength > Limit
1093 ? 0
1094 : Limit - TheLine->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001095
Daniel Jasper567dcf92013-09-05 09:29:45 +00001096 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001097 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001098
Daniel Jasper567dcf92013-09-05 09:29:45 +00001099 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001100 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001101 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001102 TheLine->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001103 tryMergeSimpleControlStatement(I, E, Limit);
1104 } else if (Style.AllowShortLoopsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001105 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001106 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001107 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
1108 TheLine->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001109 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001110 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001111 }
1112
Daniel Jasperb77d7412013-09-06 07:54:20 +00001113 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1114 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001115 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001116 if (Limit == 0)
1117 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001118 AnnotatedLine &Line = **I;
1119 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001120 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001121 if (I + 2 != E && (*(I + 2))->InPPDirective &&
1122 !(*(I + 2))->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001123 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001124 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001125 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001126 join(Line, **(++I));
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001127 }
1128
Daniel Jasperb77d7412013-09-06 07:54:20 +00001129 void
1130 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1131 SmallVectorImpl<AnnotatedLine *>::iterator E,
1132 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001133 if (Limit == 0)
1134 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001135 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001136 (*(I + 1))->First->is(tok::l_brace))
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001137 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001138 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
1139 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001140 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001141 AnnotatedLine &Line = **I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001142 if (Line.Last->isNot(tok::r_paren))
1143 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001144 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001145 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001146 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1147 tok::kw_while) ||
1148 (*(I + 1))->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001149 return;
1150 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001151 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001152 (*(I + 2))->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001153 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001154 join(Line, **(++I));
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001155 }
1156
Daniel Jasperb77d7412013-09-06 07:54:20 +00001157 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1158 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001159 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001160 // No merging if the brace already is on the next line.
1161 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1162 return;
1163
Manuel Klimek517e8942013-01-11 17:54:10 +00001164 // First, check that the current line allows merging. This is the case if
1165 // we're not in a control flow statement and the last token is an opening
1166 // brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001167 AnnotatedLine &Line = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001168 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1169 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001170 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001171 // This gets rid of all ObjC @ keywords and methods.
1172 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001173 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001174
Daniel Jasper567dcf92013-09-05 09:29:45 +00001175 FormatToken *Tok = (*(I + 1))->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001176 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001177 (Tok->getNextNonComment() == NULL ||
1178 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001179 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001180 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001181 Tok->CanBreakBefore = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001182 join(Line, **(I + 1));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001183 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001184 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001185 // Check that we still have three lines and they fit into the limit.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001186 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001187 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001188 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001189
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001190 // Second, check that the next line does not contain any braces - if it
1191 // does, readability declines when putting it into a single line.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001192 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001193 return;
1194 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001195 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001196 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001197 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001198 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001199
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001200 // Last, check that the third line contains a single closing brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001201 Tok = (*(I + 2))->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001202 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001203 Tok->MustBreakBefore)
1204 return;
1205
Daniel Jasper567dcf92013-09-05 09:29:45 +00001206 join(Line, **(I + 1));
1207 join(Line, **(I + 2));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001208 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001209 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001210 }
1211
Daniel Jasperb77d7412013-09-06 07:54:20 +00001212 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001213 unsigned Limit) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001214 return 1 + (*(I + 1))->Last->TotalLength + 1 +
1215 (*(I + 2))->Last->TotalLength <=
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001216 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001217 }
1218
Daniel Jasper995e8202013-01-14 13:08:07 +00001219 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001220 assert(!A.Last->Next);
1221 assert(!B.First->Previous);
1222 A.Last->Next = B.First;
1223 B.First->Previous = A.Last;
1224 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1225 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1226 Tok->TotalLength += LengthA;
1227 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001228 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001229 }
1230
Daniel Jasper6f21a982013-03-13 07:49:51 +00001231 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001232 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1233 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1234 Ranges[i].getBegin()) &&
1235 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1236 Range.getBegin()))
1237 return true;
1238 }
1239 return false;
1240 }
1241
1242 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001243 const FormatToken *First = TheLine.First;
1244 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001245 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001246 First->WhitespaceRange.getBegin().getLocWithOffset(
1247 First->LastNewlineOffset),
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001248 Last->getStartOfNonWhitespace().getLocWithOffset(
1249 Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001250 return touchesRanges(LineRange);
1251 }
1252
Daniel Jasperb77d7412013-09-06 07:54:20 +00001253 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
1254 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001255 for (; I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001256 if ((*I)->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001257 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001258 if (touchesLine(**I))
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001259 return true;
1260 }
1261 return false;
1262 }
1263
Daniel Jasperf3023542013-03-07 20:50:00 +00001264 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001265 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001266 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001267 First->WhitespaceRange.getBegin(),
1268 First->WhitespaceRange.getBegin().getLocWithOffset(
1269 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001270 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001271 }
1272
1273 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001274 assert(!UnwrappedLines.empty());
1275 UnwrappedLines.back().push_back(TheLine);
1276 }
1277
1278 virtual void finishRun() {
1279 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001280 }
1281
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001282 /// \brief Add a new line and the required indent before the first Token
1283 /// of the \c UnwrappedLine if there was no structural parsing error.
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001284 void formatFirstToken(FormatToken &RootToken,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001285 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1286 unsigned Indent, bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001287 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001288 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001289 // Remove empty lines before "}" where applicable.
1290 if (RootToken.is(tok::r_brace) &&
1291 (!RootToken.Next ||
1292 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1293 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001294 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001295 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001296
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001297 // Insert extra new line before access specifiers.
Daniel Jasper63cfb892013-10-06 11:40:08 +00001298 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001299 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001300 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001301
Daniel Jasper63cfb892013-10-06 11:40:08 +00001302 // Remove empty lines after access specifiers.
1303 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1304 Newlines = std::min(1u, Newlines);
1305
Manuel Klimekb3987012013-05-29 14:47:47 +00001306 Whitespaces.replaceWhitespace(
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001307 RootToken, Newlines, IndentLevel, Indent, Indent,
Manuel Klimekb3987012013-05-29 14:47:47 +00001308 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001309 }
1310
Daniel Jasper567dcf92013-09-05 09:29:45 +00001311 unsigned getColumnLimit(bool InPPDirective) const {
1312 // In preprocessor directives reserve two chars for trailing " \"
1313 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1314 }
1315
Daniel Jasperbac016b2012-12-03 18:12:45 +00001316 FormatStyle Style;
1317 Lexer &Lex;
1318 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001319 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001320 std::vector<CharSourceRange> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001321 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001322
1323 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001324 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001325};
1326
Craig Topper83f81d72013-06-30 22:29:28 +00001327} // end anonymous namespace
1328
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001329tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1330 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001331 std::vector<CharSourceRange> Ranges) {
1332 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001333 return formatter.format();
1334}
1335
Daniel Jasper8a999452013-05-16 10:40:07 +00001336tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1337 std::vector<tooling::Range> Ranges,
1338 StringRef FileName) {
1339 FileManager Files((FileSystemOptions()));
1340 DiagnosticsEngine Diagnostics(
1341 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1342 new DiagnosticOptions);
1343 SourceManager SourceMgr(Diagnostics, Files);
1344 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1345 const clang::FileEntry *Entry =
1346 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1347 SourceMgr.overrideFileContents(Entry, Buf);
1348 FileID ID =
1349 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001350 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1351 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001352 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1353 std::vector<CharSourceRange> CharRanges;
1354 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1355 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1356 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1357 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1358 }
1359 return reformat(Style, Lex, SourceMgr, CharRanges);
1360}
1361
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001362LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001363 LangOptions LangOpts;
1364 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001365 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001366 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001367 LangOpts.Bool = 1;
1368 LangOpts.ObjC1 = 1;
1369 LangOpts.ObjC2 = 1;
1370 return LangOpts;
1371}
1372
Edwin Vanef4e12c82013-09-30 13:31:48 +00001373const char *StyleOptionHelpDescription =
1374 "Coding style, currently supports:\n"
1375 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1376 "Use -style=file to load style configuration from\n"
1377 ".clang-format file located in one of the parent\n"
1378 "directories of the source file (or current\n"
1379 "directory for stdin).\n"
1380 "Use -style=\"{key: value, ...}\" to set specific\n"
1381 "parameters, e.g.:\n"
1382 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1383
1384FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1385 // Fallback style in case the rest of this function can't determine a style.
1386 StringRef FallbackStyle = "LLVM";
1387 FormatStyle Style;
1388 getPredefinedStyle(FallbackStyle, &Style);
1389
1390 if (StyleName.startswith("{")) {
1391 // Parse YAML/JSON style from the command line.
1392 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001393 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1394 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00001395 }
1396 return Style;
1397 }
1398
1399 if (!StyleName.equals_lower("file")) {
1400 if (!getPredefinedStyle(StyleName, &Style))
1401 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1402 << " style\n";
1403 return Style;
1404 }
1405
1406 SmallString<128> Path(FileName);
1407 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001408 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00001409 Directory = llvm::sys::path::parent_path(Directory)) {
1410 if (!llvm::sys::fs::is_directory(Directory))
1411 continue;
1412 SmallString<128> ConfigFile(Directory);
1413
1414 llvm::sys::path::append(ConfigFile, ".clang-format");
1415 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1416 bool IsFile = false;
1417 // Ignore errors from is_regular_file: we only need to know if we can read
1418 // the file or not.
1419 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1420
1421 if (!IsFile) {
1422 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1423 ConfigFile = Directory;
1424 llvm::sys::path::append(ConfigFile, "_clang-format");
1425 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1426 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1427 }
1428
1429 if (IsFile) {
1430 OwningPtr<llvm::MemoryBuffer> Text;
1431 if (llvm::error_code ec = llvm::MemoryBuffer::getFile(ConfigFile, Text)) {
1432 llvm::errs() << ec.message() << "\n";
1433 continue;
1434 }
1435 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1436 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1437 << "\n";
1438 continue;
1439 }
1440 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1441 return Style;
1442 }
1443 }
1444 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1445 << " style\n";
1446 return Style;
1447}
1448
Daniel Jaspercd162382013-01-07 13:26:07 +00001449} // namespace format
1450} // namespace clang