blob: 080769d159a2d3f7c408ba6474b142656886e285 [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 Kornienko6d2c88e2013-12-10 10:30:34 +000034using clang::format::FormatStyle;
35
Alexander Kornienkod6538332013-05-07 15:32:14 +000036namespace llvm {
37namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000038template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
39 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
40 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
41 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
42 }
43};
44
45template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
46 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
47 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
48 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
49 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
50 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
51 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
52 }
53};
54
55template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
56 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
57 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
58 IO.enumCase(Value, "false", FormatStyle::UT_Never);
59 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
60 IO.enumCase(Value, "true", FormatStyle::UT_Always);
61 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
62 }
63};
64
65template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
66 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
67 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
68 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
69 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
70 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000071 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000072 }
73};
74
Alexander Kornienkod6538332013-05-07 15:32:14 +000075template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000076struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000077 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000078 FormatStyle::NamespaceIndentationKind &Value) {
79 IO.enumCase(Value, "None", FormatStyle::NI_None);
80 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
81 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000082 }
83};
84
85template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000087 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000088 FormatStyle::SpaceBeforeParensOptions &Value) {
89 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000090 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000091 FormatStyle::SBPO_ControlStatements);
92 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000093
94 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000095 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
96 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000097 }
98};
99
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000100template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000101 static void mapping(IO &IO, FormatStyle &Style) {
102 // When reading, read the language first, we need it for getPredefinedStyle.
103 IO.mapOptional("Language", Style.Language);
104
Alexander Kornienko49149672013-05-10 11:56:10 +0000105 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000106 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000107 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000108 ArrayRef<StringRef> Styles(StylesArray);
109 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
110 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000111 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000112 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000113 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000114 IO.mapOptional("# BasedOnStyle", StyleName);
115 break;
116 }
117 }
118 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000119 StringRef BasedOnStyle;
120 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000121 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000122 FormatStyle::LanguageKind OldLanguage = Style.Language;
123 FormatStyle::LanguageKind Language =
124 ((FormatStyle *)IO.getContext())->Language;
125 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000126 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
127 return;
128 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000129 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000130 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000131 }
132
133 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000134 IO.mapOptional("ConstructorInitializerIndentWidth",
135 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000136 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000137 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000138 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
139 Style.AllowAllParametersOfDeclarationOnNextLine);
140 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
141 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000142 IO.mapOptional("AllowShortLoopsOnASingleLine",
143 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000144 IO.mapOptional("AllowShortFunctionsOnASingleLine",
145 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000146 IO.mapOptional("AlwaysBreakTemplateDeclarations",
147 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000148 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
149 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000150 IO.mapOptional("BreakBeforeBinaryOperators",
151 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000152 IO.mapOptional("BreakBeforeTernaryOperators",
153 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000154 IO.mapOptional("BreakConstructorInitializersBeforeComma",
155 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000156 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
157 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
158 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
159 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
160 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000161 IO.mapOptional("ExperimentalAutoDetectBinPacking",
162 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000163 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
164 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000165 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000166 IO.mapOptional("ObjCSpaceBeforeProtocolList",
167 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000168 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
169 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000170 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
171 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000172 IO.mapOptional("PenaltyBreakFirstLessLess",
173 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000174 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
175 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
176 Style.PenaltyReturnTypeOnItsOwnLine);
177 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
178 IO.mapOptional("SpacesBeforeTrailingComments",
179 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000180 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000181 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000182 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000183 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000184 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000185 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000186 IO.mapOptional("IndentFunctionDeclarationAfterType",
187 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000188 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000189 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000190 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000191 IO.mapOptional("SpacesInCStyleCastParentheses",
192 Style.SpacesInCStyleCastParentheses);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000193 IO.mapOptional("SpaceBeforeAssignmentOperators",
194 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000195 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000196
197 // For backward compatibility.
198 if (!IO.outputting()) {
199 IO.mapOptional("SpaceAfterControlStatementKeyword",
200 Style.SpaceBeforeParens);
201 }
202 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 }
204};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000205
206// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000207// IO.getContext() should contain a pointer to the FormatStyle structure, that
208// will be used to get default values for missing keys.
209// If the first element has no Language specified, it will be treated as the
210// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000211template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000212 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
213 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000214 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000215 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000216 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000217 if (Index >= Seq.size()) {
218 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000219 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000220 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000221 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000222 } else {
223 Template = *((const FormatStyle*)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000224 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000225 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000226 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000227 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000228 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000229 }
230};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231}
232}
233
Daniel Jasperf7935112012-12-03 18:12:45 +0000234namespace clang {
235namespace format {
236
Daniel Jasperf7935112012-12-03 18:12:45 +0000237FormatStyle getLLVMStyle() {
238 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000239 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000240 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000241 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000242 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000243 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000244 LLVMStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000245 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000246 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000247 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000248 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000249 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000250 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000251 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000252 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
253 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000254 LLVMStyle.ColumnLimit = 80;
255 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000256 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000257 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000258 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000259 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000260 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000261 LLVMStyle.IndentFunctionDeclarationAfterType = false;
262 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000263 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000264 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000265 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000266 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000267 LLVMStyle.PointerBindsToType = false;
268 LLVMStyle.SpacesBeforeTrailingComments = 1;
269 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000270 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000271 LLVMStyle.SpacesInParentheses = false;
272 LLVMStyle.SpaceInEmptyParentheses = false;
273 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000274 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000275 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000276 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000277 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000278
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000279 LLVMStyle.PenaltyBreakComment = 60;
280 LLVMStyle.PenaltyBreakFirstLessLess = 120;
281 LLVMStyle.PenaltyBreakString = 1000;
282 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000283 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000284 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000285
Daniel Jasperf7935112012-12-03 18:12:45 +0000286 return LLVMStyle;
287}
288
289FormatStyle getGoogleStyle() {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000290 FormatStyle GoogleStyle = getLLVMStyle();
Daniel Jasperf7935112012-12-03 18:12:45 +0000291 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000292 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000293 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000294 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000295 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000296 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000297 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000298 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000299 GoogleStyle.DerivePointerBinding = true;
300 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000301 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Nico Webera6087752013-01-10 20:12:55 +0000302 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000303 GoogleStyle.PointerBindsToType = true;
304 GoogleStyle.SpacesBeforeTrailingComments = 2;
305 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000306
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000307 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000308 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000309
Daniel Jasperf7935112012-12-03 18:12:45 +0000310 return GoogleStyle;
311}
312
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000313FormatStyle getGoogleJSStyle() {
314 FormatStyle GoogleJSStyle = getGoogleStyle();
315 GoogleJSStyle.Language = FormatStyle::LK_JavaScript;
316 GoogleJSStyle.BreakBeforeTernaryOperators = false;
317 // FIXME: Currently unimplemented:
318 // var arr = [1, 2, 3]; // No space after [ or before ].
319 // var obj = {a: 1, b: 2, c: 3}; // No space after ':'.
320 return GoogleJSStyle;
321}
322
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000323FormatStyle getChromiumStyle() {
324 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000325 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000326 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000327 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000328 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000329 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000330 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000331 return ChromiumStyle;
332}
333
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000334FormatStyle getMozillaStyle() {
335 FormatStyle MozillaStyle = getLLVMStyle();
336 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
337 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
338 MozillaStyle.DerivePointerBinding = true;
339 MozillaStyle.IndentCaseLabels = true;
340 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
341 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
342 MozillaStyle.PointerBindsToType = true;
343 return MozillaStyle;
344}
345
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000346FormatStyle getWebKitStyle() {
347 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000348 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000349 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000350 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000351 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000352 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000353 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000354 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000355 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000356 Style.PointerBindsToType = true;
357 return Style;
358}
359
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000360FormatStyle getGNUStyle() {
361 FormatStyle Style = getLLVMStyle();
362 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000363 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000364 Style.BreakBeforeTernaryOperators = true;
365 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000366 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
367 return Style;
368}
369
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000370bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
371 FormatStyle *Style) {
372 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000373 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000374 } else if (Name.equals_lower("chromium")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000375 *Style = getChromiumStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000376 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000377 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000378 } else if (Name.equals_lower("google")) {
379 *Style = Language == FormatStyle::LK_JavaScript ? getGoogleJSStyle()
380 : getGoogleStyle();
381 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000382 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000383 } else if (Name.equals_lower("gnu")) {
384 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000385 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000386 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000387 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000388
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000389 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000390 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000391}
392
393llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000394 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000395 FormatStyle::LanguageKind Language = Style->Language;
396 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000397 if (Text.trim().empty())
398 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000399
400 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000401 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000402 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
403 // values for the fields, keys for which are missing from the configuration.
404 // Mapping also uses the context to get the language to find the correct
405 // base style.
406 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000407 Input >> Styles;
408 if (Input.error())
409 return Input.error();
410
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000411 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000412 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000413 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000414 return llvm::make_error_code(llvm::errc::invalid_argument);
415 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000416 for (unsigned j = 0; j < i; ++j) {
417 if (Styles[i].Language == Styles[j].Language) {
418 DEBUG(llvm::dbgs()
419 << "Duplicate languages in the config file on positions " << j
420 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000421 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000422 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000423 }
424 }
425 // Look for a suitable configuration starting from the end, so we can
426 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000427 // configuration (which can only be at slot 0) after it.
428 for (int i = Styles.size() - 1; i >= 0; --i) {
429 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000430 Styles[i].Language == FormatStyle::LK_None) {
431 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000432 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000433 return llvm::make_error_code(llvm::errc::success);
434 }
435 }
436 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000437}
438
439std::string configurationAsText(const FormatStyle &Style) {
440 std::string Text;
441 llvm::raw_string_ostream Stream(Text);
442 llvm::yaml::Output Output(Stream);
443 // We use the same mapping method for input and output, so we need a non-const
444 // reference here.
445 FormatStyle NonConstStyle = Style;
446 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000447 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000448}
449
Craig Topperaf35e852013-06-30 22:29:28 +0000450namespace {
451
Daniel Jasperde0328a2013-08-16 11:20:30 +0000452class NoColumnLimitFormatter {
453public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000454 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000455
456 /// \brief Formats the line starting at \p State, simply keeping all of the
457 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000458 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000459 LineState State =
460 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000461 while (State.NextToken != NULL) {
462 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000463 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000464 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
465 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
466 }
467 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000468
Daniel Jasperde0328a2013-08-16 11:20:30 +0000469private:
470 ContinuationIndenter *Indenter;
471};
472
Daniel Jasper56f8b432013-11-06 23:12:09 +0000473class LineJoiner {
474public:
475 LineJoiner(const FormatStyle &Style) : Style(Style) {}
476
477 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
478 unsigned
479 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000480 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000481 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
482 // We can never merge stuff if there are trailing line comments.
483 AnnotatedLine *TheLine = *I;
484 if (TheLine->Last->Type == TT_LineComment)
485 return 0;
486
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000487 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
488 return 0;
489
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000490 unsigned Limit =
491 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000492 // If we already exceed the column limit, we set 'Limit' to 0. The different
493 // tryMerge..() functions can then decide whether to still do merging.
494 Limit = TheLine->Last->TotalLength > Limit
495 ? 0
496 : Limit - TheLine->Last->TotalLength;
497
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000498 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000499 return 0;
500
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000501 if (TheLine->Last->Type == TT_FunctionLBrace) {
502 return Style.AllowShortFunctionsOnASingleLine
503 ? tryMergeSimpleBlock(I, E, Limit)
504 : 0;
505 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000506 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000507 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000508 ? tryMergeSimpleBlock(I, E, Limit)
509 : 0;
510 }
511 if (I[1]->First->Type == TT_FunctionLBrace &&
512 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
513 // Reduce the column limit by the number of spaces we need to insert
514 // around braces.
515 Limit = Limit > 3 ? Limit - 3 : 0;
516 unsigned MergedLines = 0;
517 if (Style.AllowShortFunctionsOnASingleLine) {
518 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
519 // If we managed to merge the block, count the function header, which is
520 // on a separate line.
521 if (MergedLines > 0)
522 ++MergedLines;
523 }
524 return MergedLines;
525 }
526 if (TheLine->First->is(tok::kw_if)) {
527 return Style.AllowShortIfStatementsOnASingleLine
528 ? tryMergeSimpleControlStatement(I, E, Limit)
529 : 0;
530 }
531 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
532 return Style.AllowShortLoopsOnASingleLine
533 ? tryMergeSimpleControlStatement(I, E, Limit)
534 : 0;
535 }
536 if (TheLine->InPPDirective &&
537 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000538 return tryMergeSimplePPDirective(I, E, Limit);
539 }
540 return 0;
541 }
542
543private:
544 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000545 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000546 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
547 unsigned Limit) {
548 if (Limit == 0)
549 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000550 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000551 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000552 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000553 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000554 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000555 return 0;
556 return 1;
557 }
558
559 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000560 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000561 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
562 if (Limit == 0)
563 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000564 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
565 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000566 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000567 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000568 if (I[1]->InPPDirective != (*I)->InPPDirective ||
569 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000570 return 0;
571 AnnotatedLine &Line = **I;
572 if (Line.Last->isNot(tok::r_paren))
573 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000574 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000575 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000576 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000577 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000578 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000579 return 0;
580 // Only inline simple if's (no nested if or else).
581 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000582 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000583 return 0;
584 return 1;
585 }
586
587 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000588 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000589 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
590 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000591 // First, check that the current line allows merging. This is the case if
592 // we're not in a control flow statement and the last token is an opening
593 // brace.
594 AnnotatedLine &Line = **I;
595 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
596 tok::kw_else, tok::kw_try, tok::kw_catch,
597 tok::kw_for,
598 // This gets rid of all ObjC @ keywords and methods.
599 tok::at, tok::minus, tok::plus))
600 return 0;
601
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000602 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000603 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
604 (Tok->getNextNonComment() == NULL ||
605 Tok->getNextNonComment()->is(tok::semi))) {
606 // We merge empty blocks even if the line exceeds the column limit.
607 Tok->SpacesRequiredBefore = 0;
608 Tok->CanBreakBefore = true;
609 return 1;
610 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
611 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000612 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000613 return 0;
614
615 if (!nextTwoLinesFitInto(I, Limit))
616 return 0;
617
618 // Second, check that the next line does not contain any braces - if it
619 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000620 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000621 return 0;
622 do {
623 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
624 return 0;
625 Tok = Tok->Next;
626 } while (Tok != NULL);
627
628 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000629 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000630 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
631 Tok->MustBreakBefore)
632 return 0;
633
634 return 2;
635 }
636 return 0;
637 }
638
639 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
640 unsigned Limit) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000641 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000642 }
643
644 const FormatStyle &Style;
645};
646
Daniel Jasperf7935112012-12-03 18:12:45 +0000647class UnwrappedLineFormatter {
648public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000649 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000650 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000651 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000652 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
653 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000654
Daniel Jasper56f8b432013-11-06 23:12:09 +0000655 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000656 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000657 assert(!Lines.empty());
658 unsigned Penalty = 0;
659 std::vector<int> IndentForLevel;
660 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
661 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000662 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000663 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
664 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000665 I != E; ++I) {
666 const AnnotatedLine &TheLine = **I;
667 const FormatToken *FirstTok = TheLine.First;
668 int Offset = getIndentOffset(*FirstTok);
669
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000670 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000671 unsigned Indent;
672 if (TheLine.InPPDirective) {
673 Indent = TheLine.Level * Style.IndentWidth;
674 } else {
675 while (IndentForLevel.size() <= TheLine.Level)
676 IndentForLevel.push_back(-1);
677 IndentForLevel.resize(TheLine.Level + 1);
678 Indent = getIndent(IndentForLevel, TheLine.Level);
679 }
680 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000681 if (static_cast<int>(Indent) + Offset >= 0)
682 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000683
684 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000686 if (MergedLines > 0 && Style.ColumnLimit == 0) {
687 // Disallow line merging if there is a break at the start of one of the
688 // input lines.
689 for (unsigned i = 0; i < MergedLines; ++i) {
690 if (I[i + 1]->First->NewlinesBefore > 0)
691 MergedLines = 0;
692 }
693 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000694 if (!DryRun) {
695 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000696 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 }
698 }
699 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000700
Daniel Jasper9c199562013-11-28 15:58:55 +0000701 bool FixIndentation =
702 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000703 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000704 if (PreviousLine && PreviousLine->Affected && !DryRun) {
705 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000706 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
707 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
708 /*IndentLevel=*/0, /*Spaces=*/0,
709 /*TargetColumn=*/0);
710 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000711 } else if (TheLine.Type != LT_Invalid &&
712 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000713 if (FirstTok->WhitespaceRange.isValid()) {
714 if (!DryRun)
715 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
716 Indent, TheLine.InPPDirective);
717 } else {
718 Indent = LevelIndent = FirstTok->OriginalColumn;
719 }
720
721 // If everything fits on a single line, just put it there.
722 unsigned ColumnLimit = Style.ColumnLimit;
723 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000724 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000725 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
726 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
727 }
728
729 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
730 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
731 while (State.NextToken != NULL)
732 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
733 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000734 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000735 NoColumnLimitFormatter Formatter(Indenter);
736 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000737 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000738 } else {
739 Penalty += format(TheLine, Indent, DryRun);
740 }
741
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000742 if (!TheLine.InPPDirective)
743 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000744 } else if (TheLine.ChildrenAffected) {
745 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000746 } else {
747 // Format the first token if necessary, and notify the WhitespaceManager
748 // about the unchanged whitespace.
749 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
750 if (Tok == TheLine.First &&
751 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
752 unsigned LevelIndent = Tok->OriginalColumn;
753 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000754 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000755 if ((PreviousLine && PreviousLine->Affected) ||
756 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000757 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
758 TheLine.InPPDirective);
759 } else {
760 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
761 }
762 }
763
764 if (static_cast<int>(LevelIndent) - Offset >= 0)
765 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000766 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000767 IndentForLevel[TheLine.Level] = LevelIndent;
768 } else if (!DryRun) {
769 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
770 }
771 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000772 }
773 if (!DryRun) {
774 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
775 Tok->Finalized = true;
776 }
777 }
778 PreviousLine = *I;
779 }
780 return Penalty;
781 }
782
783private:
784 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000785 ///
786 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000787 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
788 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000789 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000790
Daniel Jasperacc33662013-02-08 08:22:00 +0000791 // If the ObjC method declaration does not fit on a line, we should format
792 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000793 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000794 State.Stack.back().BreakBeforeParameter = true;
795
Daniel Jasper4b866272013-02-01 11:00:45 +0000796 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000797 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000798 }
799
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000800 /// \brief An edge in the solution space from \c Previous->State to \c State,
801 /// inserting a newline dependent on the \c NewLine.
802 struct StateNode {
803 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000804 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000805 LineState State;
806 bool NewLine;
807 StateNode *Previous;
808 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000809
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000810 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
811 ///
812 /// In case of equal penalties, we want to prefer states that were inserted
813 /// first. During state generation we make sure that we insert states first
814 /// that break the line as late as possible.
815 typedef std::pair<unsigned, unsigned> OrderedPenalty;
816
817 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
818 /// \c State has the given \c OrderedPenalty.
819 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
820
821 /// \brief The BFS queue type.
822 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
823 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000824
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000825 /// \brief Get the offset of the line relatively to the level.
826 ///
827 /// For example, 'public:' labels in classes are offset by 1 or 2
828 /// characters to the left from their level.
829 int getIndentOffset(const FormatToken &RootToken) {
830 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
831 return Style.AccessModifierOffset;
832 return 0;
833 }
834
835 /// \brief Add a new line and the required indent before the first Token
836 /// of the \c UnwrappedLine if there was no structural parsing error.
837 void formatFirstToken(FormatToken &RootToken,
838 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
839 unsigned Indent, bool InPPDirective) {
840 unsigned Newlines =
841 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
842 // Remove empty lines before "}" where applicable.
843 if (RootToken.is(tok::r_brace) &&
844 (!RootToken.Next ||
845 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
846 Newlines = std::min(Newlines, 1u);
847 if (Newlines == 0 && !RootToken.IsFirst)
848 Newlines = 1;
849
850 // Insert extra new line before access specifiers.
851 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
852 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
853 ++Newlines;
854
855 // Remove empty lines after access specifiers.
856 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
857 Newlines = std::min(1u, Newlines);
858
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000859 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
860 Indent, InPPDirective &&
861 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000862 }
863
864 /// \brief Get the indent of \p Level from \p IndentForLevel.
865 ///
866 /// \p IndentForLevel must contain the indent for the level \c l
867 /// at \p IndentForLevel[l], or a value < 0 if the indent for
868 /// that level is unknown.
869 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
870 if (IndentForLevel[Level] != -1)
871 return IndentForLevel[Level];
872 if (Level == 0)
873 return 0;
874 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
875 }
876
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000877 void join(AnnotatedLine &A, const AnnotatedLine &B) {
878 assert(!A.Last->Next);
879 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000880 if (B.Affected)
881 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000882 A.Last->Next = B.First;
883 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000884 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000885 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
886 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
887 Tok->TotalLength += LengthA;
888 A.Last = Tok;
889 }
890 }
891
892 unsigned getColumnLimit(bool InPPDirective) const {
893 // In preprocessor directives reserve two chars for trailing " \"
894 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
895 }
896
Daniel Jasper4b866272013-02-01 11:00:45 +0000897 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000898 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000899 /// This implements a variant of Dijkstra's algorithm on the graph that spans
900 /// the solution space (\c LineStates are the nodes). The algorithm tries to
901 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000902 /// to a state where all tokens are placed. Returns the penalty.
903 ///
904 /// If \p DryRun is \c false, directly applies the changes.
905 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 std::set<LineState> Seen;
907
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000908 // Increasing count of \c StateNode items we have created. This is used to
909 // create a deterministic order independent of the container.
910 unsigned Count = 0;
911 QueueType Queue;
912
Daniel Jasper4b866272013-02-01 11:00:45 +0000913 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000914 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000915 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
916 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
917 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000918
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000919 unsigned Penalty = 0;
920
Daniel Jasper4b866272013-02-01 11:00:45 +0000921 // While not empty, take first element and follow edges.
922 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000923 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000924 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000925 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000926 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000927 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000928 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000929 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000930
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000931 // Cut off the analysis of certain solutions if the analysis gets too
932 // complex. See description of IgnoreStackForComparison.
933 if (Count > 10000)
934 Node->State.IgnoreStackForComparison = true;
935
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000936 if (!Seen.insert(Node->State).second)
937 // State already examined with lower penalty.
938 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000939
Manuel Klimek71814b42013-10-11 21:25:45 +0000940 FormatDecision LastFormat = Node->State.NextToken->Decision;
941 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000942 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +0000943 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000944 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 }
946
Manuel Klimek71814b42013-10-11 21:25:45 +0000947 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000948 // We were unable to find a solution, do nothing.
949 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +0000950 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000951 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +0000952 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000953
Daniel Jasper4b866272013-02-01 11:00:45 +0000954 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000955 if (!DryRun)
956 reconstructPath(InitialState, Queue.top().second);
957
Alexander Kornienko49149672013-05-10 11:56:10 +0000958 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
959 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000960
961 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000962 }
963
964 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000965 std::deque<StateNode *> Path;
966 // We do not need a break before the initial token.
967 while (Current->Previous) {
968 Path.push_front(Current);
969 Current = Current->Previous;
970 }
971 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
972 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000973 unsigned Penalty = 0;
974 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
975 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
976
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000977 DEBUG({
978 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000979 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000980 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000981 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000982 }
983 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000984 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000985 }
986
Manuel Klimekaf491072013-02-13 10:54:19 +0000987 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000988 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000989 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000990 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000991 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000992 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000993 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000994 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000995 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000996 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000997
998 StateNode *Node = new (Allocator.Allocate())
999 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001000 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1001 return;
1002
Daniel Jasperde0328a2013-08-16 11:20:30 +00001003 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001004
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001005 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1006 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001007 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001008
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001009 /// \brief If the \p State's next token is an r_brace closing a nested block,
1010 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001011 ///
1012 /// Returns \c true if all children could be placed successfully and adapts
1013 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1014 /// creates changes using \c Whitespaces.
1015 ///
1016 /// The crucial idea here is that children always get formatted upon
1017 /// encountering the closing brace right after the nested block. Now, if we
1018 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1019 /// \c false), the entire block has to be kept on the same line (which is only
1020 /// possible if it fits on the line, only contains a single statement, etc.
1021 ///
1022 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1023 /// break after the "{", format all lines with correct indentation and the put
1024 /// the closing "}" on yet another new line.
1025 ///
1026 /// This enables us to keep the simple structure of the
1027 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1028 /// break or don't break.
1029 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1030 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001031 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001032 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1033 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1034 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001035 // The previous token does not open a block. Nothing to do. We don't
1036 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001037 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001038
1039 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001040 int AdditionalIndent = State.Stack.back().Indent -
1041 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001042 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1043 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001044 return true;
1045 }
1046
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001047 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001048 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001049 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001050
1051 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001052 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001053 return false;
1054
1055 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001056 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001057 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001058 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001059 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001060 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001061 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001062
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001063 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001064 return true;
1065 }
1066
Daniel Jasperde0328a2013-08-16 11:20:30 +00001067 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001068 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001069 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001070 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001071
1072 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001073};
1074
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001075class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001076public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001077 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001078 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001079 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001080 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1081 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001082 Lex.SetKeepWhitespaceMode(true);
1083 }
1084
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001085 ArrayRef<FormatToken *> lex() {
1086 assert(Tokens.empty());
1087 do {
1088 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001089 tryMergePreviousTokens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001090 } while (Tokens.back()->Tok.isNot(tok::eof));
1091 return Tokens;
1092 }
1093
1094 IdentifierTable &getIdentTable() { return IdentTable; }
1095
1096private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001097 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001098 if (tryMerge_TMacro())
1099 return;
1100
1101 if (Style.Language == FormatStyle::LK_JavaScript) {
1102 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1103 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1104 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1105 tok::greaterequal };
1106 // FIXME: We probably need to change token type to mimic operator with the
1107 // correct priority.
1108 if (tryMergeTokens(JSIdentity))
1109 return;
1110 if (tryMergeTokens(JSNotIdentity))
1111 return;
1112 if (tryMergeTokens(JSShiftEqual))
1113 return;
1114 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001115 }
1116
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001117 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1118 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001119 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001120
1121 SmallVectorImpl<FormatToken *>::const_iterator First =
1122 Tokens.end() - Kinds.size();
1123 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001124 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001125 unsigned AddLength = 0;
1126 for (unsigned i = 1; i < Kinds.size(); ++i) {
1127 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1128 First[i]->WhitespaceRange.getEnd())
1129 return false;
1130 AddLength += First[i]->TokenText.size();
1131 }
1132 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1133 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1134 First[0]->TokenText.size() + AddLength);
1135 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001136 return true;
1137 }
1138
1139 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001140 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001141 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001142 FormatToken *Last = Tokens.back();
1143 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001144 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001145
1146 FormatToken *String = Tokens[Tokens.size() - 2];
1147 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001148 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001149
1150 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001151 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001152
1153 FormatToken *Macro = Tokens[Tokens.size() - 4];
1154 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001155 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001156
1157 const char *Start = Macro->TokenText.data();
1158 const char *End = Last->TokenText.data() + Last->TokenText.size();
1159 String->TokenText = StringRef(Start, End - Start);
1160 String->IsFirst = Macro->IsFirst;
1161 String->LastNewlineOffset = Macro->LastNewlineOffset;
1162 String->WhitespaceRange = Macro->WhitespaceRange;
1163 String->OriginalColumn = Macro->OriginalColumn;
1164 String->ColumnWidth = encoding::columnWidthWithTabs(
1165 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1166
1167 Tokens.pop_back();
1168 Tokens.pop_back();
1169 Tokens.pop_back();
1170 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001171 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001172 }
1173
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001174 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001175 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001176 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001177 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001178 Token Greater = FormatTok->Tok;
1179 FormatTok = new (Allocator.Allocate()) FormatToken;
1180 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001181 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001182 FormatTok->Tok.getLocation().getLocWithOffset(1);
1183 FormatTok->WhitespaceRange =
1184 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001185 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001186 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001187 GreaterStashed = false;
1188 return FormatTok;
1189 }
1190
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001191 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001192 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001193 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001194 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001195 FormatTok->IsFirst = IsFirstToken;
1196 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001197
1198 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001199 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001200 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001201 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1202 switch (FormatTok->TokenText[i]) {
1203 case '\n':
1204 ++FormatTok->NewlinesBefore;
1205 // FIXME: This is technically incorrect, as it could also
1206 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001207 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1208 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1209 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001210 FormatTok->HasUnescapedNewline = true;
1211 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1212 Column = 0;
1213 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001214 case '\r':
1215 case '\f':
1216 case '\v':
1217 Column = 0;
1218 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001219 case ' ':
1220 ++Column;
1221 break;
1222 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001223 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001224 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001225 case '\\':
1226 ++Column;
1227 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1228 FormatTok->TokenText[i + 1] != '\n'))
1229 FormatTok->Type = TT_ImplicitStringLiteral;
1230 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001231 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001232 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001233 ++Column;
1234 break;
1235 }
1236 }
1237
Daniel Jasper877615c2013-10-11 19:45:02 +00001238 if (FormatTok->Type == TT_ImplicitStringLiteral)
1239 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001240 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001241
Daniel Jasper8369aa52013-07-16 20:28:33 +00001242 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001243 }
Manuel Klimekef920692013-01-07 07:56:50 +00001244
Manuel Klimek1abf7892013-01-04 23:34:14 +00001245 // In case the token starts with escaped newlines, we want to
1246 // take them into account as whitespace - this pattern is quite frequent
1247 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001248 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001249 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1250 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001251 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001252 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001253 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001254 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001255 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001256
1257 FormatTok->WhitespaceRange = SourceRange(
1258 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1259
Manuel Klimek31c85922013-08-29 15:21:40 +00001260 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001261
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001262 TrailingWhitespace = 0;
1263 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001264 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001265 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001266 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001267 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001268 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001269 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001270 FormatTok->Tok.setIdentifierInfo(&Info);
1271 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001272 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001273 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001274 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275 GreaterStashed = true;
1276 }
1277
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001278 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001279
Alexander Kornienko39856b72013-09-10 09:38:25 +00001280 StringRef Text = FormatTok->TokenText;
1281 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001282 if (FirstNewlinePos == StringRef::npos) {
1283 // FIXME: ColumnWidth actually depends on the start column, we need to
1284 // take this into account when the token is moved.
1285 FormatTok->ColumnWidth =
1286 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1287 Column += FormatTok->ColumnWidth;
1288 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001289 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001290 // FIXME: ColumnWidth actually depends on the start column, we need to
1291 // take this into account when the token is moved.
1292 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1293 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1294
Alexander Kornienko39856b72013-09-10 09:38:25 +00001295 // The last line of the token always starts in column 0.
1296 // Thus, the length can be precomputed even in the presence of tabs.
1297 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1298 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1299 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001300 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001301 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001302
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001303 return FormatTok;
1304 }
1305
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001306 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001307 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001308 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001309 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001310 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001311 Lexer &Lex;
1312 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001313 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001314 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001315 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001316 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1317 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001318
Daniel Jasper8369aa52013-07-16 20:28:33 +00001319 void readRawToken(FormatToken &Tok) {
1320 Lex.LexFromRawLexer(Tok.Tok);
1321 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1322 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001323 // For formatting, treat unterminated string literals like normal string
1324 // literals.
1325 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1326 Tok.TokenText[0] == '"') {
1327 Tok.Tok.setKind(tok::string_literal);
1328 Tok.IsUnterminatedLiteral = true;
1329 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001330 }
1331};
1332
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001333static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1334 switch (Language) {
1335 case FormatStyle::LK_Cpp:
1336 return "C++";
1337 case FormatStyle::LK_JavaScript:
1338 return "JavaScript";
1339 default:
1340 return "Unknown";
1341 }
1342}
1343
Daniel Jasperf7935112012-12-03 18:12:45 +00001344class Formatter : public UnwrappedLineConsumer {
1345public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001346 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001347 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001348 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001349 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001350 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001351 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001352 DEBUG(llvm::dbgs() << "File encoding: "
1353 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1354 : "unknown")
1355 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001356 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1357 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001358 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001359
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001360 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001361 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001362 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001363
1364 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001365 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001366 assert(UnwrappedLines.rbegin()->empty());
1367 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1368 ++Run) {
1369 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1370 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1371 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1372 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1373 }
1374 tooling::Replacements RunResult =
1375 format(AnnotatedLines, StructuralError, Tokens);
1376 DEBUG({
1377 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1378 for (tooling::Replacements::iterator I = RunResult.begin(),
1379 E = RunResult.end();
1380 I != E; ++I) {
1381 llvm::dbgs() << I->toString() << "\n";
1382 }
1383 });
1384 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1385 delete AnnotatedLines[i];
1386 }
1387 Result.insert(RunResult.begin(), RunResult.end());
1388 Whitespaces.reset();
1389 }
1390 return Result;
1391 }
1392
1393 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1394 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001395 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001396 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001397 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001398 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001399 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001400 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001401 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001402 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001403 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001404
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001405 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001406 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1407 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001408 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001409 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001410 return Whitespaces.generateReplacements();
1411 }
1412
1413private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001414 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001415 // Returns \c true if at least one line between I and E or one of their
1416 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001417 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1418 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1419 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001420 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001421 while (I != E) {
1422 AnnotatedLine *Line = *I;
1423 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1424
1425 // If a line is part of a preprocessor directive, it needs to be formatted
1426 // if any token within the directive is affected.
1427 if (Line->InPPDirective) {
1428 FormatToken *Last = Line->Last;
1429 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1430 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1431 Last = (*PPEnd)->Last;
1432 ++PPEnd;
1433 }
1434
1435 if (affectsTokenRange(*Line->First, *Last,
1436 /*IncludeLeadingNewlines=*/false)) {
1437 SomeLineAffected = true;
1438 markAllAsAffected(I, PPEnd);
1439 }
1440 I = PPEnd;
1441 continue;
1442 }
1443
Daniel Jasper38c82402013-11-29 09:27:43 +00001444 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001445 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001446
Daniel Jasper38c82402013-11-29 09:27:43 +00001447 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001448 ++I;
1449 }
1450 return SomeLineAffected;
1451 }
1452
Daniel Jasper9c199562013-11-28 15:58:55 +00001453 // Determines whether 'Line' is affected by the SourceRanges given as input.
1454 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001455 bool nonPPLineAffected(AnnotatedLine *Line,
1456 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001457 bool SomeLineAffected = false;
1458 Line->ChildrenAffected =
1459 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1460 if (Line->ChildrenAffected)
1461 SomeLineAffected = true;
1462
1463 // Stores whether one of the line's tokens is directly affected.
1464 bool SomeTokenAffected = false;
1465 // Stores whether we need to look at the leading newlines of the next token
1466 // in order to determine whether it was affected.
1467 bool IncludeLeadingNewlines = false;
1468
1469 // Stores whether the first child line of any of this line's tokens is
1470 // affected.
1471 bool SomeFirstChildAffected = false;
1472
1473 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1474 // Determine whether 'Tok' was affected.
1475 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1476 SomeTokenAffected = true;
1477
1478 // Determine whether the first child of 'Tok' was affected.
1479 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1480 SomeFirstChildAffected = true;
1481
1482 IncludeLeadingNewlines = Tok->Children.empty();
1483 }
1484
1485 // Was this line moved, i.e. has it previously been on the same line as an
1486 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001487 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1488 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001489
Daniel Jasper38c82402013-11-29 09:27:43 +00001490 bool IsContinuedComment = Line->First->is(tok::comment) &&
1491 Line->First->Next == NULL &&
1492 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001493 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001494 PreviousLine->Last->is(tok::comment);
1495
1496 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1497 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001498 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001499 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001500 }
1501 return SomeLineAffected;
1502 }
1503
Daniel Jasper5500f612013-11-25 11:08:59 +00001504 // Marks all lines between I and E as well as all their children as affected.
1505 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1506 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1507 while (I != E) {
1508 (*I)->Affected = true;
1509 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1510 ++I;
1511 }
1512 }
1513
1514 // Returns true if the range from 'First' to 'Last' intersects with one of the
1515 // input ranges.
1516 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1517 bool IncludeLeadingNewlines) {
1518 SourceLocation Start = First.WhitespaceRange.getBegin();
1519 if (!IncludeLeadingNewlines)
1520 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001521 SourceLocation End = Last.getStartOfNonWhitespace();
1522 if (Last.TokenText.size() > 0)
1523 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001524 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1525 return affectsCharSourceRange(Range);
1526 }
1527
1528 // Returns true if one of the input ranges intersect the leading empty lines
1529 // before 'Tok'.
1530 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1531 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1532 Tok.WhitespaceRange.getBegin(),
1533 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1534 return affectsCharSourceRange(EmptyLineRange);
1535 }
1536
1537 // Returns true if 'Range' intersects with one of the input ranges.
1538 bool affectsCharSourceRange(const CharSourceRange &Range) {
1539 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1540 E = Ranges.end();
1541 I != E; ++I) {
1542 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1543 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1544 return true;
1545 }
1546 return false;
1547 }
1548
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001549 static bool inputUsesCRLF(StringRef Text) {
1550 return Text.count('\r') * 2 > Text.count('\n');
1551 }
1552
Manuel Klimek71814b42013-10-11 21:25:45 +00001553 void
1554 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001555 unsigned CountBoundToVariable = 0;
1556 unsigned CountBoundToType = 0;
1557 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001558 bool HasBinPackedFunction = false;
1559 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001560 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001561 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001562 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001563 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001564 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001565 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001566 bool SpacesBefore =
1567 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1568 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1569 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001570 if (SpacesBefore && !SpacesAfter)
1571 ++CountBoundToVariable;
1572 else if (!SpacesBefore && SpacesAfter)
1573 ++CountBoundToType;
1574 }
1575
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001576 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1577 if (Tok->is(tok::coloncolon) &&
1578 Tok->Previous->Type == TT_TemplateOpener)
1579 HasCpp03IncompatibleFormat = true;
1580 if (Tok->Type == TT_TemplateCloser &&
1581 Tok->Previous->Type == TT_TemplateCloser)
1582 HasCpp03IncompatibleFormat = true;
1583 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001584
1585 if (Tok->PackingKind == PPK_BinPacked)
1586 HasBinPackedFunction = true;
1587 if (Tok->PackingKind == PPK_OnePerLine)
1588 HasOnePerLineFunction = true;
1589
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001590 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001591 }
1592 }
1593 if (Style.DerivePointerBinding) {
1594 if (CountBoundToType > CountBoundToVariable)
1595 Style.PointerBindsToType = true;
1596 else if (CountBoundToType < CountBoundToVariable)
1597 Style.PointerBindsToType = false;
1598 }
1599 if (Style.Standard == FormatStyle::LS_Auto) {
1600 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1601 : FormatStyle::LS_Cpp03;
1602 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001603 BinPackInconclusiveFunctions =
1604 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001605 }
1606
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001607 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001608 assert(!UnwrappedLines.empty());
1609 UnwrappedLines.back().push_back(TheLine);
1610 }
1611
1612 virtual void finishRun() {
1613 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001614 }
1615
1616 FormatStyle Style;
1617 Lexer &Lex;
1618 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001619 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001620 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001621 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001622
1623 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001624 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001625};
1626
Craig Topperaf35e852013-06-30 22:29:28 +00001627} // end anonymous namespace
1628
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001629tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1630 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001631 std::vector<CharSourceRange> Ranges) {
1632 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001633 return formatter.format();
1634}
1635
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001636tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1637 std::vector<tooling::Range> Ranges,
1638 StringRef FileName) {
1639 FileManager Files((FileSystemOptions()));
1640 DiagnosticsEngine Diagnostics(
1641 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1642 new DiagnosticOptions);
1643 SourceManager SourceMgr(Diagnostics, Files);
1644 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1645 const clang::FileEntry *Entry =
1646 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1647 SourceMgr.overrideFileContents(Entry, Buf);
1648 FileID ID =
1649 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001650 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1651 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001652 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1653 std::vector<CharSourceRange> CharRanges;
1654 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1655 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1656 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1657 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1658 }
1659 return reformat(Style, Lex, SourceMgr, CharRanges);
1660}
1661
Alexander Kornienko1e808872013-06-28 12:51:24 +00001662LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001663 LangOptions LangOpts;
1664 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001665 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001666 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001667 LangOpts.Bool = 1;
1668 LangOpts.ObjC1 = 1;
1669 LangOpts.ObjC2 = 1;
1670 return LangOpts;
1671}
1672
Edwin Vaned544aa72013-09-30 13:31:48 +00001673const char *StyleOptionHelpDescription =
1674 "Coding style, currently supports:\n"
1675 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1676 "Use -style=file to load style configuration from\n"
1677 ".clang-format file located in one of the parent\n"
1678 "directories of the source file (or current\n"
1679 "directory for stdin).\n"
1680 "Use -style=\"{key: value, ...}\" to set specific\n"
1681 "parameters, e.g.:\n"
1682 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1683
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001684static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001685 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001686 return FormatStyle::LK_JavaScript;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001687 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001688 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001689}
1690
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001691FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1692 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001693 FormatStyle Style = getLLVMStyle();
1694 Style.Language = getLanguageByFileName(FileName);
1695 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001696 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1697 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001698 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001699 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001700
1701 if (StyleName.startswith("{")) {
1702 // Parse YAML/JSON style from the command line.
1703 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001704 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1705 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001706 }
1707 return Style;
1708 }
1709
1710 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001711 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001712 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1713 << " style\n";
1714 return Style;
1715 }
1716
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001717 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001718 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001719 SmallString<128> Path(FileName);
1720 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001721 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001722 Directory = llvm::sys::path::parent_path(Directory)) {
1723 if (!llvm::sys::fs::is_directory(Directory))
1724 continue;
1725 SmallString<128> ConfigFile(Directory);
1726
1727 llvm::sys::path::append(ConfigFile, ".clang-format");
1728 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1729 bool IsFile = false;
1730 // Ignore errors from is_regular_file: we only need to know if we can read
1731 // the file or not.
1732 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1733
1734 if (!IsFile) {
1735 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1736 ConfigFile = Directory;
1737 llvm::sys::path::append(ConfigFile, "_clang-format");
1738 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1739 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1740 }
1741
1742 if (IsFile) {
1743 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001744 if (llvm::error_code ec =
1745 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001746 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001747 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001748 }
1749 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001750 if (ec == llvm::errc::not_supported) {
1751 if (!UnsuitableConfigFiles.empty())
1752 UnsuitableConfigFiles.append(", ");
1753 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001754 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001755 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001756 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1757 << "\n";
1758 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001759 }
1760 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1761 return Style;
1762 }
1763 }
1764 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1765 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001766 if (!UnsuitableConfigFiles.empty()) {
1767 llvm::errs() << "Configuration file(s) do(es) not support "
1768 << getLanguageName(Style.Language) << ": "
1769 << UnsuitableConfigFiles << "\n";
1770 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001771 return Style;
1772}
1773
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001774} // namespace format
1775} // namespace clang