blob: a7d7d5eb108dd9f89c640ee5a55028c781f690d7 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000030#include "llvm/Support/Path.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod6538332013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000040 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000041 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000042 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimeka8eb9142013-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 Jasper12f9d8e2013-05-14 09:30:02 +000048template <>
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +000049struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000050 static void enumeration(IO &IO,
51 clang::format::FormatStyle::UseTabStyle &Value) {
Alexander Kornienko3c3d09c2013-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 Klimeka8eb9142013-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 Klimekd3ed59a2013-08-02 21:31:59 +000068 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod6538332013-05-07 15:32:14 +000069 }
70};
71
Daniel Jasper65ee3472013-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 Kornienkod6538332013-05-07 15:32:14 +000084template <> struct MappingTraits<clang::format::FormatStyle> {
85 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000086 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +000087 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
88 "Mozilla", "WebKit" };
Alexander Kornienko49149672013-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 Kornienko006b5c82013-05-19 00:53:30 +000092 clang::format::FormatStyle PredefinedStyle;
93 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
94 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000095 IO.mapOptional("# BasedOnStyle", StyleName);
96 break;
97 }
98 }
99 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100 StringRef BasedOnStyle;
101 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000102 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-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 Kornienkod6538332013-05-07 15:32:14 +0000107 }
108
109 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000110 IO.mapOptional("ConstructorInitializerIndentWidth",
111 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000112 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000113 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000114 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
115 Style.AllowAllParametersOfDeclarationOnNextLine);
116 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
117 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000118 IO.mapOptional("AllowShortLoopsOnASingleLine",
119 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000120 IO.mapOptional("AllowShortFunctionsOnASingleLine",
121 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000122 IO.mapOptional("AlwaysBreakTemplateDeclarations",
123 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000124 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
125 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000126 IO.mapOptional("BreakBeforeBinaryOperators",
127 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000128 IO.mapOptional("BreakBeforeTernaryOperators",
129 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000130 IO.mapOptional("BreakConstructorInitializersBeforeComma",
131 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000132 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
133 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
134 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
135 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
136 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000137 IO.mapOptional("ExperimentalAutoDetectBinPacking",
138 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000139 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
140 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000141 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000142 IO.mapOptional("ObjCSpaceBeforeProtocolList",
143 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000144 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
145 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000146 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
147 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000148 IO.mapOptional("PenaltyBreakFirstLessLess",
149 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000150 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
151 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
152 Style.PenaltyReturnTypeOnItsOwnLine);
153 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
154 IO.mapOptional("SpacesBeforeTrailingComments",
155 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000156 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000157 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000158 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000159 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000160 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000161 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000162 IO.mapOptional("IndentFunctionDeclarationAfterType",
163 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000164 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000165 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000166 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000167 IO.mapOptional("SpacesInCStyleCastParentheses",
168 Style.SpacesInCStyleCastParentheses);
169 IO.mapOptional("SpaceAfterControlStatementKeyword",
170 Style.SpaceAfterControlStatementKeyword);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000171 IO.mapOptional("SpaceBeforeAssignmentOperators",
172 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000173 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000174 }
175};
176}
177}
178
Daniel Jasperf7935112012-12-03 18:12:45 +0000179namespace clang {
180namespace format {
181
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000182void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasper2739af32013-08-28 10:03:58 +0000183 Style.PenaltyBreakComment = 60;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000184 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000185 Style.PenaltyBreakString = 1000;
186 Style.PenaltyExcessCharacter = 1000000;
187}
188
Daniel Jasperf7935112012-12-03 18:12:45 +0000189FormatStyle getLLVMStyle() {
190 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000191 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000192 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000193 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000194 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000195 LLVMStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000196 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000197 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000198 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000199 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000200 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000201 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000202 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000203 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
204 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000205 LLVMStyle.ColumnLimit = 80;
206 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000207 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000208 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000209 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000210 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000211 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000212 LLVMStyle.IndentFunctionDeclarationAfterType = false;
213 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000214 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000215 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000216 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000217 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000218 LLVMStyle.PointerBindsToType = false;
219 LLVMStyle.SpacesBeforeTrailingComments = 1;
220 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000221 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000222 LLVMStyle.SpacesInParentheses = false;
223 LLVMStyle.SpaceInEmptyParentheses = false;
224 LLVMStyle.SpacesInCStyleCastParentheses = false;
225 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000226 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000227 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000228 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000229
230 setDefaultPenalties(LLVMStyle);
231 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000232 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000233
Daniel Jasperf7935112012-12-03 18:12:45 +0000234 return LLVMStyle;
235}
236
237FormatStyle getGoogleStyle() {
238 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000239 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000240 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000241 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000242 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000243 GoogleStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000244 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000245 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000246 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000247 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000248 GoogleStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000249 GoogleStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000250 GoogleStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000251 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
252 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000253 GoogleStyle.ColumnLimit = 80;
254 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000255 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000256 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000257 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000258 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000259 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000260 GoogleStyle.IndentFunctionDeclarationAfterType = true;
261 GoogleStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000262 GoogleStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000263 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000264 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000265 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000266 GoogleStyle.PointerBindsToType = true;
267 GoogleStyle.SpacesBeforeTrailingComments = 2;
268 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000269 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000270 GoogleStyle.SpacesInParentheses = false;
271 GoogleStyle.SpaceInEmptyParentheses = false;
272 GoogleStyle.SpacesInCStyleCastParentheses = false;
273 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000274 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000275 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000276 GoogleStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000277
278 setDefaultPenalties(GoogleStyle);
279 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000280 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000281
Daniel Jasperf7935112012-12-03 18:12:45 +0000282 return GoogleStyle;
283}
284
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000285FormatStyle getChromiumStyle() {
286 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000287 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000288 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000289 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000290 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000291 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000292 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000293 return ChromiumStyle;
294}
295
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000296FormatStyle getMozillaStyle() {
297 FormatStyle MozillaStyle = getLLVMStyle();
298 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
299 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
300 MozillaStyle.DerivePointerBinding = true;
301 MozillaStyle.IndentCaseLabels = true;
302 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
303 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
304 MozillaStyle.PointerBindsToType = true;
305 return MozillaStyle;
306}
307
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000308FormatStyle getWebKitStyle() {
309 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000310 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000311 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000312 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000313 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000314 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000315 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000316 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000317 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000318 Style.PointerBindsToType = true;
319 return Style;
320}
321
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000322bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000323 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000324 *Style = getLLVMStyle();
325 else if (Name.equals_lower("chromium"))
326 *Style = getChromiumStyle();
327 else if (Name.equals_lower("mozilla"))
328 *Style = getMozillaStyle();
329 else if (Name.equals_lower("google"))
330 *Style = getGoogleStyle();
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000331 else if (Name.equals_lower("webkit"))
332 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000333 else
334 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000335
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000336 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000337}
338
339llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000340 if (Text.trim().empty())
341 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000342 llvm::yaml::Input Input(Text);
343 Input >> *Style;
344 return Input.error();
345}
346
347std::string configurationAsText(const FormatStyle &Style) {
348 std::string Text;
349 llvm::raw_string_ostream Stream(Text);
350 llvm::yaml::Output Output(Stream);
351 // We use the same mapping method for input and output, so we need a non-const
352 // reference here.
353 FormatStyle NonConstStyle = Style;
354 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000355 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000356}
357
Craig Topperaf35e852013-06-30 22:29:28 +0000358namespace {
359
Daniel Jasperde0328a2013-08-16 11:20:30 +0000360class NoColumnLimitFormatter {
361public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000362 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000363
364 /// \brief Formats the line starting at \p State, simply keeping all of the
365 /// input's line breaking decisions.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000366 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000367 LineState State =
368 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000369 while (State.NextToken != NULL) {
370 bool Newline =
371 Indenter->mustBreak(State) ||
372 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
373 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
374 }
375 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000376
Daniel Jasperde0328a2013-08-16 11:20:30 +0000377private:
378 ContinuationIndenter *Indenter;
379};
380
Daniel Jasper56f8b432013-11-06 23:12:09 +0000381class LineJoiner {
382public:
383 LineJoiner(const FormatStyle &Style) : Style(Style) {}
384
385 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
386 unsigned
387 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000388 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000389 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
390 // We can never merge stuff if there are trailing line comments.
391 AnnotatedLine *TheLine = *I;
392 if (TheLine->Last->Type == TT_LineComment)
393 return 0;
394
395 if (Indent > Style.ColumnLimit)
396 return 0;
397
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000398 unsigned Limit =
399 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000400 // If we already exceed the column limit, we set 'Limit' to 0. The different
401 // tryMerge..() functions can then decide whether to still do merging.
402 Limit = TheLine->Last->TotalLength > Limit
403 ? 0
404 : Limit - TheLine->Last->TotalLength;
405
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000406 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000407 return 0;
408
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000409 if (TheLine->Last->Type == TT_FunctionLBrace) {
410 return Style.AllowShortFunctionsOnASingleLine
411 ? tryMergeSimpleBlock(I, E, Limit)
412 : 0;
413 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000414 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000415 return Style.BreakBeforeBraces == clang::format::FormatStyle::BS_Attach
416 ? tryMergeSimpleBlock(I, E, Limit)
417 : 0;
418 }
419 if (I[1]->First->Type == TT_FunctionLBrace &&
420 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
421 // Reduce the column limit by the number of spaces we need to insert
422 // around braces.
423 Limit = Limit > 3 ? Limit - 3 : 0;
424 unsigned MergedLines = 0;
425 if (Style.AllowShortFunctionsOnASingleLine) {
426 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
427 // If we managed to merge the block, count the function header, which is
428 // on a separate line.
429 if (MergedLines > 0)
430 ++MergedLines;
431 }
432 return MergedLines;
433 }
434 if (TheLine->First->is(tok::kw_if)) {
435 return Style.AllowShortIfStatementsOnASingleLine
436 ? tryMergeSimpleControlStatement(I, E, Limit)
437 : 0;
438 }
439 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
440 return Style.AllowShortLoopsOnASingleLine
441 ? tryMergeSimpleControlStatement(I, E, Limit)
442 : 0;
443 }
444 if (TheLine->InPPDirective &&
445 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000446 return tryMergeSimplePPDirective(I, E, Limit);
447 }
448 return 0;
449 }
450
451private:
452 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000453 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000454 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
455 unsigned Limit) {
456 if (Limit == 0)
457 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000458 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000459 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000460 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000461 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000462 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000463 return 0;
464 return 1;
465 }
466
467 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000468 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000469 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
470 if (Limit == 0)
471 return 0;
472 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000473 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000474 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000475 if (I[1]->InPPDirective != (*I)->InPPDirective ||
476 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000477 return 0;
478 AnnotatedLine &Line = **I;
479 if (Line.Last->isNot(tok::r_paren))
480 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000481 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000482 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000483 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000484 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000485 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000486 return 0;
487 // Only inline simple if's (no nested if or else).
488 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000489 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000490 return 0;
491 return 1;
492 }
493
494 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000495 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000496 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
497 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000498 // First, check that the current line allows merging. This is the case if
499 // we're not in a control flow statement and the last token is an opening
500 // brace.
501 AnnotatedLine &Line = **I;
502 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
503 tok::kw_else, tok::kw_try, tok::kw_catch,
504 tok::kw_for,
505 // This gets rid of all ObjC @ keywords and methods.
506 tok::at, tok::minus, tok::plus))
507 return 0;
508
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000509 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000510 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
511 (Tok->getNextNonComment() == NULL ||
512 Tok->getNextNonComment()->is(tok::semi))) {
513 // We merge empty blocks even if the line exceeds the column limit.
514 Tok->SpacesRequiredBefore = 0;
515 Tok->CanBreakBefore = true;
516 return 1;
517 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
518 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000519 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000520 return 0;
521
522 if (!nextTwoLinesFitInto(I, Limit))
523 return 0;
524
525 // Second, check that the next line does not contain any braces - if it
526 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000527 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000528 return 0;
529 do {
530 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
531 return 0;
532 Tok = Tok->Next;
533 } while (Tok != NULL);
534
535 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000536 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000537 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
538 Tok->MustBreakBefore)
539 return 0;
540
541 return 2;
542 }
543 return 0;
544 }
545
546 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
547 unsigned Limit) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000548 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000549 }
550
551 const FormatStyle &Style;
552};
553
Daniel Jasperf7935112012-12-03 18:12:45 +0000554class UnwrappedLineFormatter {
555public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000556 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000557 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000558 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000559 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
560 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000561
Daniel Jasper56f8b432013-11-06 23:12:09 +0000562 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000563 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000564 assert(!Lines.empty());
565 unsigned Penalty = 0;
566 std::vector<int> IndentForLevel;
567 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
568 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000569 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000570 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
571 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000572 I != E; ++I) {
573 const AnnotatedLine &TheLine = **I;
574 const FormatToken *FirstTok = TheLine.First;
575 int Offset = getIndentOffset(*FirstTok);
576
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000577 // Determine indent and try to merge multiple unwrapped lines.
578 while (IndentForLevel.size() <= TheLine.Level)
579 IndentForLevel.push_back(-1);
580 IndentForLevel.resize(TheLine.Level + 1);
581 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
582 if (static_cast<int>(Indent) + Offset >= 0)
583 Indent += Offset;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000584 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
585 if (!DryRun) {
586 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000587 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000588 }
589 }
590 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000591
Daniel Jasper9c199562013-11-28 15:58:55 +0000592 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
593 bool FixIndentation =
594 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000595 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000596 if (PreviousLine && PreviousLine->Affected && !DryRun) {
597 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000598 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
599 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
600 /*IndentLevel=*/0, /*Spaces=*/0,
601 /*TargetColumn=*/0);
602 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000603 } else if (TheLine.Type != LT_Invalid &&
604 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000605 if (FirstTok->WhitespaceRange.isValid()) {
606 if (!DryRun)
607 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
608 Indent, TheLine.InPPDirective);
609 } else {
610 Indent = LevelIndent = FirstTok->OriginalColumn;
611 }
612
613 // If everything fits on a single line, just put it there.
614 unsigned ColumnLimit = Style.ColumnLimit;
615 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000616 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000617 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
618 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
619 }
620
621 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
622 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
623 while (State.NextToken != NULL)
624 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
625 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000626 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000627 NoColumnLimitFormatter Formatter(Indenter);
628 if (!DryRun)
629 Formatter.format(Indent, &TheLine);
630 } else {
631 Penalty += format(TheLine, Indent, DryRun);
632 }
633
634 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000635 } else if (TheLine.ChildrenAffected) {
636 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000637 } else {
638 // Format the first token if necessary, and notify the WhitespaceManager
639 // about the unchanged whitespace.
640 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
641 if (Tok == TheLine.First &&
642 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
643 unsigned LevelIndent = Tok->OriginalColumn;
644 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000645 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000646 if ((PreviousLine && PreviousLine->Affected) ||
647 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000648 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
649 TheLine.InPPDirective);
650 } else {
651 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
652 }
653 }
654
655 if (static_cast<int>(LevelIndent) - Offset >= 0)
656 LevelIndent -= Offset;
657 if (Tok->isNot(tok::comment))
658 IndentForLevel[TheLine.Level] = LevelIndent;
659 } else if (!DryRun) {
660 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
661 }
662 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000663 }
664 if (!DryRun) {
665 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
666 Tok->Finalized = true;
667 }
668 }
669 PreviousLine = *I;
670 }
671 return Penalty;
672 }
673
674private:
675 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000676 ///
677 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000678 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
679 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000680 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000681
Daniel Jasperacc33662013-02-08 08:22:00 +0000682 // If the ObjC method declaration does not fit on a line, we should format
683 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000684 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000685 State.Stack.back().BreakBeforeParameter = true;
686
Daniel Jasper4b866272013-02-01 11:00:45 +0000687 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000688 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000689 }
690
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000691 /// \brief An edge in the solution space from \c Previous->State to \c State,
692 /// inserting a newline dependent on the \c NewLine.
693 struct StateNode {
694 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000695 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000696 LineState State;
697 bool NewLine;
698 StateNode *Previous;
699 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000700
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000701 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
702 ///
703 /// In case of equal penalties, we want to prefer states that were inserted
704 /// first. During state generation we make sure that we insert states first
705 /// that break the line as late as possible.
706 typedef std::pair<unsigned, unsigned> OrderedPenalty;
707
708 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
709 /// \c State has the given \c OrderedPenalty.
710 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
711
712 /// \brief The BFS queue type.
713 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
714 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000715
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000716 /// \brief Get the offset of the line relatively to the level.
717 ///
718 /// For example, 'public:' labels in classes are offset by 1 or 2
719 /// characters to the left from their level.
720 int getIndentOffset(const FormatToken &RootToken) {
721 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
722 return Style.AccessModifierOffset;
723 return 0;
724 }
725
726 /// \brief Add a new line and the required indent before the first Token
727 /// of the \c UnwrappedLine if there was no structural parsing error.
728 void formatFirstToken(FormatToken &RootToken,
729 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
730 unsigned Indent, bool InPPDirective) {
731 unsigned Newlines =
732 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
733 // Remove empty lines before "}" where applicable.
734 if (RootToken.is(tok::r_brace) &&
735 (!RootToken.Next ||
736 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
737 Newlines = std::min(Newlines, 1u);
738 if (Newlines == 0 && !RootToken.IsFirst)
739 Newlines = 1;
740
741 // Insert extra new line before access specifiers.
742 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
743 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
744 ++Newlines;
745
746 // Remove empty lines after access specifiers.
747 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
748 Newlines = std::min(1u, Newlines);
749
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000750 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
751 Indent, InPPDirective &&
752 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000753 }
754
755 /// \brief Get the indent of \p Level from \p IndentForLevel.
756 ///
757 /// \p IndentForLevel must contain the indent for the level \c l
758 /// at \p IndentForLevel[l], or a value < 0 if the indent for
759 /// that level is unknown.
760 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
761 if (IndentForLevel[Level] != -1)
762 return IndentForLevel[Level];
763 if (Level == 0)
764 return 0;
765 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
766 }
767
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000768 void join(AnnotatedLine &A, const AnnotatedLine &B) {
769 assert(!A.Last->Next);
770 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000771 if (B.Affected)
772 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000773 A.Last->Next = B.First;
774 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000775 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000776 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
777 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
778 Tok->TotalLength += LengthA;
779 A.Last = Tok;
780 }
781 }
782
783 unsigned getColumnLimit(bool InPPDirective) const {
784 // In preprocessor directives reserve two chars for trailing " \"
785 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
786 }
787
Daniel Jasper4b866272013-02-01 11:00:45 +0000788 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000789 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000790 /// This implements a variant of Dijkstra's algorithm on the graph that spans
791 /// the solution space (\c LineStates are the nodes). The algorithm tries to
792 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000793 /// to a state where all tokens are placed. Returns the penalty.
794 ///
795 /// If \p DryRun is \c false, directly applies the changes.
796 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 std::set<LineState> Seen;
798
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000799 // Increasing count of \c StateNode items we have created. This is used to
800 // create a deterministic order independent of the container.
801 unsigned Count = 0;
802 QueueType Queue;
803
Daniel Jasper4b866272013-02-01 11:00:45 +0000804 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000805 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000806 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
807 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
808 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000809
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000810 unsigned Penalty = 0;
811
Daniel Jasper4b866272013-02-01 11:00:45 +0000812 // While not empty, take first element and follow edges.
813 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000814 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000815 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000816 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000817 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000818 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000819 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000820 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000821
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000822 // Cut off the analysis of certain solutions if the analysis gets too
823 // complex. See description of IgnoreStackForComparison.
824 if (Count > 10000)
825 Node->State.IgnoreStackForComparison = true;
826
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000827 if (!Seen.insert(Node->State).second)
828 // State already examined with lower penalty.
829 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000830
Manuel Klimek71814b42013-10-11 21:25:45 +0000831 FormatDecision LastFormat = Node->State.NextToken->Decision;
832 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000833 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +0000834 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000835 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +0000836 }
837
Manuel Klimek71814b42013-10-11 21:25:45 +0000838 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000839 // We were unable to find a solution, do nothing.
840 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +0000841 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000842 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +0000843 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000844
Daniel Jasper4b866272013-02-01 11:00:45 +0000845 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000846 if (!DryRun)
847 reconstructPath(InitialState, Queue.top().second);
848
Alexander Kornienko49149672013-05-10 11:56:10 +0000849 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
850 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000851
852 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000853 }
854
855 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000856 std::deque<StateNode *> Path;
857 // We do not need a break before the initial token.
858 while (Current->Previous) {
859 Path.push_front(Current);
860 Current = Current->Previous;
861 }
862 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
863 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000864 unsigned Penalty = 0;
865 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
866 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
867
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000868 DEBUG({
869 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000870 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000871 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000872 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000873 }
874 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000875 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000876 }
877
Manuel Klimekaf491072013-02-13 10:54:19 +0000878 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000879 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000880 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000881 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000882 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000883 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000884 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000885 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000886 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000887 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000888
889 StateNode *Node = new (Allocator.Allocate())
890 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000891 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
892 return;
893
Daniel Jasperde0328a2013-08-16 11:20:30 +0000894 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000895
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000896 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
897 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +0000898 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000899
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000900 /// \brief If the \p State's next token is an r_brace closing a nested block,
901 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000902 ///
903 /// Returns \c true if all children could be placed successfully and adapts
904 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
905 /// creates changes using \c Whitespaces.
906 ///
907 /// The crucial idea here is that children always get formatted upon
908 /// encountering the closing brace right after the nested block. Now, if we
909 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
910 /// \c false), the entire block has to be kept on the same line (which is only
911 /// possible if it fits on the line, only contains a single statement, etc.
912 ///
913 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
914 /// break after the "{", format all lines with correct indentation and the put
915 /// the closing "}" on yet another new line.
916 ///
917 /// This enables us to keep the simple structure of the
918 /// \c UnwrappedLineFormatter, where we only have two options for each token:
919 /// break or don't break.
920 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
921 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000922 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000923 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
924 if (!LBrace || LBrace->isNot(tok::l_brace) ||
925 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000926 // The previous token does not open a block. Nothing to do. We don't
927 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +0000928 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000929
930 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000931 int AdditionalIndent = State.Stack.back().Indent -
932 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +0000933 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
934 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000935 return true;
936 }
937
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000938 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000939 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000940 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000941
942 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000943 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000944 return false;
945
946 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000947 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000948 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000949 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000950 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000951 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000952 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000953
Daniel Jasperdcd5da12013-10-20 17:28:32 +0000954 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000955 return true;
956 }
957
Daniel Jasperde0328a2013-08-16 11:20:30 +0000958 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000959 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000960 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000961 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +0000962
963 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000964};
965
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000966class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000967public:
Manuel Klimek31c85922013-08-29 15:21:40 +0000968 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000969 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +0000970 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +0000971 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
972 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000973 Lex.SetKeepWhitespaceMode(true);
974 }
975
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000976 ArrayRef<FormatToken *> lex() {
977 assert(Tokens.empty());
978 do {
979 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000980 tryMergePreviousTokens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000981 } while (Tokens.back()->Tok.isNot(tok::eof));
982 return Tokens;
983 }
984
985 IdentifierTable &getIdentTable() { return IdentTable; }
986
987private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000988 void tryMergePreviousTokens() {
989 tryMerge_TMacro() || tryMergeJavaScriptIdentityOperators();
990 }
991
992 bool tryMergeJavaScriptIdentityOperators() {
993 if (Tokens.size() < 2)
994 return false;
995 FormatToken &First = *Tokens[Tokens.size() - 2];
996 if (!First.isOneOf(tok::exclaimequal, tok::equalequal))
997 return false;
998 FormatToken &Second = *Tokens.back();
999 if (!Second.is(tok::equal))
1000 return false;
1001 if (Second.WhitespaceRange.getBegin() != Second.WhitespaceRange.getEnd())
1002 return false;
1003 First.TokenText =
1004 StringRef(First.TokenText.data(), First.TokenText.size() + 1);
1005 First.ColumnWidth += 1;
1006 Tokens.pop_back();
1007 return true;
1008 }
1009
1010 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001011 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001012 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001013 FormatToken *Last = Tokens.back();
1014 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001015 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001016
1017 FormatToken *String = Tokens[Tokens.size() - 2];
1018 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001019 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001020
1021 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001022 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001023
1024 FormatToken *Macro = Tokens[Tokens.size() - 4];
1025 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001026 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001027
1028 const char *Start = Macro->TokenText.data();
1029 const char *End = Last->TokenText.data() + Last->TokenText.size();
1030 String->TokenText = StringRef(Start, End - Start);
1031 String->IsFirst = Macro->IsFirst;
1032 String->LastNewlineOffset = Macro->LastNewlineOffset;
1033 String->WhitespaceRange = Macro->WhitespaceRange;
1034 String->OriginalColumn = Macro->OriginalColumn;
1035 String->ColumnWidth = encoding::columnWidthWithTabs(
1036 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1037
1038 Tokens.pop_back();
1039 Tokens.pop_back();
1040 Tokens.pop_back();
1041 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001042 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001043 }
1044
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001045 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001046 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001047 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001048 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001049 Token Greater = FormatTok->Tok;
1050 FormatTok = new (Allocator.Allocate()) FormatToken;
1051 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001052 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001053 FormatTok->Tok.getLocation().getLocWithOffset(1);
1054 FormatTok->WhitespaceRange =
1055 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001056 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001057 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001058 GreaterStashed = false;
1059 return FormatTok;
1060 }
1061
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001062 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001063 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001064 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001065 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001066 FormatTok->IsFirst = IsFirstToken;
1067 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001068
1069 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001070 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001071 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001072 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1073 switch (FormatTok->TokenText[i]) {
1074 case '\n':
1075 ++FormatTok->NewlinesBefore;
1076 // FIXME: This is technically incorrect, as it could also
1077 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001078 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1079 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1080 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001081 FormatTok->HasUnescapedNewline = true;
1082 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1083 Column = 0;
1084 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001085 case '\r':
1086 case '\f':
1087 case '\v':
1088 Column = 0;
1089 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001090 case ' ':
1091 ++Column;
1092 break;
1093 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001094 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001095 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001096 case '\\':
1097 ++Column;
1098 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1099 FormatTok->TokenText[i + 1] != '\n'))
1100 FormatTok->Type = TT_ImplicitStringLiteral;
1101 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001102 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001103 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001104 ++Column;
1105 break;
1106 }
1107 }
1108
Daniel Jasper877615c2013-10-11 19:45:02 +00001109 if (FormatTok->Type == TT_ImplicitStringLiteral)
1110 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001111 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001112
Daniel Jasper8369aa52013-07-16 20:28:33 +00001113 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001114 }
Manuel Klimekef920692013-01-07 07:56:50 +00001115
Manuel Klimek1abf7892013-01-04 23:34:14 +00001116 // In case the token starts with escaped newlines, we want to
1117 // take them into account as whitespace - this pattern is quite frequent
1118 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001119 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001120 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1121 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001122 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001123 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001124 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001125 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001126 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001127
1128 FormatTok->WhitespaceRange = SourceRange(
1129 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1130
Manuel Klimek31c85922013-08-29 15:21:40 +00001131 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001132
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001133 TrailingWhitespace = 0;
1134 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001135 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001136 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001137 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001138 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001139 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001140 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001141 FormatTok->Tok.setIdentifierInfo(&Info);
1142 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001143 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001144 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001145 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001146 GreaterStashed = true;
1147 }
1148
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001149 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001150
Alexander Kornienko39856b72013-09-10 09:38:25 +00001151 StringRef Text = FormatTok->TokenText;
1152 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001153 if (FirstNewlinePos == StringRef::npos) {
1154 // FIXME: ColumnWidth actually depends on the start column, we need to
1155 // take this into account when the token is moved.
1156 FormatTok->ColumnWidth =
1157 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1158 Column += FormatTok->ColumnWidth;
1159 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001160 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001161 // FIXME: ColumnWidth actually depends on the start column, we need to
1162 // take this into account when the token is moved.
1163 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1164 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1165
Alexander Kornienko39856b72013-09-10 09:38:25 +00001166 // The last line of the token always starts in column 0.
1167 // Thus, the length can be precomputed even in the presence of tabs.
1168 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1169 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1170 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001171 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001172 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001173
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001174 return FormatTok;
1175 }
1176
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001177 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001178 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001179 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001180 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001181 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001182 Lexer &Lex;
1183 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001184 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001185 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001186 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001187 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1188 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001189
Daniel Jasper8369aa52013-07-16 20:28:33 +00001190 void readRawToken(FormatToken &Tok) {
1191 Lex.LexFromRawLexer(Tok.Tok);
1192 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1193 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001194 // For formatting, treat unterminated string literals like normal string
1195 // literals.
1196 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1197 Tok.TokenText[0] == '"') {
1198 Tok.Tok.setKind(tok::string_literal);
1199 Tok.IsUnterminatedLiteral = true;
1200 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001201 }
1202};
1203
Daniel Jasperf7935112012-12-03 18:12:45 +00001204class Formatter : public UnwrappedLineConsumer {
1205public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001206 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001207 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001208 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001209 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001210 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001211 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001212 DEBUG(llvm::dbgs() << "File encoding: "
1213 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1214 : "unknown")
1215 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001216 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001217
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001218 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001219 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001220 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001221
1222 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001223 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001224 assert(UnwrappedLines.rbegin()->empty());
1225 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1226 ++Run) {
1227 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1228 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1229 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1230 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1231 }
1232 tooling::Replacements RunResult =
1233 format(AnnotatedLines, StructuralError, Tokens);
1234 DEBUG({
1235 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1236 for (tooling::Replacements::iterator I = RunResult.begin(),
1237 E = RunResult.end();
1238 I != E; ++I) {
1239 llvm::dbgs() << I->toString() << "\n";
1240 }
1241 });
1242 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1243 delete AnnotatedLines[i];
1244 }
1245 Result.insert(RunResult.begin(), RunResult.end());
1246 Whitespaces.reset();
1247 }
1248 return Result;
1249 }
1250
1251 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1252 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001253 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001254 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001255 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001256 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001257 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001258 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001259 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001260 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001261 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001262
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001263 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001264 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1265 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001266 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001267 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001268 return Whitespaces.generateReplacements();
1269 }
1270
1271private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001272 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001273 // Returns \c true if at least one line between I and E or one of their
1274 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001275 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1276 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1277 bool SomeLineAffected = false;
1278 bool PreviousLineAffected = false;
1279 while (I != E) {
1280 AnnotatedLine *Line = *I;
1281 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1282
1283 // If a line is part of a preprocessor directive, it needs to be formatted
1284 // if any token within the directive is affected.
1285 if (Line->InPPDirective) {
1286 FormatToken *Last = Line->Last;
1287 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1288 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1289 Last = (*PPEnd)->Last;
1290 ++PPEnd;
1291 }
1292
1293 if (affectsTokenRange(*Line->First, *Last,
1294 /*IncludeLeadingNewlines=*/false)) {
1295 SomeLineAffected = true;
1296 markAllAsAffected(I, PPEnd);
1297 }
1298 I = PPEnd;
1299 continue;
1300 }
1301
Daniel Jasper9c199562013-11-28 15:58:55 +00001302 if (nonPPLineAffected(Line, &PreviousLineAffected))
Daniel Jasper5500f612013-11-25 11:08:59 +00001303 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001304
1305 ++I;
1306 }
1307 return SomeLineAffected;
1308 }
1309
Daniel Jasper9c199562013-11-28 15:58:55 +00001310 // Determines whether 'Line' is affected by the SourceRanges given as input.
1311 // Returns \c true if line or one if its children is affected.
1312 bool nonPPLineAffected(AnnotatedLine *Line, bool *PreviousLineAffected) {
1313 bool SomeLineAffected = false;
1314 Line->ChildrenAffected =
1315 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1316 if (Line->ChildrenAffected)
1317 SomeLineAffected = true;
1318
1319 // Stores whether one of the line's tokens is directly affected.
1320 bool SomeTokenAffected = false;
1321 // Stores whether we need to look at the leading newlines of the next token
1322 // in order to determine whether it was affected.
1323 bool IncludeLeadingNewlines = false;
1324
1325 // Stores whether the first child line of any of this line's tokens is
1326 // affected.
1327 bool SomeFirstChildAffected = false;
1328
1329 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1330 // Determine whether 'Tok' was affected.
1331 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1332 SomeTokenAffected = true;
1333
1334 // Determine whether the first child of 'Tok' was affected.
1335 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1336 SomeFirstChildAffected = true;
1337
1338 IncludeLeadingNewlines = Tok->Children.empty();
1339 }
1340
1341 // Was this line moved, i.e. has it previously been on the same line as an
1342 // affected line?
1343 bool LineMoved = *PreviousLineAffected && Line->First->NewlinesBefore == 0;
1344
1345 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved) {
1346 Line->Affected = true;
1347 *PreviousLineAffected = true;
1348 SomeLineAffected = true;
1349 } else {
1350 *PreviousLineAffected = false;
1351 }
1352 return SomeLineAffected;
1353 }
1354
Daniel Jasper5500f612013-11-25 11:08:59 +00001355 // Marks all lines between I and E as well as all their children as affected.
1356 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1357 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1358 while (I != E) {
1359 (*I)->Affected = true;
1360 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1361 ++I;
1362 }
1363 }
1364
1365 // Returns true if the range from 'First' to 'Last' intersects with one of the
1366 // input ranges.
1367 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1368 bool IncludeLeadingNewlines) {
1369 SourceLocation Start = First.WhitespaceRange.getBegin();
1370 if (!IncludeLeadingNewlines)
1371 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001372 SourceLocation End = Last.getStartOfNonWhitespace();
1373 if (Last.TokenText.size() > 0)
1374 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001375 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1376 return affectsCharSourceRange(Range);
1377 }
1378
1379 // Returns true if one of the input ranges intersect the leading empty lines
1380 // before 'Tok'.
1381 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1382 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1383 Tok.WhitespaceRange.getBegin(),
1384 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1385 return affectsCharSourceRange(EmptyLineRange);
1386 }
1387
1388 // Returns true if 'Range' intersects with one of the input ranges.
1389 bool affectsCharSourceRange(const CharSourceRange &Range) {
1390 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1391 E = Ranges.end();
1392 I != E; ++I) {
1393 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1394 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1395 return true;
1396 }
1397 return false;
1398 }
1399
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001400 static bool inputUsesCRLF(StringRef Text) {
1401 return Text.count('\r') * 2 > Text.count('\n');
1402 }
1403
Manuel Klimek71814b42013-10-11 21:25:45 +00001404 void
1405 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001406 unsigned CountBoundToVariable = 0;
1407 unsigned CountBoundToType = 0;
1408 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001409 bool HasBinPackedFunction = false;
1410 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001411 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001412 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001413 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001414 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001415 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001416 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001417 bool SpacesBefore =
1418 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1419 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1420 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001421 if (SpacesBefore && !SpacesAfter)
1422 ++CountBoundToVariable;
1423 else if (!SpacesBefore && SpacesAfter)
1424 ++CountBoundToType;
1425 }
1426
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001427 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1428 if (Tok->is(tok::coloncolon) &&
1429 Tok->Previous->Type == TT_TemplateOpener)
1430 HasCpp03IncompatibleFormat = true;
1431 if (Tok->Type == TT_TemplateCloser &&
1432 Tok->Previous->Type == TT_TemplateCloser)
1433 HasCpp03IncompatibleFormat = true;
1434 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001435
1436 if (Tok->PackingKind == PPK_BinPacked)
1437 HasBinPackedFunction = true;
1438 if (Tok->PackingKind == PPK_OnePerLine)
1439 HasOnePerLineFunction = true;
1440
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001441 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001442 }
1443 }
1444 if (Style.DerivePointerBinding) {
1445 if (CountBoundToType > CountBoundToVariable)
1446 Style.PointerBindsToType = true;
1447 else if (CountBoundToType < CountBoundToVariable)
1448 Style.PointerBindsToType = false;
1449 }
1450 if (Style.Standard == FormatStyle::LS_Auto) {
1451 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1452 : FormatStyle::LS_Cpp03;
1453 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001454 BinPackInconclusiveFunctions =
1455 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001456 }
1457
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001458 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001459 assert(!UnwrappedLines.empty());
1460 UnwrappedLines.back().push_back(TheLine);
1461 }
1462
1463 virtual void finishRun() {
1464 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001465 }
1466
1467 FormatStyle Style;
1468 Lexer &Lex;
1469 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001470 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001471 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001472 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001473
1474 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001475 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001476};
1477
Craig Topperaf35e852013-06-30 22:29:28 +00001478} // end anonymous namespace
1479
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001480tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1481 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001482 std::vector<CharSourceRange> Ranges) {
1483 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001484 return formatter.format();
1485}
1486
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001487tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1488 std::vector<tooling::Range> Ranges,
1489 StringRef FileName) {
1490 FileManager Files((FileSystemOptions()));
1491 DiagnosticsEngine Diagnostics(
1492 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1493 new DiagnosticOptions);
1494 SourceManager SourceMgr(Diagnostics, Files);
1495 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1496 const clang::FileEntry *Entry =
1497 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1498 SourceMgr.overrideFileContents(Entry, Buf);
1499 FileID ID =
1500 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001501 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1502 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001503 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1504 std::vector<CharSourceRange> CharRanges;
1505 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1506 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1507 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1508 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1509 }
1510 return reformat(Style, Lex, SourceMgr, CharRanges);
1511}
1512
Alexander Kornienko1e808872013-06-28 12:51:24 +00001513LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001514 LangOptions LangOpts;
1515 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001516 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001517 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001518 LangOpts.Bool = 1;
1519 LangOpts.ObjC1 = 1;
1520 LangOpts.ObjC2 = 1;
1521 return LangOpts;
1522}
1523
Edwin Vaned544aa72013-09-30 13:31:48 +00001524const char *StyleOptionHelpDescription =
1525 "Coding style, currently supports:\n"
1526 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1527 "Use -style=file to load style configuration from\n"
1528 ".clang-format file located in one of the parent\n"
1529 "directories of the source file (or current\n"
1530 "directory for stdin).\n"
1531 "Use -style=\"{key: value, ...}\" to set specific\n"
1532 "parameters, e.g.:\n"
1533 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1534
1535FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1536 // Fallback style in case the rest of this function can't determine a style.
1537 StringRef FallbackStyle = "LLVM";
1538 FormatStyle Style;
1539 getPredefinedStyle(FallbackStyle, &Style);
1540
1541 if (StyleName.startswith("{")) {
1542 // Parse YAML/JSON style from the command line.
1543 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001544 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1545 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001546 }
1547 return Style;
1548 }
1549
1550 if (!StyleName.equals_lower("file")) {
1551 if (!getPredefinedStyle(StyleName, &Style))
1552 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1553 << " style\n";
1554 return Style;
1555 }
1556
1557 SmallString<128> Path(FileName);
1558 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001559 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001560 Directory = llvm::sys::path::parent_path(Directory)) {
1561 if (!llvm::sys::fs::is_directory(Directory))
1562 continue;
1563 SmallString<128> ConfigFile(Directory);
1564
1565 llvm::sys::path::append(ConfigFile, ".clang-format");
1566 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1567 bool IsFile = false;
1568 // Ignore errors from is_regular_file: we only need to know if we can read
1569 // the file or not.
1570 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1571
1572 if (!IsFile) {
1573 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1574 ConfigFile = Directory;
1575 llvm::sys::path::append(ConfigFile, "_clang-format");
1576 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1577 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1578 }
1579
1580 if (IsFile) {
1581 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001582 if (llvm::error_code ec =
1583 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001584 llvm::errs() << ec.message() << "\n";
1585 continue;
1586 }
1587 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1588 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1589 << "\n";
1590 continue;
1591 }
1592 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1593 return Style;
1594 }
1595 }
1596 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1597 << " style\n";
1598 return Style;
1599}
1600
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001601} // namespace format
1602} // namespace clang