blob: 6166ecc1b37326e310ba2a1ddb6e47dc1f04abf1 [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"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod71ec162013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000039 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000040 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000041 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000042 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
Daniel Jasper1fb8d882013-05-14 09:30:02 +000047template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000048struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
49 static void
50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000054 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000055 }
56};
57
Daniel Jaspereff18b92013-07-31 23:16:02 +000058template <>
59struct ScalarEnumerationTraits<
60 clang::format::FormatStyle::NamespaceIndentationKind> {
61 static void
62 enumeration(IO &IO,
63 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
64 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
65 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
66 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
67 }
68};
69
Alexander Kornienkod71ec162013-05-07 15:32:14 +000070template <> struct MappingTraits<clang::format::FormatStyle> {
71 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000072 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000073 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
74 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000075 ArrayRef<StringRef> Styles(StylesArray);
76 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
77 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000078 clang::format::FormatStyle PredefinedStyle;
79 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
80 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000081 IO.mapOptional("# BasedOnStyle", StyleName);
82 break;
83 }
84 }
85 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000086 StringRef BasedOnStyle;
87 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000088 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000089 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
90 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
91 return;
92 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000093 }
94
95 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +000096 IO.mapOptional("ConstructorInitializerIndentWidth",
97 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000098 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +000099 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
101 Style.AllowAllParametersOfDeclarationOnNextLine);
102 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
103 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000104 IO.mapOptional("AllowShortLoopsOnASingleLine",
105 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000106 IO.mapOptional("AlwaysBreakTemplateDeclarations",
107 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000108 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
109 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000110 IO.mapOptional("BreakBeforeBinaryOperators",
111 Style.BreakBeforeBinaryOperators);
112 IO.mapOptional("BreakConstructorInitializersBeforeComma",
113 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
115 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
116 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
117 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
118 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000119 IO.mapOptional("ExperimentalAutoDetectBinPacking",
120 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000121 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
122 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000123 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000124 IO.mapOptional("ObjCSpaceBeforeProtocolList",
125 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000126 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
127 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000128 IO.mapOptional("PenaltyBreakFirstLessLess",
129 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000130 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
131 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
132 Style.PenaltyReturnTypeOnItsOwnLine);
133 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
134 IO.mapOptional("SpacesBeforeTrailingComments",
135 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000136 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000137 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000138 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000139 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000140 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000141 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000142 IO.mapOptional("IndentFunctionDeclarationAfterType",
143 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000144 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000145 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000146 IO.mapOptional("SpacesInCStyleCastParentheses",
147 Style.SpacesInCStyleCastParentheses);
148 IO.mapOptional("SpaceAfterControlStatementKeyword",
149 Style.SpaceAfterControlStatementKeyword);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000150 IO.mapOptional("SpaceBeforeAssignmentOperators",
151 Style.SpaceBeforeAssignmentOperators);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000152 }
153};
154}
155}
156
Daniel Jasperbac016b2012-12-03 18:12:45 +0000157namespace clang {
158namespace format {
159
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000160void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000161 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000162 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000163 Style.PenaltyBreakString = 1000;
164 Style.PenaltyExcessCharacter = 1000000;
165}
166
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167FormatStyle getLLVMStyle() {
168 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000169 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000170 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000171 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000172 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000173 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000174 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000175 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000176 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000177 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000178 LLVMStyle.BreakBeforeBinaryOperators = false;
179 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
180 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000181 LLVMStyle.ColumnLimit = 80;
182 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000183 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000184 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000185 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000186 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000187 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000188 LLVMStyle.IndentFunctionDeclarationAfterType = false;
189 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000190 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000191 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000192 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000193 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000194 LLVMStyle.PointerBindsToType = false;
195 LLVMStyle.SpacesBeforeTrailingComments = 1;
196 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000197 LLVMStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000198 LLVMStyle.SpacesInParentheses = false;
199 LLVMStyle.SpaceInEmptyParentheses = false;
200 LLVMStyle.SpacesInCStyleCastParentheses = false;
201 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000202 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000203
204 setDefaultPenalties(LLVMStyle);
205 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
206
Daniel Jasperbac016b2012-12-03 18:12:45 +0000207 return LLVMStyle;
208}
209
210FormatStyle getGoogleStyle() {
211 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000213 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000214 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000215 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000216 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000217 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000218 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000219 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000220 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000221 GoogleStyle.BreakBeforeBinaryOperators = false;
222 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
223 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000224 GoogleStyle.ColumnLimit = 80;
225 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000226 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000227 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000228 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000229 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000230 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000231 GoogleStyle.IndentFunctionDeclarationAfterType = true;
232 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000233 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000234 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000235 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000236 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000237 GoogleStyle.PointerBindsToType = true;
238 GoogleStyle.SpacesBeforeTrailingComments = 2;
239 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000240 GoogleStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000241 GoogleStyle.SpacesInParentheses = false;
242 GoogleStyle.SpaceInEmptyParentheses = false;
243 GoogleStyle.SpacesInCStyleCastParentheses = false;
244 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000245 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000246
247 setDefaultPenalties(GoogleStyle);
248 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
249
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250 return GoogleStyle;
251}
252
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000253FormatStyle getChromiumStyle() {
254 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000255 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000256 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000257 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000258 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000259 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000260 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000261 return ChromiumStyle;
262}
263
Alexander Kornienkofb594862013-05-06 14:11:27 +0000264FormatStyle getMozillaStyle() {
265 FormatStyle MozillaStyle = getLLVMStyle();
266 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
267 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
268 MozillaStyle.DerivePointerBinding = true;
269 MozillaStyle.IndentCaseLabels = true;
270 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
271 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
272 MozillaStyle.PointerBindsToType = true;
273 return MozillaStyle;
274}
275
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000276FormatStyle getWebKitStyle() {
277 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000278 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000279 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000280 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000281 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000282 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000283 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000284 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000285 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000286 Style.PointerBindsToType = true;
287 return Style;
288}
289
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000290bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000291 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000292 *Style = getLLVMStyle();
293 else if (Name.equals_lower("chromium"))
294 *Style = getChromiumStyle();
295 else if (Name.equals_lower("mozilla"))
296 *Style = getMozillaStyle();
297 else if (Name.equals_lower("google"))
298 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000299 else if (Name.equals_lower("webkit"))
300 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000301 else
302 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000303
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000304 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000305}
306
307llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000308 if (Text.trim().empty())
309 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000310 llvm::yaml::Input Input(Text);
311 Input >> *Style;
312 return Input.error();
313}
314
315std::string configurationAsText(const FormatStyle &Style) {
316 std::string Text;
317 llvm::raw_string_ostream Stream(Text);
318 llvm::yaml::Output Output(Stream);
319 // We use the same mapping method for input and output, so we need a non-const
320 // reference here.
321 FormatStyle NonConstStyle = Style;
322 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000323 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000324}
325
Craig Topper83f81d72013-06-30 22:29:28 +0000326namespace {
327
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000328class NoColumnLimitFormatter {
329public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000330 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000331
332 /// \brief Formats the line starting at \p State, simply keeping all of the
333 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000334 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000335 LineState State =
336 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000337 while (State.NextToken != NULL) {
338 bool Newline =
339 Indenter->mustBreak(State) ||
340 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
341 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
342 }
343 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000344
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000345private:
346 ContinuationIndenter *Indenter;
347};
348
Daniel Jasperbac016b2012-12-03 18:12:45 +0000349class UnwrappedLineFormatter {
350public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000351 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000352 WhitespaceManager *Whitespaces,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000353 const FormatStyle &Style, const AnnotatedLine &Line)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000354 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
355 Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000356
Daniel Jasper567dcf92013-09-05 09:29:45 +0000357 /// \brief Formats an \c UnwrappedLine and returns the penalty.
358 ///
359 /// If \p DryRun is \c false, directly applies the changes.
360 unsigned format(unsigned FirstIndent, bool DryRun = false) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000361 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000362
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000363 // If the ObjC method declaration does not fit on a line, we should format
364 // it with one arg per line.
365 if (Line.Type == LT_ObjCMethodDecl)
366 State.Stack.back().BreakBeforeParameter = true;
367
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000368 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000369 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000370 }
371
372private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000373 /// \brief An edge in the solution space from \c Previous->State to \c State,
374 /// inserting a newline dependent on the \c NewLine.
375 struct StateNode {
376 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000377 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000378 LineState State;
379 bool NewLine;
380 StateNode *Previous;
381 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000382
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000383 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
384 ///
385 /// In case of equal penalties, we want to prefer states that were inserted
386 /// first. During state generation we make sure that we insert states first
387 /// that break the line as late as possible.
388 typedef std::pair<unsigned, unsigned> OrderedPenalty;
389
390 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
391 /// \c State has the given \c OrderedPenalty.
392 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
393
394 /// \brief The BFS queue type.
395 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
396 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000397
398 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000400 /// This implements a variant of Dijkstra's algorithm on the graph that spans
401 /// the solution space (\c LineStates are the nodes). The algorithm tries to
402 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000403 /// to a state where all tokens are placed. Returns the penalty.
404 ///
405 /// If \p DryRun is \c false, directly applies the changes.
406 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000407 std::set<LineState> Seen;
408
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000409 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000410 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000411 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
412 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
413 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000414
Daniel Jasper567dcf92013-09-05 09:29:45 +0000415 unsigned Penalty = 0;
416
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000417 // While not empty, take first element and follow edges.
418 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000419 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000420 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000421 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000422 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000423 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000424 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000425 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000426
Daniel Jasper54b4e442013-05-22 05:27:42 +0000427 // Cut off the analysis of certain solutions if the analysis gets too
428 // complex. See description of IgnoreStackForComparison.
429 if (Count > 10000)
430 Node->State.IgnoreStackForComparison = true;
431
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000432 if (!Seen.insert(Node->State).second)
433 // State already examined with lower penalty.
434 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000435
Nico Weber27268772013-06-26 00:30:14 +0000436 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
437 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000438 }
439
440 if (Queue.empty())
441 // We were unable to find a solution, do nothing.
442 // FIXME: Add diagnostic?
Daniel Jasper567dcf92013-09-05 09:29:45 +0000443 return 0;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000444
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000445 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000446 if (!DryRun)
447 reconstructPath(InitialState, Queue.top().second);
448
Alexander Kornienkodd256312013-05-10 11:56:10 +0000449 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
450 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000451
452 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000453 }
454
455 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000456 std::deque<StateNode *> Path;
457 // We do not need a break before the initial token.
458 while (Current->Previous) {
459 Path.push_front(Current);
460 Current = Current->Previous;
461 }
462 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
463 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000464 unsigned Penalty = 0;
465 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
466 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
467
Manuel Klimek9c333b92013-05-29 15:10:11 +0000468 DEBUG({
469 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000470 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000471 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000472 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000473 }
474 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000475 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000476 }
477
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000478 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000479 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000480 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000481 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000482 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
483 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000484 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000485 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000486 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000487 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000488
489 StateNode *Node = new (Allocator.Allocate())
490 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000491 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
492 return;
493
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000494 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000495
496 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
497 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000498 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000499
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000500 /// \brief If the \p State's next token is an r_brace closing a nested block,
501 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000502 ///
503 /// Returns \c true if all children could be placed successfully and adapts
504 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
505 /// creates changes using \c Whitespaces.
506 ///
507 /// The crucial idea here is that children always get formatted upon
508 /// encountering the closing brace right after the nested block. Now, if we
509 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
510 /// \c false), the entire block has to be kept on the same line (which is only
511 /// possible if it fits on the line, only contains a single statement, etc.
512 ///
513 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
514 /// break after the "{", format all lines with correct indentation and the put
515 /// the closing "}" on yet another new line.
516 ///
517 /// This enables us to keep the simple structure of the
518 /// \c UnwrappedLineFormatter, where we only have two options for each token:
519 /// break or don't break.
520 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
521 unsigned &Penalty) {
522 const FormatToken &LBrace = *State.NextToken->Previous;
523 if (LBrace.isNot(tok::l_brace) || LBrace.BlockKind != BK_Block ||
524 LBrace.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000525 // The previous token does not open a block. Nothing to do. We don't
526 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000527 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000528
529 if (NewLine) {
530 unsigned ParentIndent = State.Stack.back().Indent;
531 for (SmallVector<AnnotatedLine *, 1>::const_iterator
532 I = LBrace.Children.begin(),
533 E = LBrace.Children.end();
534 I != E; ++I) {
535 unsigned Indent =
Daniel Jasper57981202013-09-13 09:20:45 +0000536 ParentIndent + ((*I)->Level - Line.Level - 1) * Style.IndentWidth;
Daniel Jasper14e25c02013-09-08 14:07:57 +0000537 if (!DryRun) {
538 unsigned Newlines = std::min((*I)->First->NewlinesBefore,
539 Style.MaxEmptyLinesToKeep + 1);
540 Newlines = std::max(1u, Newlines);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000541 Whitespaces->replaceWhitespace(
Daniel Jasper14e25c02013-09-08 14:07:57 +0000542 *(*I)->First, Newlines, /*Spaces=*/Indent,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000543 /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000544 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000545 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
546 Penalty += Formatter.format(Indent, DryRun);
547 }
548 return true;
549 }
550
551 if (LBrace.Children.size() > 1)
552 return false; // Cannot merge multiple statements into a single line.
553
554 // We can't put the closing "}" on a line with a trailing comment.
555 if (LBrace.Children[0]->Last->isTrailingComment())
556 return false;
557
558 if (!DryRun) {
559 Whitespaces->replaceWhitespace(*LBrace.Children[0]->First,
560 /*Newlines=*/0, /*Spaces=*/1,
561 /*StartOfTokenColumn=*/State.Column,
562 State.Line->InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000563 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style,
564 *LBrace.Children[0]);
565 Penalty += Formatter.format(State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000566 }
567
568 State.Column += 1 + LBrace.Children[0]->Last->TotalLength;
569 return true;
570 }
571
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000572 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000573 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000575 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000576
577 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
578 QueueType Queue;
579 // Increasing count of \c StateNode items we have created. This is used
580 // to create a deterministic order independent of the container.
581 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000582};
583
Manuel Klimek96e888b2013-05-28 11:55:06 +0000584class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000585public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000586 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000587 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000588 : FormatTok(NULL), GreaterStashed(false), Column(0),
589 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
590 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000591 Lex.SetKeepWhitespaceMode(true);
592 }
593
Manuel Klimek96e888b2013-05-28 11:55:06 +0000594 ArrayRef<FormatToken *> lex() {
595 assert(Tokens.empty());
596 do {
597 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000598 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +0000599 } while (Tokens.back()->Tok.isNot(tok::eof));
600 return Tokens;
601 }
602
603 IdentifierTable &getIdentTable() { return IdentTable; }
604
605private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000606 void maybeJoinPreviousTokens() {
607 if (Tokens.size() < 4)
608 return;
609 FormatToken *Last = Tokens.back();
610 if (!Last->is(tok::r_paren))
611 return;
612
613 FormatToken *String = Tokens[Tokens.size() - 2];
614 if (!String->is(tok::string_literal) || String->IsMultiline)
615 return;
616
617 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
618 return;
619
620 FormatToken *Macro = Tokens[Tokens.size() - 4];
621 if (Macro->TokenText != "_T")
622 return;
623
624 const char *Start = Macro->TokenText.data();
625 const char *End = Last->TokenText.data() + Last->TokenText.size();
626 String->TokenText = StringRef(Start, End - Start);
627 String->IsFirst = Macro->IsFirst;
628 String->LastNewlineOffset = Macro->LastNewlineOffset;
629 String->WhitespaceRange = Macro->WhitespaceRange;
630 String->OriginalColumn = Macro->OriginalColumn;
631 String->ColumnWidth = encoding::columnWidthWithTabs(
632 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
633
634 Tokens.pop_back();
635 Tokens.pop_back();
636 Tokens.pop_back();
637 Tokens.back() = String;
638 }
639
Manuel Klimek96e888b2013-05-28 11:55:06 +0000640 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000641 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000642 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000643 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000644 Token Greater = FormatTok->Tok;
645 FormatTok = new (Allocator.Allocate()) FormatToken;
646 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000647 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000648 FormatTok->Tok.getLocation().getLocWithOffset(1);
649 FormatTok->WhitespaceRange =
650 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000651 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000652 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000653 GreaterStashed = false;
654 return FormatTok;
655 }
656
Manuel Klimek96e888b2013-05-28 11:55:06 +0000657 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000658 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000659 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000660 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000661 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000662 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000663
664 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000665 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000666 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000667 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
668 switch (FormatTok->TokenText[i]) {
669 case '\n':
670 ++FormatTok->NewlinesBefore;
671 // FIXME: This is technically incorrect, as it could also
672 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000673 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
674 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
675 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +0000676 FormatTok->HasUnescapedNewline = true;
677 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
678 Column = 0;
679 break;
680 case ' ':
681 ++Column;
682 break;
683 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000684 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000685 break;
686 default:
687 ++Column;
688 break;
689 }
690 }
691
Manuel Klimek96e888b2013-05-28 11:55:06 +0000692 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000693
Daniel Jasper561211d2013-07-16 20:28:33 +0000694 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000695 }
Manuel Klimek95419382013-01-07 07:56:50 +0000696
Manuel Klimekd4397b92013-01-04 23:34:14 +0000697 // In case the token starts with escaped newlines, we want to
698 // take them into account as whitespace - this pattern is quite frequent
699 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +0000700 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000701 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
702 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000703 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000704 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000705 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000706 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000707 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000708
709 FormatTok->WhitespaceRange = SourceRange(
710 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
711
Manuel Klimekc41e8192013-08-29 15:21:40 +0000712 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000713
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000714 TrailingWhitespace = 0;
715 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000716 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000717 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +0000718 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +0000719 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000720 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000721 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000722 FormatTok->Tok.setIdentifierInfo(&Info);
723 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000724 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000725 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000726 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000727 GreaterStashed = true;
728 }
729
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000730 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +0000731
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000732 StringRef Text = FormatTok->TokenText;
733 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000734 if (FirstNewlinePos == StringRef::npos) {
735 // FIXME: ColumnWidth actually depends on the start column, we need to
736 // take this into account when the token is moved.
737 FormatTok->ColumnWidth =
738 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
739 Column += FormatTok->ColumnWidth;
740 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000741 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000742 // FIXME: ColumnWidth actually depends on the start column, we need to
743 // take this into account when the token is moved.
744 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
745 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
746
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000747 // The last line of the token always starts in column 0.
748 // Thus, the length can be precomputed even in the presence of tabs.
749 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
750 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
751 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000752 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000753 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000754
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000755 return FormatTok;
756 }
757
Manuel Klimek96e888b2013-05-28 11:55:06 +0000758 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000759 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000760 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000761 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000762 Lexer &Lex;
763 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000764 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000765 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000766 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000767 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
768 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000769
Daniel Jasper561211d2013-07-16 20:28:33 +0000770 void readRawToken(FormatToken &Tok) {
771 Lex.LexFromRawLexer(Tok.Tok);
772 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
773 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000774 // For formatting, treat unterminated string literals like normal string
775 // literals.
776 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
777 Tok.TokenText[0] == '"') {
778 Tok.Tok.setKind(tok::string_literal);
779 Tok.IsUnterminatedLiteral = true;
780 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000781 }
782};
783
Daniel Jasperbac016b2012-12-03 18:12:45 +0000784class Formatter : public UnwrappedLineConsumer {
785public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000786 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000787 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000788 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000789 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
790 Ranges(Ranges), Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000791 DEBUG(llvm::dbgs() << "File encoding: "
792 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
793 : "unknown")
794 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000795 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000796
Daniel Jasper567dcf92013-09-05 09:29:45 +0000797 virtual ~Formatter() {
798 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
799 delete AnnotatedLines[i];
800 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000801 }
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000802
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000803 tooling::Replacements format() {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000804 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000805
806 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000807 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +0000808 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000809 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000810 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000811 }
812 deriveLocalStyle();
813 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000814 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000815 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000816
Daniel Jasperb77d7412013-09-06 07:54:20 +0000817 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper5999f762013-04-09 17:46:55 +0000818
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000819 std::vector<int> IndentForLevel;
820 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +0000821 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000822 bool FormatPPDirective = false;
Daniel Jasperb77d7412013-09-06 07:54:20 +0000823 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
824 E = AnnotatedLines.end();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000825 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000826 const AnnotatedLine &TheLine = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000827 const FormatToken *FirstTok = TheLine.First;
828 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000829
830 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000831 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000832 FormatPPDirective = false;
833 if (!FormatPPDirective && TheLine.InPPDirective &&
834 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
835 FormatPPDirective = true;
836
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000837 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000838 while (IndentForLevel.size() <= TheLine.Level)
839 IndentForLevel.push_back(-1);
840 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000841 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
842 if (static_cast<int>(Indent) + Offset >= 0)
843 Indent += Offset;
844 tryFitMultipleLinesInOne(Indent, I, E);
845
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000846 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000847 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000848 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000849 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +0000850 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000851 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000852 }
853 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000854 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000855 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000856 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +0000857 // Insert a break even if there is a structural error in case where
858 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000859 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000860 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000861 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000862 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000863 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000864 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000865 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000866 BinPackInconclusiveFunctions);
867
868 // If everything fits on a single line, just put it there.
869 unsigned ColumnLimit = Style.ColumnLimit;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000870 AnnotatedLine *NextLine = *(I + 1);
871 if ((I + 1) != E && NextLine->InPPDirective &&
872 !NextLine->First->HasUnescapedNewline)
873 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000874
Daniel Jasper567dcf92013-09-05 09:29:45 +0000875 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000876 LineState State =
877 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000878 while (State.NextToken != NULL)
879 Indenter.addTokenToState(State, false, false);
880 } else if (Style.ColumnLimit == 0) {
881 NoColumnLimitFormatter Formatter(&Indenter);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000882 Formatter.format(Indent, &TheLine);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000883 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000884 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
885 TheLine);
886 Formatter.format(Indent);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000887 }
888
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000889 IndentForLevel[TheLine.Level] = LevelIndent;
890 PreviousLineWasTouched = true;
891 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000892 // Format the first token if necessary, and notify the WhitespaceManager
893 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000894 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
895 Tok = Tok->Next) {
896 if (Tok == TheLine.First &&
897 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000898 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000899 // Remove trailing whitespace of the previous line if it was
900 // touched.
901 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
902 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
903 TheLine.InPPDirective);
904 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000905 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000906 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000907
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000908 if (static_cast<int>(LevelIndent) - Offset >= 0)
909 LevelIndent -= Offset;
910 if (Tok->isNot(tok::comment))
911 IndentForLevel[TheLine.Level] = LevelIndent;
912 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000913 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000914 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000915 }
916 // If we did not reformat this unwrapped line, the column at the end of
917 // the last token is unchanged - thus, we can calculate the end of the
918 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000919 PreviousLineWasTouched = false;
920 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000921 PreviousLineLastToken = TheLine.Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000922 }
923 return Whitespaces.generateReplacements();
924 }
925
926private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000927 static bool inputUsesCRLF(StringRef Text) {
928 return Text.count('\r') * 2 > Text.count('\n');
929 }
930
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000931 void deriveLocalStyle() {
932 unsigned CountBoundToVariable = 0;
933 unsigned CountBoundToType = 0;
934 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000935 bool HasBinPackedFunction = false;
936 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000937 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000938 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000939 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000940 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +0000941 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000942 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000943 bool SpacesBefore =
944 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
945 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
946 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000947 if (SpacesBefore && !SpacesAfter)
948 ++CountBoundToVariable;
949 else if (!SpacesBefore && SpacesAfter)
950 ++CountBoundToType;
951 }
952
Daniel Jasper29f123b2013-02-08 15:28:42 +0000953 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000954 Tok->Previous->Type == TT_TemplateCloser &&
955 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000956 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000957
958 if (Tok->PackingKind == PPK_BinPacked)
959 HasBinPackedFunction = true;
960 if (Tok->PackingKind == PPK_OnePerLine)
961 HasOnePerLineFunction = true;
962
Manuel Klimekb3987012013-05-29 14:47:47 +0000963 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000964 }
965 }
966 if (Style.DerivePointerBinding) {
967 if (CountBoundToType > CountBoundToVariable)
968 Style.PointerBindsToType = true;
969 else if (CountBoundToType < CountBoundToVariable)
970 Style.PointerBindsToType = false;
971 }
972 if (Style.Standard == FormatStyle::LS_Auto) {
973 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
974 : FormatStyle::LS_Cpp03;
975 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000976 BinPackInconclusiveFunctions =
977 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000978 }
979
Manuel Klimek547d5db2013-02-08 17:38:27 +0000980 /// \brief Get the indent of \p Level from \p IndentForLevel.
981 ///
982 /// \p IndentForLevel must contain the indent for the level \c l
983 /// at \p IndentForLevel[l], or a value < 0 if the indent for
984 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +0000985 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +0000986 if (IndentForLevel[Level] != -1)
987 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +0000988 if (Level == 0)
989 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000990 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +0000991 }
992
993 /// \brief Get the offset of the line relatively to the level.
994 ///
995 /// For example, 'public:' labels in classes are offset by 1 or 2
996 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +0000997 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000998 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +0000999 return Style.AccessModifierOffset;
1000 return 0;
1001 }
1002
Manuel Klimek517e8942013-01-11 17:54:10 +00001003 /// \brief Tries to merge lines into one.
1004 ///
1005 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1006 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001007 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperb77d7412013-09-06 07:54:20 +00001008 SmallVectorImpl<AnnotatedLine *>::iterator &I,
1009 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001010 // We can never merge stuff if there are trailing line comments.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001011 AnnotatedLine *TheLine = *I;
1012 if (TheLine->Last->Type == TT_LineComment)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001013 return;
1014
Daniel Jaspere05dc6d2013-07-24 13:10:59 +00001015 if (Indent > Style.ColumnLimit)
1016 return;
1017
Daniel Jaspera4d46212013-02-28 11:05:57 +00001018 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001019 // If we already exceed the column limit, we set 'Limit' to 0. The different
1020 // tryMerge..() functions can then decide whether to still do merging.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001021 Limit = TheLine->Last->TotalLength > Limit
1022 ? 0
1023 : Limit - TheLine->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001024
Daniel Jasper567dcf92013-09-05 09:29:45 +00001025 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001026 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001027
Daniel Jasper567dcf92013-09-05 09:29:45 +00001028 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001029 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001030 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001031 TheLine->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001032 tryMergeSimpleControlStatement(I, E, Limit);
1033 } else if (Style.AllowShortLoopsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001034 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001035 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001036 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
1037 TheLine->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001038 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001039 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001040 }
1041
Daniel Jasperb77d7412013-09-06 07:54:20 +00001042 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1043 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001044 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001045 if (Limit == 0)
1046 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001047 AnnotatedLine &Line = **I;
1048 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001049 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001050 if (I + 2 != E && (*(I + 2))->InPPDirective &&
1051 !(*(I + 2))->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001052 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001053 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001054 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001055 join(Line, **(++I));
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001056 }
1057
Daniel Jasperb77d7412013-09-06 07:54:20 +00001058 void
1059 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1060 SmallVectorImpl<AnnotatedLine *>::iterator E,
1061 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001062 if (Limit == 0)
1063 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001064 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001065 (*(I + 1))->First->is(tok::l_brace))
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001066 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001067 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
1068 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001069 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001070 AnnotatedLine &Line = **I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001071 if (Line.Last->isNot(tok::r_paren))
1072 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001073 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001074 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001075 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1076 tok::kw_while) ||
1077 (*(I + 1))->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001078 return;
1079 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001080 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001081 (*(I + 2))->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001082 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001083 join(Line, **(++I));
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001084 }
1085
Daniel Jasperb77d7412013-09-06 07:54:20 +00001086 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1087 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001088 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001089 // No merging if the brace already is on the next line.
1090 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1091 return;
1092
Manuel Klimek517e8942013-01-11 17:54:10 +00001093 // First, check that the current line allows merging. This is the case if
1094 // we're not in a control flow statement and the last token is an opening
1095 // brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001096 AnnotatedLine &Line = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001097 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1098 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001099 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001100 // This gets rid of all ObjC @ keywords and methods.
1101 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001102 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001103
Daniel Jasper567dcf92013-09-05 09:29:45 +00001104 FormatToken *Tok = (*(I + 1))->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001105 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001106 (Tok->getNextNonComment() == NULL ||
1107 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001108 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001109 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001110 Tok->CanBreakBefore = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001111 join(Line, **(I + 1));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001112 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001113 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001114 // Check that we still have three lines and they fit into the limit.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001115 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001116 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001117 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001118
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001119 // Second, check that the next line does not contain any braces - if it
1120 // does, readability declines when putting it into a single line.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001121 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001122 return;
1123 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001124 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001125 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001126 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001127 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001128
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001129 // Last, check that the third line contains a single closing brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001130 Tok = (*(I + 2))->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001131 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001132 Tok->MustBreakBefore)
1133 return;
1134
Daniel Jasper567dcf92013-09-05 09:29:45 +00001135 join(Line, **(I + 1));
1136 join(Line, **(I + 2));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001137 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001138 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001139 }
1140
Daniel Jasperb77d7412013-09-06 07:54:20 +00001141 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001142 unsigned Limit) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001143 return 1 + (*(I + 1))->Last->TotalLength + 1 +
1144 (*(I + 2))->Last->TotalLength <=
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001145 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001146 }
1147
Daniel Jasper995e8202013-01-14 13:08:07 +00001148 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001149 assert(!A.Last->Next);
1150 assert(!B.First->Previous);
1151 A.Last->Next = B.First;
1152 B.First->Previous = A.Last;
1153 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1154 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1155 Tok->TotalLength += LengthA;
1156 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001157 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001158 }
1159
Daniel Jasper6f21a982013-03-13 07:49:51 +00001160 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001161 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1162 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1163 Ranges[i].getBegin()) &&
1164 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1165 Range.getBegin()))
1166 return true;
1167 }
1168 return false;
1169 }
1170
1171 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001172 const FormatToken *First = TheLine.First;
1173 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001174 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001175 First->WhitespaceRange.getBegin().getLocWithOffset(
1176 First->LastNewlineOffset),
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001177 Last->getStartOfNonWhitespace().getLocWithOffset(
1178 Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001179 return touchesRanges(LineRange);
1180 }
1181
Daniel Jasperb77d7412013-09-06 07:54:20 +00001182 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
1183 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001184 for (; I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001185 if ((*I)->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001186 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001187 if (touchesLine(**I))
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001188 return true;
1189 }
1190 return false;
1191 }
1192
Daniel Jasperf3023542013-03-07 20:50:00 +00001193 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001194 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001195 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001196 First->WhitespaceRange.getBegin(),
1197 First->WhitespaceRange.getBegin().getLocWithOffset(
1198 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001199 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001200 }
1201
1202 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001203 AnnotatedLines.push_back(new AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001204 }
1205
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001206 /// \brief Add a new line and the required indent before the first Token
1207 /// of the \c UnwrappedLine if there was no structural parsing error.
1208 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001209 void formatFirstToken(const FormatToken &RootToken,
1210 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001211 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001212 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001213 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001214 // Remove empty lines before "}" where applicable.
1215 if (RootToken.is(tok::r_brace) &&
1216 (!RootToken.Next ||
1217 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1218 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001219 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001220 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001221
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001222 // Insert extra new line before access specifiers.
1223 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001224 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001225 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001226
Manuel Klimekb3987012013-05-29 14:47:47 +00001227 Whitespaces.replaceWhitespace(
1228 RootToken, Newlines, Indent, Indent,
1229 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001230 }
1231
Daniel Jasper567dcf92013-09-05 09:29:45 +00001232 unsigned getColumnLimit(bool InPPDirective) const {
1233 // In preprocessor directives reserve two chars for trailing " \"
1234 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1235 }
1236
Daniel Jasperbac016b2012-12-03 18:12:45 +00001237 FormatStyle Style;
1238 Lexer &Lex;
1239 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001240 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001241 std::vector<CharSourceRange> Ranges;
Daniel Jasperb77d7412013-09-06 07:54:20 +00001242 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001243
1244 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001245 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001246};
1247
Craig Topper83f81d72013-06-30 22:29:28 +00001248} // end anonymous namespace
1249
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001250tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1251 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001252 std::vector<CharSourceRange> Ranges) {
1253 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001254 return formatter.format();
1255}
1256
Daniel Jasper8a999452013-05-16 10:40:07 +00001257tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1258 std::vector<tooling::Range> Ranges,
1259 StringRef FileName) {
1260 FileManager Files((FileSystemOptions()));
1261 DiagnosticsEngine Diagnostics(
1262 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1263 new DiagnosticOptions);
1264 SourceManager SourceMgr(Diagnostics, Files);
1265 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1266 const clang::FileEntry *Entry =
1267 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1268 SourceMgr.overrideFileContents(Entry, Buf);
1269 FileID ID =
1270 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001271 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1272 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001273 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1274 std::vector<CharSourceRange> CharRanges;
1275 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1276 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1277 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1278 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1279 }
1280 return reformat(Style, Lex, SourceMgr, CharRanges);
1281}
1282
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001283LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001284 LangOptions LangOpts;
1285 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001286 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001287 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001288 LangOpts.Bool = 1;
1289 LangOpts.ObjC1 = 1;
1290 LangOpts.ObjC2 = 1;
1291 return LangOpts;
1292}
1293
Daniel Jaspercd162382013-01-07 13:26:07 +00001294} // namespace format
1295} // namespace clang