blob: f715ce2810c9efc5729a2dfa31c16d167cffba44 [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"
Edwin Vaned544aa72013-09-30 13:31:48 +000029#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "llvm/Support/YAMLTraits.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);
Daniel Jasper7052ce62014-01-19 09:04:08 +000042 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000043 }
44};
45
46template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
47 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
48 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
49 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
50 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
51 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
52 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
53 }
54};
55
56template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
57 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
58 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
59 IO.enumCase(Value, "false", FormatStyle::UT_Never);
60 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
61 IO.enumCase(Value, "true", FormatStyle::UT_Always);
62 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
63 }
64};
65
66template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
67 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
68 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
69 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
70 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
71 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000072 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000073 }
74};
75
Alexander Kornienkod6538332013-05-07 15:32:14 +000076template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000077struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000078 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079 FormatStyle::NamespaceIndentationKind &Value) {
80 IO.enumCase(Value, "None", FormatStyle::NI_None);
81 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
82 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000083 }
84};
85
86template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000087struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000088 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000089 FormatStyle::SpaceBeforeParensOptions &Value) {
90 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000091 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 FormatStyle::SBPO_ControlStatements);
93 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000094
95 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000096 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
97 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +000098 }
99};
100
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000101template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000102 static void mapping(IO &IO, FormatStyle &Style) {
103 // When reading, read the language first, we need it for getPredefinedStyle.
104 IO.mapOptional("Language", Style.Language);
105
Alexander Kornienko49149672013-05-10 11:56:10 +0000106 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000107 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000108 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000109 ArrayRef<StringRef> Styles(StylesArray);
110 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
111 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000112 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000113 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000114 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000115 IO.mapOptional("# BasedOnStyle", StyleName);
116 break;
117 }
118 }
119 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000120 StringRef BasedOnStyle;
121 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000122 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000123 FormatStyle::LanguageKind OldLanguage = Style.Language;
124 FormatStyle::LanguageKind Language =
125 ((FormatStyle *)IO.getContext())->Language;
126 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000127 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
128 return;
129 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000130 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000131 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000132 }
133
134 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000135 IO.mapOptional("ConstructorInitializerIndentWidth",
136 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000137 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000138 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000139 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
140 Style.AllowAllParametersOfDeclarationOnNextLine);
141 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
142 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000143 IO.mapOptional("AllowShortLoopsOnASingleLine",
144 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000145 IO.mapOptional("AllowShortFunctionsOnASingleLine",
146 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000147 IO.mapOptional("AlwaysBreakTemplateDeclarations",
148 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000149 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
150 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000151 IO.mapOptional("BreakBeforeBinaryOperators",
152 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000153 IO.mapOptional("BreakBeforeTernaryOperators",
154 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000155 IO.mapOptional("BreakConstructorInitializersBeforeComma",
156 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000157 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
158 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
159 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
160 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
161 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000162 IO.mapOptional("ExperimentalAutoDetectBinPacking",
163 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000164 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
165 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000166 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000167 IO.mapOptional("ObjCSpaceBeforeProtocolList",
168 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000169 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
170 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000171 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
172 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000173 IO.mapOptional("PenaltyBreakFirstLessLess",
174 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000175 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
176 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
177 Style.PenaltyReturnTypeOnItsOwnLine);
178 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
179 IO.mapOptional("SpacesBeforeTrailingComments",
180 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000181 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000182 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000183 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000184 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000185 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000186 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000187 IO.mapOptional("IndentFunctionDeclarationAfterType",
188 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000189 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000190 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000191 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000192 IO.mapOptional("SpacesInCStyleCastParentheses",
193 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000194 IO.mapOptional("SpacesInContainerLiterals",
195 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000196 IO.mapOptional("SpaceBeforeAssignmentOperators",
197 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000198 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000199 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000200
201 // For backward compatibility.
202 if (!IO.outputting()) {
203 IO.mapOptional("SpaceAfterControlStatementKeyword",
204 Style.SpaceBeforeParens);
205 }
206 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000207 }
208};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000209
210// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000211// IO.getContext() should contain a pointer to the FormatStyle structure, that
212// will be used to get default values for missing keys.
213// If the first element has no Language specified, it will be treated as the
214// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000215template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000216 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
217 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000218 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000219 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000220 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000221 if (Index >= Seq.size()) {
222 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000223 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000224 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000225 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000226 } else {
227 Template = *((const FormatStyle*)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000228 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000229 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000230 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000231 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000232 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000233 }
234};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235}
236}
237
Daniel Jasperf7935112012-12-03 18:12:45 +0000238namespace clang {
239namespace format {
240
Daniel Jasperf7935112012-12-03 18:12:45 +0000241FormatStyle getLLVMStyle() {
242 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000243 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000244 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000245 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000246 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000247 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000248 LLVMStyle.AllowShortFunctionsOnASingleLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000249 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000250 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000251 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000252 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000253 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000254 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000255 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000256 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
257 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000258 LLVMStyle.ColumnLimit = 80;
259 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000260 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000261 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000262 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000263 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000264 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000265 LLVMStyle.IndentFunctionDeclarationAfterType = false;
266 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000267 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000268 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000269 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000270 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000271 LLVMStyle.PointerBindsToType = false;
272 LLVMStyle.SpacesBeforeTrailingComments = 1;
273 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000274 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000275 LLVMStyle.SpacesInParentheses = false;
276 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000277 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000278 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000279 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000280 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000281 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000282 LLVMStyle.SpacesInAngles = false;
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000283 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000284
Daniel Jasper19a541e2013-12-19 16:45:34 +0000285 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000286 LLVMStyle.PenaltyBreakFirstLessLess = 120;
287 LLVMStyle.PenaltyBreakString = 1000;
288 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000289 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000290 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000291
Daniel Jasperf7935112012-12-03 18:12:45 +0000292 return LLVMStyle;
293}
294
295FormatStyle getGoogleStyle() {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000296 FormatStyle GoogleStyle = getLLVMStyle();
Daniel Jasperf7935112012-12-03 18:12:45 +0000297 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000298 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000299 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000300 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000301 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000302 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000303 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000304 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000305 GoogleStyle.DerivePointerBinding = true;
306 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000307 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Nico Webera6087752013-01-10 20:12:55 +0000308 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000309 GoogleStyle.PointerBindsToType = true;
310 GoogleStyle.SpacesBeforeTrailingComments = 2;
311 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000312
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000313 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000314 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000315
Daniel Jasperf7935112012-12-03 18:12:45 +0000316 return GoogleStyle;
317}
318
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000319FormatStyle getGoogleJSStyle() {
320 FormatStyle GoogleJSStyle = getGoogleStyle();
321 GoogleJSStyle.Language = FormatStyle::LK_JavaScript;
322 GoogleJSStyle.BreakBeforeTernaryOperators = false;
Daniel Jaspera55544a2014-01-20 14:10:30 +0000323 GoogleJSStyle.MaxEmptyLinesToKeep = 2;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000324 GoogleJSStyle.SpacesInContainerLiterals = false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000325 return GoogleJSStyle;
326}
327
Daniel Jasper7052ce62014-01-19 09:04:08 +0000328FormatStyle getGoogleProtoStyle() {
329 FormatStyle GoogleProtoStyle = getGoogleStyle();
330 GoogleProtoStyle.Language = FormatStyle::LK_Proto;
331 GoogleProtoStyle.AllowShortFunctionsOnASingleLine = false;
332 return GoogleProtoStyle;
333}
334
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000335FormatStyle getChromiumStyle() {
336 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000337 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000338 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000339 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000340 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000341 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000342 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000343 return ChromiumStyle;
344}
345
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000346FormatStyle getMozillaStyle() {
347 FormatStyle MozillaStyle = getLLVMStyle();
348 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
349 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
350 MozillaStyle.DerivePointerBinding = true;
351 MozillaStyle.IndentCaseLabels = true;
352 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
353 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
354 MozillaStyle.PointerBindsToType = true;
355 return MozillaStyle;
356}
357
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000358FormatStyle getWebKitStyle() {
359 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000360 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000361 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000362 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000363 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000364 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000365 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000366 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000367 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000368 Style.PointerBindsToType = true;
369 return Style;
370}
371
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000372FormatStyle getGNUStyle() {
373 FormatStyle Style = getLLVMStyle();
374 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000375 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000376 Style.BreakBeforeTernaryOperators = true;
377 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000378 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
379 return Style;
380}
381
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000382bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
383 FormatStyle *Style) {
384 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000385 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000386 } else if (Name.equals_lower("chromium")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000387 *Style = getChromiumStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000388 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000389 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000390 } else if (Name.equals_lower("google")) {
Daniel Jasper7052ce62014-01-19 09:04:08 +0000391 switch (Language) {
392 case FormatStyle::LK_JavaScript:
393 *Style = getGoogleJSStyle();
394 break;
395 case FormatStyle::LK_Proto:
396 *Style = getGoogleProtoStyle();
397 break;
398 default:
399 *Style = getGoogleStyle();
400 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000401 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000402 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000403 } else if (Name.equals_lower("gnu")) {
404 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000405 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000406 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000407 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000408
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000409 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000410 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000411}
412
413llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000414 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000415 FormatStyle::LanguageKind Language = Style->Language;
416 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000417 if (Text.trim().empty())
418 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000419
420 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000421 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000422 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
423 // values for the fields, keys for which are missing from the configuration.
424 // Mapping also uses the context to get the language to find the correct
425 // base style.
426 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000427 Input >> Styles;
428 if (Input.error())
429 return Input.error();
430
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000431 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000432 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000433 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000434 return llvm::make_error_code(llvm::errc::invalid_argument);
435 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000436 for (unsigned j = 0; j < i; ++j) {
437 if (Styles[i].Language == Styles[j].Language) {
438 DEBUG(llvm::dbgs()
439 << "Duplicate languages in the config file on positions " << j
440 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000441 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000442 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000443 }
444 }
445 // Look for a suitable configuration starting from the end, so we can
446 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000447 // configuration (which can only be at slot 0) after it.
448 for (int i = Styles.size() - 1; i >= 0; --i) {
449 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000450 Styles[i].Language == FormatStyle::LK_None) {
451 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000452 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000453 return llvm::make_error_code(llvm::errc::success);
454 }
455 }
456 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000457}
458
459std::string configurationAsText(const FormatStyle &Style) {
460 std::string Text;
461 llvm::raw_string_ostream Stream(Text);
462 llvm::yaml::Output Output(Stream);
463 // We use the same mapping method for input and output, so we need a non-const
464 // reference here.
465 FormatStyle NonConstStyle = Style;
466 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000467 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000468}
469
Craig Topperaf35e852013-06-30 22:29:28 +0000470namespace {
471
Daniel Jasperde0328a2013-08-16 11:20:30 +0000472class NoColumnLimitFormatter {
473public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000474 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000475
476 /// \brief Formats the line starting at \p State, simply keeping all of the
477 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000478 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000479 LineState State =
480 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000481 while (State.NextToken != NULL) {
482 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000483 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000484 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
485 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
486 }
487 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000488
Daniel Jasperde0328a2013-08-16 11:20:30 +0000489private:
490 ContinuationIndenter *Indenter;
491};
492
Daniel Jasper56f8b432013-11-06 23:12:09 +0000493class LineJoiner {
494public:
495 LineJoiner(const FormatStyle &Style) : Style(Style) {}
496
497 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
498 unsigned
499 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000500 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000501 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
502 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000503 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000504 if (TheLine->Last->Type == TT_LineComment)
505 return 0;
506
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000507 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
508 return 0;
509
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000510 unsigned Limit =
511 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000512 // If we already exceed the column limit, we set 'Limit' to 0. The different
513 // tryMerge..() functions can then decide whether to still do merging.
514 Limit = TheLine->Last->TotalLength > Limit
515 ? 0
516 : Limit - TheLine->Last->TotalLength;
517
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000518 if (I + 1 == E || I[1]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000519 return 0;
520
Daniel Jasper234379f2013-12-24 13:31:25 +0000521 if (TheLine->Last->Type == TT_FunctionLBrace &&
522 TheLine->First != TheLine->Last) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000523 return Style.AllowShortFunctionsOnASingleLine
524 ? tryMergeSimpleBlock(I, E, Limit)
525 : 0;
526 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000527 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000528 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000529 ? tryMergeSimpleBlock(I, E, Limit)
530 : 0;
531 }
532 if (I[1]->First->Type == TT_FunctionLBrace &&
533 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000534 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000535 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
536 return 0;
537 Limit -= 2;
538
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000539 unsigned MergedLines = 0;
540 if (Style.AllowShortFunctionsOnASingleLine) {
541 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
542 // If we managed to merge the block, count the function header, which is
543 // on a separate line.
544 if (MergedLines > 0)
545 ++MergedLines;
546 }
547 return MergedLines;
548 }
549 if (TheLine->First->is(tok::kw_if)) {
550 return Style.AllowShortIfStatementsOnASingleLine
551 ? tryMergeSimpleControlStatement(I, E, Limit)
552 : 0;
553 }
554 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
555 return Style.AllowShortLoopsOnASingleLine
556 ? tryMergeSimpleControlStatement(I, E, Limit)
557 : 0;
558 }
559 if (TheLine->InPPDirective &&
560 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000561 return tryMergeSimplePPDirective(I, E, Limit);
562 }
563 return 0;
564 }
565
566private:
567 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000568 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000569 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
570 unsigned Limit) {
571 if (Limit == 0)
572 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000573 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000574 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000575 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000576 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000577 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000578 return 0;
579 return 1;
580 }
581
582 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000583 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000584 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
585 if (Limit == 0)
586 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000587 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
588 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000589 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000590 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000591 if (I[1]->InPPDirective != (*I)->InPPDirective ||
592 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000593 return 0;
594 AnnotatedLine &Line = **I;
595 if (Line.Last->isNot(tok::r_paren))
596 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000597 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000598 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000599 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000600 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000601 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000602 return 0;
603 // Only inline simple if's (no nested if or else).
604 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000605 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000606 return 0;
607 return 1;
608 }
609
610 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000611 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000612 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
613 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000614 // First, check that the current line allows merging. This is the case if
615 // we're not in a control flow statement and the last token is an opening
616 // brace.
617 AnnotatedLine &Line = **I;
618 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
619 tok::kw_else, tok::kw_try, tok::kw_catch,
620 tok::kw_for,
621 // This gets rid of all ObjC @ keywords and methods.
622 tok::at, tok::minus, tok::plus))
623 return 0;
624
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000625 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000626 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
627 (Tok->getNextNonComment() == NULL ||
628 Tok->getNextNonComment()->is(tok::semi))) {
629 // We merge empty blocks even if the line exceeds the column limit.
630 Tok->SpacesRequiredBefore = 0;
631 Tok->CanBreakBefore = true;
632 return 1;
633 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
634 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000635 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000636 return 0;
637
638 if (!nextTwoLinesFitInto(I, Limit))
639 return 0;
640
641 // Second, check that the next line does not contain any braces - if it
642 // does, readability declines when putting it into a single line.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000643 if (I[1]->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000644 return 0;
645 do {
646 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
647 return 0;
648 Tok = Tok->Next;
649 } while (Tok != NULL);
650
651 // Last, check that the third line contains a single closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000652 Tok = I[2]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000653 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
654 Tok->MustBreakBefore)
655 return 0;
656
657 return 2;
658 }
659 return 0;
660 }
661
662 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
663 unsigned Limit) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000664 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000665 }
666
Daniel Jasper234379f2013-12-24 13:31:25 +0000667 bool containsMustBreak(const AnnotatedLine *Line) {
668 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
669 if (Tok->MustBreakBefore)
670 return true;
671 }
672 return false;
673 }
674
Daniel Jasper56f8b432013-11-06 23:12:09 +0000675 const FormatStyle &Style;
676};
677
Daniel Jasperf7935112012-12-03 18:12:45 +0000678class UnwrappedLineFormatter {
679public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000680 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000681 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000682 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000683 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
684 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000685
Daniel Jasper56f8b432013-11-06 23:12:09 +0000686 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000687 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000688 assert(!Lines.empty());
689 unsigned Penalty = 0;
690 std::vector<int> IndentForLevel;
691 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
692 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000693 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000694 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
695 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000696 I != E; ++I) {
697 const AnnotatedLine &TheLine = **I;
698 const FormatToken *FirstTok = TheLine.First;
699 int Offset = getIndentOffset(*FirstTok);
700
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000701 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000702 unsigned Indent;
703 if (TheLine.InPPDirective) {
704 Indent = TheLine.Level * Style.IndentWidth;
705 } else {
706 while (IndentForLevel.size() <= TheLine.Level)
707 IndentForLevel.push_back(-1);
708 IndentForLevel.resize(TheLine.Level + 1);
709 Indent = getIndent(IndentForLevel, TheLine.Level);
710 }
711 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000712 if (static_cast<int>(Indent) + Offset >= 0)
713 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000714
715 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000716 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000717 if (MergedLines > 0 && Style.ColumnLimit == 0) {
718 // Disallow line merging if there is a break at the start of one of the
719 // input lines.
720 for (unsigned i = 0; i < MergedLines; ++i) {
721 if (I[i + 1]->First->NewlinesBefore > 0)
722 MergedLines = 0;
723 }
724 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000725 if (!DryRun) {
726 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000727 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 }
729 }
730 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000731
Daniel Jasper9c199562013-11-28 15:58:55 +0000732 bool FixIndentation =
733 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000734 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000735 if (PreviousLine && PreviousLine->Affected && !DryRun) {
736 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000737 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
738 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
739 /*IndentLevel=*/0, /*Spaces=*/0,
740 /*TargetColumn=*/0);
741 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000742 } else if (TheLine.Type != LT_Invalid &&
743 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000744 if (FirstTok->WhitespaceRange.isValid()) {
745 if (!DryRun)
746 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
747 Indent, TheLine.InPPDirective);
748 } else {
749 Indent = LevelIndent = FirstTok->OriginalColumn;
750 }
751
752 // If everything fits on a single line, just put it there.
753 unsigned ColumnLimit = Style.ColumnLimit;
754 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000755 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000756 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
757 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
758 }
759
760 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
761 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
762 while (State.NextToken != NULL)
763 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
764 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000765 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000766 NoColumnLimitFormatter Formatter(Indenter);
767 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000768 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000769 } else {
770 Penalty += format(TheLine, Indent, DryRun);
771 }
772
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000773 if (!TheLine.InPPDirective)
774 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000775 } else if (TheLine.ChildrenAffected) {
776 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000777 } else {
778 // Format the first token if necessary, and notify the WhitespaceManager
779 // about the unchanged whitespace.
780 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
781 if (Tok == TheLine.First &&
782 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
783 unsigned LevelIndent = Tok->OriginalColumn;
784 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000785 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000786 if ((PreviousLine && PreviousLine->Affected) ||
787 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000788 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
789 TheLine.InPPDirective);
790 } else {
791 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
792 }
793 }
794
795 if (static_cast<int>(LevelIndent) - Offset >= 0)
796 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000797 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000798 IndentForLevel[TheLine.Level] = LevelIndent;
799 } else if (!DryRun) {
800 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
801 }
802 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000803 }
804 if (!DryRun) {
805 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
806 Tok->Finalized = true;
807 }
808 }
809 PreviousLine = *I;
810 }
811 return Penalty;
812 }
813
814private:
815 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000816 ///
817 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000818 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
819 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000820 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000821
Daniel Jasperacc33662013-02-08 08:22:00 +0000822 // If the ObjC method declaration does not fit on a line, we should format
823 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000824 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000825 State.Stack.back().BreakBeforeParameter = true;
826
Daniel Jasper4b866272013-02-01 11:00:45 +0000827 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000828 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000829 }
830
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000831 /// \brief An edge in the solution space from \c Previous->State to \c State,
832 /// inserting a newline dependent on the \c NewLine.
833 struct StateNode {
834 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000835 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000836 LineState State;
837 bool NewLine;
838 StateNode *Previous;
839 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000840
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000841 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
842 ///
843 /// In case of equal penalties, we want to prefer states that were inserted
844 /// first. During state generation we make sure that we insert states first
845 /// that break the line as late as possible.
846 typedef std::pair<unsigned, unsigned> OrderedPenalty;
847
848 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
849 /// \c State has the given \c OrderedPenalty.
850 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
851
852 /// \brief The BFS queue type.
853 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
854 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000855
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000856 /// \brief Get the offset of the line relatively to the level.
857 ///
858 /// For example, 'public:' labels in classes are offset by 1 or 2
859 /// characters to the left from their level.
860 int getIndentOffset(const FormatToken &RootToken) {
861 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
862 return Style.AccessModifierOffset;
863 return 0;
864 }
865
866 /// \brief Add a new line and the required indent before the first Token
867 /// of the \c UnwrappedLine if there was no structural parsing error.
868 void formatFirstToken(FormatToken &RootToken,
869 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
870 unsigned Indent, bool InPPDirective) {
871 unsigned Newlines =
872 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
873 // Remove empty lines before "}" where applicable.
874 if (RootToken.is(tok::r_brace) &&
875 (!RootToken.Next ||
876 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
877 Newlines = std::min(Newlines, 1u);
878 if (Newlines == 0 && !RootToken.IsFirst)
879 Newlines = 1;
880
881 // Insert extra new line before access specifiers.
882 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
883 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
884 ++Newlines;
885
886 // Remove empty lines after access specifiers.
887 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
888 Newlines = std::min(1u, Newlines);
889
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000890 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
891 Indent, InPPDirective &&
892 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000893 }
894
895 /// \brief Get the indent of \p Level from \p IndentForLevel.
896 ///
897 /// \p IndentForLevel must contain the indent for the level \c l
898 /// at \p IndentForLevel[l], or a value < 0 if the indent for
899 /// that level is unknown.
900 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
901 if (IndentForLevel[Level] != -1)
902 return IndentForLevel[Level];
903 if (Level == 0)
904 return 0;
905 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
906 }
907
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000908 void join(AnnotatedLine &A, const AnnotatedLine &B) {
909 assert(!A.Last->Next);
910 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000911 if (B.Affected)
912 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000913 A.Last->Next = B.First;
914 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000915 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000916 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
917 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
918 Tok->TotalLength += LengthA;
919 A.Last = Tok;
920 }
921 }
922
923 unsigned getColumnLimit(bool InPPDirective) const {
924 // In preprocessor directives reserve two chars for trailing " \"
925 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
926 }
927
Daniel Jasper4b866272013-02-01 11:00:45 +0000928 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000930 /// This implements a variant of Dijkstra's algorithm on the graph that spans
931 /// the solution space (\c LineStates are the nodes). The algorithm tries to
932 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000933 /// to a state where all tokens are placed. Returns the penalty.
934 ///
935 /// If \p DryRun is \c false, directly applies the changes.
936 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000937 std::set<LineState> Seen;
938
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000939 // Increasing count of \c StateNode items we have created. This is used to
940 // create a deterministic order independent of the container.
941 unsigned Count = 0;
942 QueueType Queue;
943
Daniel Jasper4b866272013-02-01 11:00:45 +0000944 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000945 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000946 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
947 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
948 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000949
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000950 unsigned Penalty = 0;
951
Daniel Jasper4b866272013-02-01 11:00:45 +0000952 // While not empty, take first element and follow edges.
953 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000954 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000955 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000956 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000957 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000958 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000959 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000960 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000961
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000962 // Cut off the analysis of certain solutions if the analysis gets too
963 // complex. See description of IgnoreStackForComparison.
964 if (Count > 10000)
965 Node->State.IgnoreStackForComparison = true;
966
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000967 if (!Seen.insert(Node->State).second)
968 // State already examined with lower penalty.
969 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000970
Manuel Klimek71814b42013-10-11 21:25:45 +0000971 FormatDecision LastFormat = Node->State.NextToken->Decision;
972 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000973 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +0000974 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000975 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +0000976 }
977
Manuel Klimek71814b42013-10-11 21:25:45 +0000978 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000979 // We were unable to find a solution, do nothing.
980 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +0000981 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000982 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +0000983 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000984
Daniel Jasper4b866272013-02-01 11:00:45 +0000985 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000986 if (!DryRun)
987 reconstructPath(InitialState, Queue.top().second);
988
Alexander Kornienko49149672013-05-10 11:56:10 +0000989 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
990 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000991
992 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000993 }
994
995 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000996 std::deque<StateNode *> Path;
997 // We do not need a break before the initial token.
998 while (Current->Previous) {
999 Path.push_front(Current);
1000 Current = Current->Previous;
1001 }
1002 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1003 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001004 unsigned Penalty = 0;
1005 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1006 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1007
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001008 DEBUG({
1009 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001010 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001011 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001012 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001013 }
1014 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001015 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001016 }
1017
Manuel Klimekaf491072013-02-13 10:54:19 +00001018 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001019 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001020 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001021 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001022 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001023 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001024 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001025 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001026 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001027 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001028
1029 StateNode *Node = new (Allocator.Allocate())
1030 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001031 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1032 return;
1033
Daniel Jasperde0328a2013-08-16 11:20:30 +00001034 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001035
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001036 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1037 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001038 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001039
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001040 /// \brief If the \p State's next token is an r_brace closing a nested block,
1041 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001042 ///
1043 /// Returns \c true if all children could be placed successfully and adapts
1044 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1045 /// creates changes using \c Whitespaces.
1046 ///
1047 /// The crucial idea here is that children always get formatted upon
1048 /// encountering the closing brace right after the nested block. Now, if we
1049 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1050 /// \c false), the entire block has to be kept on the same line (which is only
1051 /// possible if it fits on the line, only contains a single statement, etc.
1052 ///
1053 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1054 /// break after the "{", format all lines with correct indentation and the put
1055 /// the closing "}" on yet another new line.
1056 ///
1057 /// This enables us to keep the simple structure of the
1058 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1059 /// break or don't break.
1060 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1061 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001062 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001063 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1064 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1065 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001066 // The previous token does not open a block. Nothing to do. We don't
1067 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001068 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001069
1070 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001071 int AdditionalIndent = State.Stack.back().Indent -
1072 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001073 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1074 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001075 return true;
1076 }
1077
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001078 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001079 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001080 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001081
1082 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001083 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001084 return false;
1085
1086 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001087 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001088 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001089 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001090 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001091 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001092 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001093
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001094 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001095 return true;
1096 }
1097
Daniel Jasperde0328a2013-08-16 11:20:30 +00001098 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001099 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001101 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001102
1103 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001104};
1105
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001106class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001107public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001108 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001109 encoding::Encoding Encoding)
Alexander Kornienko393e3082013-11-13 14:04:17 +00001110 : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
Manuel Klimek31c85922013-08-29 15:21:40 +00001111 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1112 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001113 Lex.SetKeepWhitespaceMode(true);
1114 }
1115
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001116 ArrayRef<FormatToken *> lex() {
1117 assert(Tokens.empty());
1118 do {
1119 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001120 tryMergePreviousTokens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001121 } while (Tokens.back()->Tok.isNot(tok::eof));
1122 return Tokens;
1123 }
1124
1125 IdentifierTable &getIdentTable() { return IdentTable; }
1126
1127private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001128 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001129 if (tryMerge_TMacro())
1130 return;
1131
1132 if (Style.Language == FormatStyle::LK_JavaScript) {
1133 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1134 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1135 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1136 tok::greaterequal };
1137 // FIXME: We probably need to change token type to mimic operator with the
1138 // correct priority.
1139 if (tryMergeTokens(JSIdentity))
1140 return;
1141 if (tryMergeTokens(JSNotIdentity))
1142 return;
1143 if (tryMergeTokens(JSShiftEqual))
1144 return;
1145 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001146 }
1147
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001148 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1149 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001150 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001151
1152 SmallVectorImpl<FormatToken *>::const_iterator First =
1153 Tokens.end() - Kinds.size();
1154 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001155 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001156 unsigned AddLength = 0;
1157 for (unsigned i = 1; i < Kinds.size(); ++i) {
1158 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1159 First[i]->WhitespaceRange.getEnd())
1160 return false;
1161 AddLength += First[i]->TokenText.size();
1162 }
1163 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1164 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1165 First[0]->TokenText.size() + AddLength);
1166 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001167 return true;
1168 }
1169
1170 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001171 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001172 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001173 FormatToken *Last = Tokens.back();
1174 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001175 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001176
1177 FormatToken *String = Tokens[Tokens.size() - 2];
1178 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001179 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001180
1181 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001182 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001183
1184 FormatToken *Macro = Tokens[Tokens.size() - 4];
1185 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001186 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001187
1188 const char *Start = Macro->TokenText.data();
1189 const char *End = Last->TokenText.data() + Last->TokenText.size();
1190 String->TokenText = StringRef(Start, End - Start);
1191 String->IsFirst = Macro->IsFirst;
1192 String->LastNewlineOffset = Macro->LastNewlineOffset;
1193 String->WhitespaceRange = Macro->WhitespaceRange;
1194 String->OriginalColumn = Macro->OriginalColumn;
1195 String->ColumnWidth = encoding::columnWidthWithTabs(
1196 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1197
1198 Tokens.pop_back();
1199 Tokens.pop_back();
1200 Tokens.pop_back();
1201 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001202 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001203 }
1204
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001205 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001206 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001207 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001208 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001209 Token Greater = FormatTok->Tok;
1210 FormatTok = new (Allocator.Allocate()) FormatToken;
1211 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001212 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001213 FormatTok->Tok.getLocation().getLocWithOffset(1);
1214 FormatTok->WhitespaceRange =
1215 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001216 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001217 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001218 GreaterStashed = false;
1219 return FormatTok;
1220 }
1221
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001222 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001223 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001224 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001225 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001226 FormatTok->IsFirst = IsFirstToken;
1227 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228
1229 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001230 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001231 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001232 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1233 switch (FormatTok->TokenText[i]) {
1234 case '\n':
1235 ++FormatTok->NewlinesBefore;
1236 // FIXME: This is technically incorrect, as it could also
1237 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001238 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1239 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1240 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001241 FormatTok->HasUnescapedNewline = true;
1242 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1243 Column = 0;
1244 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001245 case '\r':
1246 case '\f':
1247 case '\v':
1248 Column = 0;
1249 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001250 case ' ':
1251 ++Column;
1252 break;
1253 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001254 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001255 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001256 case '\\':
1257 ++Column;
1258 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1259 FormatTok->TokenText[i + 1] != '\n'))
1260 FormatTok->Type = TT_ImplicitStringLiteral;
1261 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001262 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001263 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001264 ++Column;
1265 break;
1266 }
1267 }
1268
Daniel Jasper877615c2013-10-11 19:45:02 +00001269 if (FormatTok->Type == TT_ImplicitStringLiteral)
1270 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001271 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001272
Daniel Jasper8369aa52013-07-16 20:28:33 +00001273 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001274 }
Manuel Klimekef920692013-01-07 07:56:50 +00001275
Manuel Klimek1abf7892013-01-04 23:34:14 +00001276 // In case the token starts with escaped newlines, we want to
1277 // take them into account as whitespace - this pattern is quite frequent
1278 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001279 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001280 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1281 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001282 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001283 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001284 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001285 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001286 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001287
1288 FormatTok->WhitespaceRange = SourceRange(
1289 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1290
Manuel Klimek31c85922013-08-29 15:21:40 +00001291 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001292
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001293 TrailingWhitespace = 0;
1294 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001295 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001296 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001297 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001298 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001299 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001300 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001301 FormatTok->Tok.setIdentifierInfo(&Info);
1302 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001303 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001304 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001305 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001306 GreaterStashed = true;
1307 }
1308
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001309 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001310
Alexander Kornienko39856b72013-09-10 09:38:25 +00001311 StringRef Text = FormatTok->TokenText;
1312 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001313 if (FirstNewlinePos == StringRef::npos) {
1314 // FIXME: ColumnWidth actually depends on the start column, we need to
1315 // take this into account when the token is moved.
1316 FormatTok->ColumnWidth =
1317 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1318 Column += FormatTok->ColumnWidth;
1319 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001320 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001321 // FIXME: ColumnWidth actually depends on the start column, we need to
1322 // take this into account when the token is moved.
1323 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1324 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1325
Alexander Kornienko39856b72013-09-10 09:38:25 +00001326 // The last line of the token always starts in column 0.
1327 // Thus, the length can be precomputed even in the presence of tabs.
1328 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1329 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1330 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001331 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001332 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001333
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001334 return FormatTok;
1335 }
1336
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001337 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001338 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001339 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001340 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001341 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001342 Lexer &Lex;
1343 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001344 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001345 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001346 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001347 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1348 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349
Daniel Jasper8369aa52013-07-16 20:28:33 +00001350 void readRawToken(FormatToken &Tok) {
1351 Lex.LexFromRawLexer(Tok.Tok);
1352 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1353 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001354 // For formatting, treat unterminated string literals like normal string
1355 // literals.
1356 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1357 Tok.TokenText[0] == '"') {
1358 Tok.Tok.setKind(tok::string_literal);
1359 Tok.IsUnterminatedLiteral = true;
1360 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001361 }
1362};
1363
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001364static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1365 switch (Language) {
1366 case FormatStyle::LK_Cpp:
1367 return "C++";
1368 case FormatStyle::LK_JavaScript:
1369 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001370 case FormatStyle::LK_Proto:
1371 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001372 default:
1373 return "Unknown";
1374 }
1375}
1376
Daniel Jasperf7935112012-12-03 18:12:45 +00001377class Formatter : public UnwrappedLineConsumer {
1378public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001379 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001380 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001381 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001382 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001383 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001384 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001385 DEBUG(llvm::dbgs() << "File encoding: "
1386 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1387 : "unknown")
1388 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001389 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1390 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001391 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001392
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001393 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001394 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001395 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001396
1397 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001398 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001399 assert(UnwrappedLines.rbegin()->empty());
1400 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1401 ++Run) {
1402 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1403 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1404 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1405 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1406 }
1407 tooling::Replacements RunResult =
1408 format(AnnotatedLines, StructuralError, Tokens);
1409 DEBUG({
1410 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1411 for (tooling::Replacements::iterator I = RunResult.begin(),
1412 E = RunResult.end();
1413 I != E; ++I) {
1414 llvm::dbgs() << I->toString() << "\n";
1415 }
1416 });
1417 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1418 delete AnnotatedLines[i];
1419 }
1420 Result.insert(RunResult.begin(), RunResult.end());
1421 Whitespaces.reset();
1422 }
1423 return Result;
1424 }
1425
1426 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1427 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001428 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001429 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001430 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001431 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001432 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001433 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001434 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001435 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001436 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001437
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001438 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001439 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1440 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001441 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001442 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001443 return Whitespaces.generateReplacements();
1444 }
1445
1446private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001447 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001448 // Returns \c true if at least one line between I and E or one of their
1449 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001450 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1451 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1452 bool SomeLineAffected = false;
Daniel Jasper38c82402013-11-29 09:27:43 +00001453 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper5500f612013-11-25 11:08:59 +00001454 while (I != E) {
1455 AnnotatedLine *Line = *I;
1456 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1457
1458 // If a line is part of a preprocessor directive, it needs to be formatted
1459 // if any token within the directive is affected.
1460 if (Line->InPPDirective) {
1461 FormatToken *Last = Line->Last;
1462 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1463 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1464 Last = (*PPEnd)->Last;
1465 ++PPEnd;
1466 }
1467
1468 if (affectsTokenRange(*Line->First, *Last,
1469 /*IncludeLeadingNewlines=*/false)) {
1470 SomeLineAffected = true;
1471 markAllAsAffected(I, PPEnd);
1472 }
1473 I = PPEnd;
1474 continue;
1475 }
1476
Daniel Jasper38c82402013-11-29 09:27:43 +00001477 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001478 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001479
Daniel Jasper38c82402013-11-29 09:27:43 +00001480 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001481 ++I;
1482 }
1483 return SomeLineAffected;
1484 }
1485
Daniel Jasper9c199562013-11-28 15:58:55 +00001486 // Determines whether 'Line' is affected by the SourceRanges given as input.
1487 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001488 bool nonPPLineAffected(AnnotatedLine *Line,
1489 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001490 bool SomeLineAffected = false;
1491 Line->ChildrenAffected =
1492 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1493 if (Line->ChildrenAffected)
1494 SomeLineAffected = true;
1495
1496 // Stores whether one of the line's tokens is directly affected.
1497 bool SomeTokenAffected = false;
1498 // Stores whether we need to look at the leading newlines of the next token
1499 // in order to determine whether it was affected.
1500 bool IncludeLeadingNewlines = false;
1501
1502 // Stores whether the first child line of any of this line's tokens is
1503 // affected.
1504 bool SomeFirstChildAffected = false;
1505
1506 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1507 // Determine whether 'Tok' was affected.
1508 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1509 SomeTokenAffected = true;
1510
1511 // Determine whether the first child of 'Tok' was affected.
1512 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1513 SomeFirstChildAffected = true;
1514
1515 IncludeLeadingNewlines = Tok->Children.empty();
1516 }
1517
1518 // Was this line moved, i.e. has it previously been on the same line as an
1519 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001520 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1521 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001522
Daniel Jasper38c82402013-11-29 09:27:43 +00001523 bool IsContinuedComment = Line->First->is(tok::comment) &&
1524 Line->First->Next == NULL &&
1525 Line->First->NewlinesBefore < 2 && PreviousLine &&
Daniel Jasper0e81f1a2013-12-02 09:19:27 +00001526 PreviousLine->Affected &&
Daniel Jasper38c82402013-11-29 09:27:43 +00001527 PreviousLine->Last->is(tok::comment);
1528
1529 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1530 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001531 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001532 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001533 }
1534 return SomeLineAffected;
1535 }
1536
Daniel Jasper5500f612013-11-25 11:08:59 +00001537 // Marks all lines between I and E as well as all their children as affected.
1538 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1539 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1540 while (I != E) {
1541 (*I)->Affected = true;
1542 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1543 ++I;
1544 }
1545 }
1546
1547 // Returns true if the range from 'First' to 'Last' intersects with one of the
1548 // input ranges.
1549 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1550 bool IncludeLeadingNewlines) {
1551 SourceLocation Start = First.WhitespaceRange.getBegin();
1552 if (!IncludeLeadingNewlines)
1553 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001554 SourceLocation End = Last.getStartOfNonWhitespace();
1555 if (Last.TokenText.size() > 0)
1556 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001557 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1558 return affectsCharSourceRange(Range);
1559 }
1560
1561 // Returns true if one of the input ranges intersect the leading empty lines
1562 // before 'Tok'.
1563 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1564 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1565 Tok.WhitespaceRange.getBegin(),
1566 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1567 return affectsCharSourceRange(EmptyLineRange);
1568 }
1569
1570 // Returns true if 'Range' intersects with one of the input ranges.
1571 bool affectsCharSourceRange(const CharSourceRange &Range) {
1572 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1573 E = Ranges.end();
1574 I != E; ++I) {
1575 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1576 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1577 return true;
1578 }
1579 return false;
1580 }
1581
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001582 static bool inputUsesCRLF(StringRef Text) {
1583 return Text.count('\r') * 2 > Text.count('\n');
1584 }
1585
Manuel Klimek71814b42013-10-11 21:25:45 +00001586 void
1587 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001588 unsigned CountBoundToVariable = 0;
1589 unsigned CountBoundToType = 0;
1590 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001591 bool HasBinPackedFunction = false;
1592 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001593 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001594 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001595 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001596 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001597 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001598 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001599 bool SpacesBefore =
1600 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1601 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1602 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001603 if (SpacesBefore && !SpacesAfter)
1604 ++CountBoundToVariable;
1605 else if (!SpacesBefore && SpacesAfter)
1606 ++CountBoundToType;
1607 }
1608
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001609 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1610 if (Tok->is(tok::coloncolon) &&
1611 Tok->Previous->Type == TT_TemplateOpener)
1612 HasCpp03IncompatibleFormat = true;
1613 if (Tok->Type == TT_TemplateCloser &&
1614 Tok->Previous->Type == TT_TemplateCloser)
1615 HasCpp03IncompatibleFormat = true;
1616 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001617
1618 if (Tok->PackingKind == PPK_BinPacked)
1619 HasBinPackedFunction = true;
1620 if (Tok->PackingKind == PPK_OnePerLine)
1621 HasOnePerLineFunction = true;
1622
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001623 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001624 }
1625 }
1626 if (Style.DerivePointerBinding) {
1627 if (CountBoundToType > CountBoundToVariable)
1628 Style.PointerBindsToType = true;
1629 else if (CountBoundToType < CountBoundToVariable)
1630 Style.PointerBindsToType = false;
1631 }
1632 if (Style.Standard == FormatStyle::LS_Auto) {
1633 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1634 : FormatStyle::LS_Cpp03;
1635 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001636 BinPackInconclusiveFunctions =
1637 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001638 }
1639
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001640 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001641 assert(!UnwrappedLines.empty());
1642 UnwrappedLines.back().push_back(TheLine);
1643 }
1644
1645 virtual void finishRun() {
1646 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001647 }
1648
1649 FormatStyle Style;
1650 Lexer &Lex;
1651 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001652 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001653 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001654 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001655
1656 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001657 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001658};
1659
Craig Topperaf35e852013-06-30 22:29:28 +00001660} // end anonymous namespace
1661
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001662tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1663 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001664 std::vector<CharSourceRange> Ranges) {
1665 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001666 return formatter.format();
1667}
1668
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001669tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1670 std::vector<tooling::Range> Ranges,
1671 StringRef FileName) {
1672 FileManager Files((FileSystemOptions()));
1673 DiagnosticsEngine Diagnostics(
1674 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1675 new DiagnosticOptions);
1676 SourceManager SourceMgr(Diagnostics, Files);
1677 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1678 const clang::FileEntry *Entry =
1679 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1680 SourceMgr.overrideFileContents(Entry, Buf);
1681 FileID ID =
1682 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001683 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1684 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001685 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1686 std::vector<CharSourceRange> CharRanges;
1687 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1688 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1689 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1690 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1691 }
1692 return reformat(Style, Lex, SourceMgr, CharRanges);
1693}
1694
Alexander Kornienko1e808872013-06-28 12:51:24 +00001695LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001696 LangOptions LangOpts;
1697 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001698 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001699 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001700 LangOpts.Bool = 1;
1701 LangOpts.ObjC1 = 1;
1702 LangOpts.ObjC2 = 1;
1703 return LangOpts;
1704}
1705
Edwin Vaned544aa72013-09-30 13:31:48 +00001706const char *StyleOptionHelpDescription =
1707 "Coding style, currently supports:\n"
1708 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1709 "Use -style=file to load style configuration from\n"
1710 ".clang-format file located in one of the parent\n"
1711 "directories of the source file (or current\n"
1712 "directory for stdin).\n"
1713 "Use -style=\"{key: value, ...}\" to set specific\n"
1714 "parameters, e.g.:\n"
1715 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1716
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001717static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001718 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001719 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001720 } else if (FileName.endswith_lower(".proto") ||
1721 FileName.endswith_lower(".protodevel")) {
1722 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001723 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001724 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001725}
1726
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001727FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1728 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001729 FormatStyle Style = getLLVMStyle();
1730 Style.Language = getLanguageByFileName(FileName);
1731 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001732 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1733 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001734 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001735 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001736
1737 if (StyleName.startswith("{")) {
1738 // Parse YAML/JSON style from the command line.
1739 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001740 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1741 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001742 }
1743 return Style;
1744 }
1745
1746 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001747 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001748 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1749 << " style\n";
1750 return Style;
1751 }
1752
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001753 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001754 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001755 SmallString<128> Path(FileName);
1756 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001757 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001758 Directory = llvm::sys::path::parent_path(Directory)) {
1759 if (!llvm::sys::fs::is_directory(Directory))
1760 continue;
1761 SmallString<128> ConfigFile(Directory);
1762
1763 llvm::sys::path::append(ConfigFile, ".clang-format");
1764 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1765 bool IsFile = false;
1766 // Ignore errors from is_regular_file: we only need to know if we can read
1767 // the file or not.
1768 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1769
1770 if (!IsFile) {
1771 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1772 ConfigFile = Directory;
1773 llvm::sys::path::append(ConfigFile, "_clang-format");
1774 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1775 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1776 }
1777
1778 if (IsFile) {
1779 OwningPtr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001780 if (llvm::error_code ec =
1781 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001782 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001783 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001784 }
1785 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001786 if (ec == llvm::errc::not_supported) {
1787 if (!UnsuitableConfigFiles.empty())
1788 UnsuitableConfigFiles.append(", ");
1789 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001790 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001791 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001792 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1793 << "\n";
1794 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001795 }
1796 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1797 return Style;
1798 }
1799 }
1800 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1801 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001802 if (!UnsuitableConfigFiles.empty()) {
1803 llvm::errs() << "Configuration file(s) do(es) not support "
1804 << getLanguageName(Style.Language) << ": "
1805 << UnsuitableConfigFiles << "\n";
1806 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001807 return Style;
1808}
1809
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001810} // namespace format
1811} // namespace clang