blob: 5275f9f0803f85e529a3006450b5d3e1bf075cac [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
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000018#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000020#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000021#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000022#include "clang/Basic/DiagnosticOptions.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
Chandler Carruth10346662014-04-22 03:17:02 +000034#define DEBUG_TYPE "format-formatter"
35
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000036using clang::format::FormatStyle;
37
Daniel Jaspere1e43192014-04-01 12:55:11 +000038LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
39
Alexander Kornienkod6538332013-05-07 15:32:14 +000040namespace llvm {
41namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000042template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
43 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
44 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000045 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000047 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000048 }
49};
50
51template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
52 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
53 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
55 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
57 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
58 }
59};
60
61template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
62 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
63 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
64 IO.enumCase(Value, "false", FormatStyle::UT_Never);
65 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
66 IO.enumCase(Value, "true", FormatStyle::UT_Always);
67 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
68 }
69};
70
Daniel Jasperd74cf402014-04-08 12:46:38 +000071template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
72 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
73 IO.enumCase(Value, "None", FormatStyle::SFS_None);
74 IO.enumCase(Value, "false", FormatStyle::SFS_None);
75 IO.enumCase(Value, "All", FormatStyle::SFS_All);
76 IO.enumCase(Value, "true", FormatStyle::SFS_All);
77 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000078 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000079 }
80};
81
Daniel Jasperac043c92014-09-15 11:11:00 +000082template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
83 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
84 IO.enumCase(Value, "All", FormatStyle::BOS_All);
85 IO.enumCase(Value, "true", FormatStyle::BOS_All);
86 IO.enumCase(Value, "None", FormatStyle::BOS_None);
87 IO.enumCase(Value, "false", FormatStyle::BOS_None);
88 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
89 }
90};
91
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
93 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
94 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
95 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
96 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
97 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000098 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000099 }
100};
101
Alexander Kornienkod6538332013-05-07 15:32:14 +0000102template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000104 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 FormatStyle::NamespaceIndentationKind &Value) {
106 IO.enumCase(Value, "None", FormatStyle::NI_None);
107 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
108 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000109 }
110};
111
Jacques Pienaarfc275112015-02-18 23:48:37 +0000112template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Alp Toker958027b2014-07-14 19:42:55 +0000118 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000126 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000129 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000132
133 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000136 }
137};
138
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
143
Alexander Kornienko49149672013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000145 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
146 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000160 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000168 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000169 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000174 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper3219e432014-12-02 13:24:51 +0000175 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000176 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000177 IO.mapOptional("AlignConsecutiveAssignments",
178 Style.AlignConsecutiveAssignments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000179 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
180 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000181 IO.mapOptional("AllowShortBlocksOnASingleLine",
182 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000183 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
184 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
186 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000187 IO.mapOptional("AllowShortLoopsOnASingleLine",
188 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000189 IO.mapOptional("AllowShortFunctionsOnASingleLine",
190 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000191 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
192 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000193 IO.mapOptional("AlwaysBreakTemplateDeclarations",
194 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000195 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
196 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000197 IO.mapOptional("BreakBeforeBinaryOperators",
198 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000199 IO.mapOptional("BreakBeforeTernaryOperators",
200 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000201 IO.mapOptional("BreakConstructorInitializersBeforeComma",
202 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000204 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000205 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
206 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
207 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000208 IO.mapOptional("ConstructorInitializerIndentWidth",
209 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000210 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000211 IO.mapOptional("ExperimentalAutoDetectBinPacking",
212 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000214 IO.mapOptional("IndentWrappedFunctionNames",
215 Style.IndentWrappedFunctionNames);
216 IO.mapOptional("IndentFunctionDeclarationAfterType",
217 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000218 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000219 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
220 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000221 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000222 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000223 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000224 IO.mapOptional("ObjCSpaceBeforeProtocolList",
225 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000226 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
227 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000228 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
229 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000230 IO.mapOptional("PenaltyBreakFirstLessLess",
231 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000232 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
233 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
234 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000235 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000236 IO.mapOptional("SpacesBeforeTrailingComments",
237 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000238 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000239 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000240 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000241 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000242 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000243 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000244 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000245 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000246 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000247 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000248 IO.mapOptional("SpacesInCStyleCastParentheses",
249 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000250 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000251 IO.mapOptional("SpacesInContainerLiterals",
252 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000253 IO.mapOptional("SpaceBeforeAssignmentOperators",
254 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000255 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000256 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000257 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000258
259 // For backward compatibility.
260 if (!IO.outputting()) {
261 IO.mapOptional("SpaceAfterControlStatementKeyword",
262 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000263 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
264 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000265 }
266 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000267 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000268 }
269};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000270
271// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000272// IO.getContext() should contain a pointer to the FormatStyle structure, that
273// will be used to get default values for missing keys.
274// If the first element has no Language specified, it will be treated as the
275// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000276template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000277 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
278 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000279 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000280 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000281 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000282 if (Index >= Seq.size()) {
283 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000284 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000285 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000286 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000287 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000288 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000289 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000290 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000291 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000292 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000293 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000294 }
295};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000296}
297}
Alexander Kornienkod6538332013-05-07 15:32:14 +0000298
Daniel Jasperf7935112012-12-03 18:12:45 +0000299namespace clang {
300namespace format {
301
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000302const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000303 static ParseErrorCategory C;
304 return C;
305}
306std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000307 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000308}
309
310const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
311 return "clang-format.parse_error";
312}
313
314std::string ParseErrorCategory::message(int EV) const {
315 switch (static_cast<ParseError>(EV)) {
316 case ParseError::Success:
317 return "Success";
318 case ParseError::Error:
319 return "Invalid argument";
320 case ParseError::Unsuitable:
321 return "Unsuitable";
322 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000323 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000324}
325
Daniel Jasperf7935112012-12-03 18:12:45 +0000326FormatStyle getLLVMStyle() {
327 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000328 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000329 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000330 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000331 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000332 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000333 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000334 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000335 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000336 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000337 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000338 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000339 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000340 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000341 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000342 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000343 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000344 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000345 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000346 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000347 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000348 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
349 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000350 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000351 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000352 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000353 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000354 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000355 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000356 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000357 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000358 LLVMStyle.ForEachMacros.push_back("foreach");
359 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
360 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000361 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000362 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000363 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000364 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000365 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000366 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000367 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000368 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000369 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000370 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000371 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000372 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000373 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000374 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000375 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000376 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000377 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000378 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000379 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000380 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000381 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000382 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000383 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000384
Daniel Jasper19a541e2013-12-19 16:45:34 +0000385 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000386 LLVMStyle.PenaltyBreakFirstLessLess = 120;
387 LLVMStyle.PenaltyBreakString = 1000;
388 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000389 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000390 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000391
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000392 LLVMStyle.DisableFormat = false;
393
Daniel Jasperf7935112012-12-03 18:12:45 +0000394 return LLVMStyle;
395}
396
Nico Weber514ecc82014-02-02 20:50:45 +0000397FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000398 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000399 GoogleStyle.Language = Language;
400
Daniel Jasperf7935112012-12-03 18:12:45 +0000401 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000402 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000403 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000404 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000405 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000406 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000407 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000408 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000409 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000410 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000411 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000412 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000413 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000414 GoogleStyle.SpacesBeforeTrailingComments = 2;
415 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000416
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000417 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000418 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000419
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000420 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000421 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000422 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000423 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000424 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000425 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000426 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000427 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
428 GoogleStyle.ColumnLimit = 100;
429 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000430 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000431 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000432 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000433 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000434 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000435 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000436 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000437 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000438 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000439 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000440 }
441
Daniel Jasperf7935112012-12-03 18:12:45 +0000442 return GoogleStyle;
443}
444
Nico Weber514ecc82014-02-02 20:50:45 +0000445FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
446 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000447 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000448 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber450425c2014-11-26 16:43:18 +0000449 ChromiumStyle.IndentWidth = 4;
450 ChromiumStyle.ContinuationIndentWidth = 8;
451 } else {
452 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
453 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
454 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
455 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
456 ChromiumStyle.BinPackParameters = false;
457 ChromiumStyle.DerivePointerAlignment = false;
458 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000459 return ChromiumStyle;
460}
461
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000462FormatStyle getMozillaStyle() {
463 FormatStyle MozillaStyle = getLLVMStyle();
464 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000465 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000466 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000467 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000468 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000469 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000470 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
471 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000472 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000473 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000474 return MozillaStyle;
475}
476
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000477FormatStyle getWebKitStyle() {
478 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000479 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000480 Style.AlignAfterOpenBracket = false;
Daniel Jasper3219e432014-12-02 13:24:51 +0000481 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000482 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000483 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000484 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000485 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000486 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000487 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000488 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000489 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000490 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000491 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000492 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000493 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000494 return Style;
495}
496
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000497FormatStyle getGNUStyle() {
498 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000499 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000500 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000501 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000502 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000503 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000504 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000505 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000506 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000507 return Style;
508}
509
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000510FormatStyle getNoStyle() {
511 FormatStyle NoStyle = getLLVMStyle();
512 NoStyle.DisableFormat = true;
513 return NoStyle;
514}
515
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000516bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
517 FormatStyle *Style) {
518 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000519 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000520 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000521 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000522 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000523 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000524 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000525 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000526 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000527 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000528 } else if (Name.equals_lower("gnu")) {
529 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000530 } else if (Name.equals_lower("none")) {
531 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000533 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000534 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000535
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000536 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000537 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000538}
539
Rafael Espindolac0809172014-06-12 14:02:15 +0000540std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000541 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 FormatStyle::LanguageKind Language = Style->Language;
543 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000544 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000545 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000546
547 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000548 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000549 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
550 // values for the fields, keys for which are missing from the configuration.
551 // Mapping also uses the context to get the language to find the correct
552 // base style.
553 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000554 Input >> Styles;
555 if (Input.error())
556 return Input.error();
557
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000559 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000560 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000561 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000562 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000563 for (unsigned j = 0; j < i; ++j) {
564 if (Styles[i].Language == Styles[j].Language) {
565 DEBUG(llvm::dbgs()
566 << "Duplicate languages in the config file on positions " << j
567 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000568 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000569 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000570 }
571 }
572 // Look for a suitable configuration starting from the end, so we can
573 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000574 // configuration (which can only be at slot 0) after it.
575 for (int i = Styles.size() - 1; i >= 0; --i) {
576 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000577 Styles[i].Language == FormatStyle::LK_None) {
578 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000579 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000580 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000581 }
582 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000583 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000584}
585
586std::string configurationAsText(const FormatStyle &Style) {
587 std::string Text;
588 llvm::raw_string_ostream Stream(Text);
589 llvm::yaml::Output Output(Stream);
590 // We use the same mapping method for input and output, so we need a non-const
591 // reference here.
592 FormatStyle NonConstStyle = Style;
593 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000594 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000595}
596
Craig Topperaf35e852013-06-30 22:29:28 +0000597namespace {
598
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000599class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000600public:
Daniel Jasper23376252014-09-09 14:37:39 +0000601 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000602 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +0000603 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Jacques Pienaarfc275112015-02-18 23:48:37 +0000604 LessStashed(false), Column(0), TrailingWhitespace(0),
605 SourceMgr(SourceMgr), ID(ID), Style(Style),
606 IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
607 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +0000608 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
609 getFormattingLangOpts(Style)));
610 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +0000611
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000612 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +0000613 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
614 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000615 }
616
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000617 ArrayRef<FormatToken *> lex() {
618 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +0000619 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000620 do {
621 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000622 tryMergePreviousTokens();
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000623 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
Manuel Klimek68b03042014-04-14 09:14:11 +0000624 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000625 } while (Tokens.back()->Tok.isNot(tok::eof));
626 return Tokens;
627 }
628
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000629 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000630
631private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000632 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000633 if (tryMerge_TMacro())
634 return;
Manuel Klimek68b03042014-04-14 09:14:11 +0000635 if (tryMergeConflictMarkers())
636 return;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000637 if (tryMergeLessLess())
638 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000639
640 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000641 if (tryMergeJSRegexLiteral())
642 return;
Daniel Jasper23376252014-09-09 14:37:39 +0000643 if (tryMergeEscapeSequence())
644 return;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000645 if (tryMergeTemplateString())
646 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000647
Benjamin Kramer28b45ce2015-03-08 16:06:46 +0000648 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
649 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
650 tok::equal};
651 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
652 tok::greaterequal};
653 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
Manuel Klimek79e06082015-05-21 12:23:34 +0000654 // FIXME: Investigate what token type gives the correct operator priority.
655 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000656 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000657 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000658 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000659 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000660 return;
Manuel Klimek79e06082015-05-21 12:23:34 +0000661 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
Daniel Jasper78214392014-05-19 07:27:02 +0000662 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000663 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000664 }
665
Jacques Pienaarfc275112015-02-18 23:48:37 +0000666 bool tryMergeLessLess() {
667 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000668 if (Tokens.size() < 3)
669 return false;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000670
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000671 bool FourthTokenIsLess = false;
672 if (Tokens.size() > 3)
673 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000674
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000675 auto First = Tokens.end() - 3;
676 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
677 First[0]->isNot(tok::less) || FourthTokenIsLess)
Jacques Pienaarfc275112015-02-18 23:48:37 +0000678 return false;
679
680 // Only merge if there currently is no whitespace between the two "<".
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000681 if (First[1]->WhitespaceRange.getBegin() !=
682 First[1]->WhitespaceRange.getEnd())
Jacques Pienaarfc275112015-02-18 23:48:37 +0000683 return false;
684
Jacques Pienaar68a7dbf2015-02-20 21:09:01 +0000685 First[0]->Tok.setKind(tok::lessless);
686 First[0]->TokenText = "<<";
687 First[0]->ColumnWidth += 1;
Jacques Pienaarfc275112015-02-18 23:48:37 +0000688 Tokens.erase(Tokens.end() - 2);
689 return true;
690 }
691
Manuel Klimek79e06082015-05-21 12:23:34 +0000692 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000693 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000694 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000695
696 SmallVectorImpl<FormatToken *>::const_iterator First =
697 Tokens.end() - Kinds.size();
698 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000699 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000700 unsigned AddLength = 0;
701 for (unsigned i = 1; i < Kinds.size(); ++i) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000702 if (!First[i]->is(Kinds[i]) ||
703 First[i]->WhitespaceRange.getBegin() !=
704 First[i]->WhitespaceRange.getEnd())
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000705 return false;
706 AddLength += First[i]->TokenText.size();
707 }
708 Tokens.resize(Tokens.size() - Kinds.size() + 1);
709 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
710 First[0]->TokenText.size() + AddLength);
711 First[0]->ColumnWidth += AddLength;
Manuel Klimek79e06082015-05-21 12:23:34 +0000712 First[0]->Type = NewType;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000713 return true;
714 }
715
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000716 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +0000717 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000718 bool tryMergeEscapeSequence() {
719 if (Tokens.size() < 2)
720 return false;
721 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +0000722 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000723 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000724 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000725 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +0000726 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
727 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000728 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +0000729 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +0000730 return true;
731 }
732
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000733 // Try to determine whether the current token ends a JavaScript regex literal.
734 // We heuristically assume that this is a regex literal if we find two
735 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +0000736 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
737 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000738 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +0000739 if (Tokens.size() < 2)
740 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000741
742 // If this is a string literal with a slash inside, compute the slash's
743 // offset and try to find the beginning of the regex literal.
744 // Also look at tok::unknown, as it can be an unterminated char literal.
745 size_t SlashInStringPos = StringRef::npos;
746 if (Tokens.back()->isOneOf(tok::string_literal, tok::char_constant,
747 tok::unknown)) {
748 // Start search from position 1 as otherwise, this is an unknown token
749 // for an unterminated /*-comment which is handled elsewhere.
750 SlashInStringPos = Tokens.back()->TokenText.find('/', 1);
751 if (SlashInStringPos == StringRef::npos)
752 return false;
753 }
754
Daniel Jasper23376252014-09-09 14:37:39 +0000755 // If a regex literal ends in "\//", this gets represented by an unknown
756 // token "\" and a comment.
757 bool MightEndWithEscapedSlash =
758 Tokens.back()->is(tok::comment) &&
759 Tokens.back()->TokenText.startswith("//") &&
760 Tokens[Tokens.size() - 2]->TokenText == "\\";
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000761 if (!MightEndWithEscapedSlash && SlashInStringPos == StringRef::npos &&
Daniel Jasper23376252014-09-09 14:37:39 +0000762 (Tokens.back()->isNot(tok::slash) ||
763 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
764 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000765 return false;
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000766
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000767 unsigned TokenCount = 0;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000768 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
769 ++TokenCount;
Daniel Jasper69694b02015-05-08 07:55:13 +0000770 if (I[0]->isOneOf(tok::slash, tok::slashequal) && I + 1 != E &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000771 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
772 tok::exclaim, tok::l_square, tok::colon, tok::comma,
773 tok::question, tok::kw_return) ||
774 I[1]->isBinaryOperator())) {
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000775 unsigned LastColumn = Tokens.back()->OriginalColumn;
776 SourceLocation Loc = Tokens.back()->Tok.getLocation();
Daniel Jasper23376252014-09-09 14:37:39 +0000777 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +0000778 // This regex literal ends in '\//'. Skip past the '//' of the last
779 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +0000780 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper6b8d26c2015-06-24 16:01:02 +0000781 } else if (SlashInStringPos != StringRef::npos) {
782 // This regex literal ends in a string_literal with a slash inside.
783 // Calculate end column and reset lexer appropriately.
784 resetLexer(SourceMgr.getFileOffset(Loc) + SlashInStringPos + 1);
785 LastColumn += SlashInStringPos;
Daniel Jasper23376252014-09-09 14:37:39 +0000786 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000787 Tokens.resize(Tokens.size() - TokenCount);
788 Tokens.back()->Tok.setKind(tok::unknown);
789 Tokens.back()->Type = TT_RegexLiteral;
790 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
791 return true;
792 }
793
794 // There can't be a newline inside a regex literal.
795 if (I[0]->NewlinesBefore > 0)
796 return false;
797 }
798 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +0000799 }
800
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000801 bool tryMergeTemplateString() {
802 if (Tokens.size() < 2)
803 return false;
804
805 FormatToken *EndBacktick = Tokens.back();
Daniel Jasperf69b9222015-05-02 08:05:38 +0000806 // Backticks get lexed as tok::unknown tokens. If a template string contains
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000807 // a comment start, it gets lexed as a tok::comment, or tok::unknown if
808 // unterminated.
Daniel Jasper2ebb0c52015-06-14 07:16:57 +0000809 if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
810 tok::char_constant, tok::unknown))
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000811 return false;
812 size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
813 // Unknown token that's not actually a backtick, or a comment that doesn't
814 // contain a backtick.
815 if (CommentBacktickPos == StringRef::npos)
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000816 return false;
817
818 unsigned TokenCount = 0;
819 bool IsMultiline = false;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000820 unsigned EndColumnInFirstLine =
821 EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000822 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
823 ++TokenCount;
824 if (I[0]->NewlinesBefore > 0 || I[0]->IsMultiline)
825 IsMultiline = true;
826
827 // If there was a preceding template string, this must be the start of a
828 // template string, not the end.
829 if (I[0]->is(TT_TemplateString))
830 return false;
831
832 if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
833 // Keep track of the rhs offset of the last token to wrap across lines -
834 // its the rhs offset of the first line of the template string, used to
835 // determine its width.
836 if (I[0]->IsMultiline)
837 EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
838 // If the token has newlines, the token before it (if it exists) is the
839 // rhs end of the previous line.
840 if (I[0]->NewlinesBefore > 0 && (I + 1 != E))
841 EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
842
843 continue;
844 }
845
846 Tokens.resize(Tokens.size() - TokenCount);
847 Tokens.back()->Type = TT_TemplateString;
Daniel Jasper0d6ac272015-04-16 08:20:51 +0000848 const char *EndOffset =
849 EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
850 if (CommentBacktickPos != 0) {
851 // If the backtick was not the first character (e.g. in a comment),
852 // re-lex after the backtick position.
853 SourceLocation Loc = EndBacktick->Tok.getLocation();
854 resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
855 }
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000856 Tokens.back()->TokenText =
857 StringRef(Tokens.back()->TokenText.data(),
858 EndOffset - Tokens.back()->TokenText.data());
Daniel Jasperf69b9222015-05-02 08:05:38 +0000859
860 unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
861 if (EndOriginalColumn == 0) {
862 SourceLocation Loc = EndBacktick->Tok.getLocation();
863 EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
864 }
865 // If the ` is further down within the token (e.g. in a comment).
866 EndOriginalColumn += CommentBacktickPos;
867
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000868 if (IsMultiline) {
869 // ColumnWidth is from backtick to last token in line.
870 // LastLineColumnWidth is 0 to backtick.
871 // x = `some content
872 // until here`;
873 Tokens.back()->ColumnWidth =
874 EndColumnInFirstLine - Tokens.back()->OriginalColumn;
Daniel Jasperf69b9222015-05-02 08:05:38 +0000875 Tokens.back()->LastLineColumnWidth = EndOriginalColumn;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000876 Tokens.back()->IsMultiline = true;
877 } else {
878 // Token simply spans from start to end, +1 for the ` itself.
879 Tokens.back()->ColumnWidth =
Daniel Jasperf69b9222015-05-02 08:05:38 +0000880 EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
Daniel Jaspera0ef4f32015-02-20 13:47:38 +0000881 }
882 return true;
883 }
884 return false;
885 }
886
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000887 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +0000888 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000889 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000890 FormatToken *Last = Tokens.back();
891 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000892 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000893
894 FormatToken *String = Tokens[Tokens.size() - 2];
895 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000896 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000897
898 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000899 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000900
901 FormatToken *Macro = Tokens[Tokens.size() - 4];
902 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000903 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000904
905 const char *Start = Macro->TokenText.data();
906 const char *End = Last->TokenText.data() + Last->TokenText.size();
907 String->TokenText = StringRef(Start, End - Start);
908 String->IsFirst = Macro->IsFirst;
909 String->LastNewlineOffset = Macro->LastNewlineOffset;
910 String->WhitespaceRange = Macro->WhitespaceRange;
911 String->OriginalColumn = Macro->OriginalColumn;
912 String->ColumnWidth = encoding::columnWidthWithTabs(
913 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
Daniel Jaspere99c72f2015-03-26 14:47:35 +0000914 String->NewlinesBefore = Macro->NewlinesBefore;
915 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000916
917 Tokens.pop_back();
918 Tokens.pop_back();
919 Tokens.pop_back();
920 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +0000921 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000922 }
923
Manuel Klimek68b03042014-04-14 09:14:11 +0000924 bool tryMergeConflictMarkers() {
925 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
926 return false;
927
928 // Conflict lines look like:
929 // <marker> <text from the vcs>
930 // For example:
931 // >>>>>>> /file/in/file/system at revision 1234
932 //
933 // We merge all tokens in a line that starts with a conflict marker
934 // into a single token with a special token type that the unwrapped line
935 // parser will use to correctly rebuild the underlying code.
936
937 FileID ID;
938 // Get the position of the first token in the line.
939 unsigned FirstInLineOffset;
940 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
941 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
942 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
943 // Calculate the offset of the start of the current line.
944 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
945 if (LineOffset == StringRef::npos) {
946 LineOffset = 0;
947 } else {
948 ++LineOffset;
949 }
950
951 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
952 StringRef LineStart;
953 if (FirstSpace == StringRef::npos) {
954 LineStart = Buffer.substr(LineOffset);
955 } else {
956 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
957 }
958
959 TokenType Type = TT_Unknown;
960 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
961 Type = TT_ConflictStart;
962 } else if (LineStart == "|||||||" || LineStart == "=======" ||
963 LineStart == "====") {
964 Type = TT_ConflictAlternative;
965 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
966 Type = TT_ConflictEnd;
967 }
968
969 if (Type != TT_Unknown) {
970 FormatToken *Next = Tokens.back();
971
972 Tokens.resize(FirstInLineIndex + 1);
973 // We do not need to build a complete token here, as we will skip it
974 // during parsing anyway (as we must not touch whitespace around conflict
975 // markers).
976 Tokens.back()->Type = Type;
977 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
978
979 Tokens.push_back(Next);
980 return true;
981 }
982
983 return false;
984 }
985
Jacques Pienaarfc275112015-02-18 23:48:37 +0000986 FormatToken *getStashedToken() {
987 // Create a synthesized second '>' or '<' token.
988 Token Tok = FormatTok->Tok;
989 StringRef TokenText = FormatTok->TokenText;
990
991 unsigned OriginalColumn = FormatTok->OriginalColumn;
992 FormatTok = new (Allocator.Allocate()) FormatToken;
993 FormatTok->Tok = Tok;
994 SourceLocation TokLocation =
Jacques Pienaar411b2512015-02-24 23:23:24 +0000995 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
996 FormatTok->Tok.setLocation(TokLocation);
Jacques Pienaarfc275112015-02-18 23:48:37 +0000997 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
998 FormatTok->TokenText = TokenText;
999 FormatTok->ColumnWidth = 1;
Jacques Pienaar411b2512015-02-24 23:23:24 +00001000 FormatTok->OriginalColumn = OriginalColumn + 1;
1001
Jacques Pienaarfc275112015-02-18 23:48:37 +00001002 return FormatTok;
1003 }
1004
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001005 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001006 if (GreaterStashed) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001007 GreaterStashed = false;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001008 return getStashedToken();
1009 }
1010 if (LessStashed) {
1011 LessStashed = false;
1012 return getStashedToken();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001013 }
1014
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001015 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001016 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001017 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001018 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001019 FormatTok->IsFirst = IsFirstToken;
1020 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001021
1022 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001023 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001024 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jaspere2408e32015-05-06 11:16:43 +00001025 StringRef Text = FormatTok->TokenText;
1026 auto EscapesNewline = [&](int pos) {
1027 // A '\r' here is just part of '\r\n'. Skip it.
1028 if (pos >= 0 && Text[pos] == '\r')
1029 --pos;
1030 // See whether there is an odd number of '\' before this.
1031 unsigned count = 0;
1032 for (; pos >= 0; --pos, ++count)
Daniel Jasperf0fd1c62015-05-10 08:00:25 +00001033 if (Text[pos] != '\\')
Daniel Jaspere2408e32015-05-06 11:16:43 +00001034 break;
1035 return count & 1;
1036 };
Daniel Jaspera0ef4f32015-02-20 13:47:38 +00001037 // FIXME: This miscounts tok:unknown tokens that are not just
1038 // whitespace, e.g. a '`' character.
Daniel Jaspere2408e32015-05-06 11:16:43 +00001039 for (int i = 0, e = Text.size(); i != e; ++i) {
1040 switch (Text[i]) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001041 case '\n':
1042 ++FormatTok->NewlinesBefore;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001043 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
Manuel Klimek31c85922013-08-29 15:21:40 +00001044 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1045 Column = 0;
1046 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001047 case '\r':
Daniel Jasper30029c62015-02-05 11:05:31 +00001048 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1049 Column = 0;
1050 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001051 case '\f':
1052 case '\v':
1053 Column = 0;
1054 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001055 case ' ':
1056 ++Column;
1057 break;
1058 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001059 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001060 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001061 case '\\':
Daniel Jaspere2408e32015-05-06 11:16:43 +00001062 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
Daniel Jasper877615c2013-10-11 19:45:02 +00001063 FormatTok->Type = TT_ImplicitStringLiteral;
1064 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001065 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001066 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001067 ++Column;
1068 break;
1069 }
1070 }
1071
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001072 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001073 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001074 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001075
Daniel Jasper8369aa52013-07-16 20:28:33 +00001076 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001077 }
Manuel Klimekef920692013-01-07 07:56:50 +00001078
Manuel Klimek1abf7892013-01-04 23:34:14 +00001079 // In case the token starts with escaped newlines, we want to
1080 // take them into account as whitespace - this pattern is quite frequent
1081 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001082 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001083 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1084 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001085 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001086 WhitespaceLength += 2;
Daniel Jaspere2408e32015-05-06 11:16:43 +00001087 FormatTok->LastNewlineOffset = 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001088 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001089 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001090 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001091
1092 FormatTok->WhitespaceRange = SourceRange(
1093 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1094
Manuel Klimek31c85922013-08-29 15:21:40 +00001095 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001096
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001097 TrailingWhitespace = 0;
1098 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001099 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001100 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001101 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001102 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001103 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001104 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001105 FormatTok->Tok.setIdentifierInfo(&Info);
1106 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001107 if (Style.Language == FormatStyle::LK_Java &&
1108 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1109 FormatTok->Tok.setKind(tok::identifier);
1110 FormatTok->Tok.setIdentifierInfo(nullptr);
1111 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001112 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001113 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001114 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001115 GreaterStashed = true;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001116 } else if (FormatTok->Tok.is(tok::lessless)) {
1117 FormatTok->Tok.setKind(tok::less);
1118 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1119 LessStashed = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001120 }
1121
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001122 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001123
Alexander Kornienko39856b72013-09-10 09:38:25 +00001124 StringRef Text = FormatTok->TokenText;
1125 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001126 if (FirstNewlinePos == StringRef::npos) {
1127 // FIXME: ColumnWidth actually depends on the start column, we need to
1128 // take this into account when the token is moved.
1129 FormatTok->ColumnWidth =
1130 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1131 Column += FormatTok->ColumnWidth;
1132 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001133 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001134 // FIXME: ColumnWidth actually depends on the start column, we need to
1135 // take this into account when the token is moved.
1136 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1137 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1138
Alexander Kornienko39856b72013-09-10 09:38:25 +00001139 // The last line of the token always starts in column 0.
1140 // Thus, the length can be precomputed even in the presence of tabs.
1141 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1142 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1143 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001144 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001145 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001146
Daniel Jasper229628b2015-06-11 08:38:19 +00001147 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1148 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1149 tok::pp_define) &&
1150 std::find(ForEachMacros.begin(), ForEachMacros.end(),
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001151 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end())
1152 FormatTok->Type = TT_ForEachMacro;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001153
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001154 return FormatTok;
1155 }
1156
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001157 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001158 bool IsFirstToken;
Jacques Pienaarfc275112015-02-18 23:48:37 +00001159 bool GreaterStashed, LessStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001160 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001161 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001162 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001163 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001164 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001165 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001166 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001167 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001168 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001169 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001170 // Index (in 'Tokens') of the last token that starts a new line.
1171 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001172 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001173 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001174
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001175 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001176
Daniel Jasper8369aa52013-07-16 20:28:33 +00001177 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001178 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001179 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1180 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001181 // For formatting, treat unterminated string literals like normal string
1182 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001183 if (Tok.is(tok::unknown)) {
1184 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1185 Tok.Tok.setKind(tok::string_literal);
1186 Tok.IsUnterminatedLiteral = true;
1187 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1188 Tok.TokenText == "''") {
1189 Tok.Tok.setKind(tok::char_constant);
1190 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001191 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001192
1193 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1194 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001195 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001196 }
1197
Daniel Jasper471894432014-08-06 13:40:26 +00001198 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001199
1200 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1201 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001202 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001203 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001204 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001205
1206 void resetLexer(unsigned Offset) {
1207 StringRef Buffer = SourceMgr.getBufferData(ID);
1208 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1209 getFormattingLangOpts(Style), Buffer.begin(),
1210 Buffer.begin() + Offset, Buffer.end()));
1211 Lex->SetKeepWhitespaceMode(true);
1212 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001213};
1214
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001215static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1216 switch (Language) {
1217 case FormatStyle::LK_Cpp:
1218 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001219 case FormatStyle::LK_Java:
1220 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001221 case FormatStyle::LK_JavaScript:
1222 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001223 case FormatStyle::LK_Proto:
1224 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001225 default:
1226 return "Unknown";
1227 }
1228}
1229
Daniel Jasperf7935112012-12-03 18:12:45 +00001230class Formatter : public UnwrappedLineConsumer {
1231public:
Daniel Jasper23376252014-09-09 14:37:39 +00001232 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001233 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001234 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1235 Whitespaces(SourceMgr, Style,
1236 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001237 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001238 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001239 DEBUG(llvm::dbgs() << "File encoding: "
1240 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1241 : "unknown")
1242 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001243 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1244 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001245 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001246
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001247 tooling::Replacements format(bool *IncompleteFormat) {
Manuel Klimek71814b42013-10-11 21:25:45 +00001248 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001249 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001250
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001251 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1252 *this);
Manuel Klimek20e0af62015-05-06 11:56:29 +00001253 Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001254 assert(UnwrappedLines.rbegin()->empty());
1255 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1256 ++Run) {
1257 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1258 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1259 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1260 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1261 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001262 tooling::Replacements RunResult =
1263 format(AnnotatedLines, Tokens, IncompleteFormat);
Manuel Klimek71814b42013-10-11 21:25:45 +00001264 DEBUG({
1265 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1266 for (tooling::Replacements::iterator I = RunResult.begin(),
1267 E = RunResult.end();
1268 I != E; ++I) {
1269 llvm::dbgs() << I->toString() << "\n";
1270 }
1271 });
1272 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1273 delete AnnotatedLines[i];
1274 }
1275 Result.insert(RunResult.begin(), RunResult.end());
1276 Whitespaces.reset();
1277 }
1278 return Result;
1279 }
1280
1281 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001282 FormatTokenLexer &Tokens,
1283 bool *IncompleteFormat) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001284 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001285 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001286 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001287 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001288 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001289 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001290 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001291 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001292 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001293
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001294 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001295 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1296 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001297 BinPackInconclusiveFunctions);
Manuel Klimekd3585db2015-05-11 08:21:35 +00001298 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1299 IncompleteFormat)
1300 .format(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001301 return Whitespaces.generateReplacements();
1302 }
1303
1304private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001305 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001306 // Returns \c true if at least one line between I and E or one of their
1307 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001308 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1309 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1310 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001311 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001312 while (I != E) {
1313 AnnotatedLine *Line = *I;
1314 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1315
1316 // If a line is part of a preprocessor directive, it needs to be formatted
1317 // if any token within the directive is affected.
1318 if (Line->InPPDirective) {
1319 FormatToken *Last = Line->Last;
1320 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1321 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1322 Last = (*PPEnd)->Last;
1323 ++PPEnd;
1324 }
1325
1326 if (affectsTokenRange(*Line->First, *Last,
1327 /*IncludeLeadingNewlines=*/false)) {
1328 SomeLineAffected = true;
1329 markAllAsAffected(I, PPEnd);
1330 }
1331 I = PPEnd;
1332 continue;
1333 }
1334
Daniel Jasper38c82402013-11-29 09:27:43 +00001335 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001336 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001337
Daniel Jasper38c82402013-11-29 09:27:43 +00001338 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001339 ++I;
1340 }
1341 return SomeLineAffected;
1342 }
1343
Daniel Jasper9c199562013-11-28 15:58:55 +00001344 // Determines whether 'Line' is affected by the SourceRanges given as input.
1345 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001346 bool nonPPLineAffected(AnnotatedLine *Line,
1347 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001348 bool SomeLineAffected = false;
1349 Line->ChildrenAffected =
1350 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1351 if (Line->ChildrenAffected)
1352 SomeLineAffected = true;
1353
1354 // Stores whether one of the line's tokens is directly affected.
1355 bool SomeTokenAffected = false;
1356 // Stores whether we need to look at the leading newlines of the next token
1357 // in order to determine whether it was affected.
1358 bool IncludeLeadingNewlines = false;
1359
1360 // Stores whether the first child line of any of this line's tokens is
1361 // affected.
1362 bool SomeFirstChildAffected = false;
1363
1364 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1365 // Determine whether 'Tok' was affected.
1366 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1367 SomeTokenAffected = true;
1368
1369 // Determine whether the first child of 'Tok' was affected.
1370 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1371 SomeFirstChildAffected = true;
1372
1373 IncludeLeadingNewlines = Tok->Children.empty();
1374 }
1375
1376 // Was this line moved, i.e. has it previously been on the same line as an
1377 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001378 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1379 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001380
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001381 bool IsContinuedComment =
1382 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1383 Line->First->NewlinesBefore < 2 && PreviousLine &&
1384 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001385
1386 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1387 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001388 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001389 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001390 }
1391 return SomeLineAffected;
1392 }
1393
Daniel Jasper5500f612013-11-25 11:08:59 +00001394 // Marks all lines between I and E as well as all their children as affected.
1395 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1396 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1397 while (I != E) {
1398 (*I)->Affected = true;
1399 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1400 ++I;
1401 }
1402 }
1403
1404 // Returns true if the range from 'First' to 'Last' intersects with one of the
1405 // input ranges.
1406 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1407 bool IncludeLeadingNewlines) {
1408 SourceLocation Start = First.WhitespaceRange.getBegin();
1409 if (!IncludeLeadingNewlines)
1410 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001411 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001412 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001413 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1414 return affectsCharSourceRange(Range);
1415 }
1416
1417 // Returns true if one of the input ranges intersect the leading empty lines
1418 // before 'Tok'.
1419 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1420 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1421 Tok.WhitespaceRange.getBegin(),
1422 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1423 return affectsCharSourceRange(EmptyLineRange);
1424 }
1425
1426 // Returns true if 'Range' intersects with one of the input ranges.
1427 bool affectsCharSourceRange(const CharSourceRange &Range) {
1428 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1429 E = Ranges.end();
1430 I != E; ++I) {
1431 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1432 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1433 return true;
1434 }
1435 return false;
1436 }
1437
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001438 static bool inputUsesCRLF(StringRef Text) {
1439 return Text.count('\r') * 2 > Text.count('\n');
1440 }
1441
Manuel Klimek71814b42013-10-11 21:25:45 +00001442 void
1443 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001444 unsigned CountBoundToVariable = 0;
1445 unsigned CountBoundToType = 0;
1446 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001447 bool HasBinPackedFunction = false;
1448 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001449 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001450 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001451 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001452 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001453 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001454 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001455 bool SpacesBefore =
1456 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1457 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1458 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001459 if (SpacesBefore && !SpacesAfter)
1460 ++CountBoundToVariable;
1461 else if (!SpacesBefore && SpacesAfter)
1462 ++CountBoundToType;
1463 }
1464
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001465 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001466 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001467 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001468 if (Tok->is(TT_TemplateCloser) &&
1469 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001470 HasCpp03IncompatibleFormat = true;
1471 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001472
1473 if (Tok->PackingKind == PPK_BinPacked)
1474 HasBinPackedFunction = true;
1475 if (Tok->PackingKind == PPK_OnePerLine)
1476 HasOnePerLineFunction = true;
1477
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001478 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001479 }
1480 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001481 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001482 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001483 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001484 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001485 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001486 }
1487 if (Style.Standard == FormatStyle::LS_Auto) {
1488 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1489 : FormatStyle::LS_Cpp03;
1490 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001491 BinPackInconclusiveFunctions =
1492 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001493 }
1494
Craig Topperfb6b25b2014-03-15 04:29:04 +00001495 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001496 assert(!UnwrappedLines.empty());
1497 UnwrappedLines.back().push_back(TheLine);
1498 }
1499
Craig Topperfb6b25b2014-03-15 04:29:04 +00001500 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001501 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001502 }
1503
1504 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00001505 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00001506 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001507 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001508 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001509 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001510
1511 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001512 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001513};
1514
Craig Topperaf35e852013-06-30 22:29:28 +00001515} // end anonymous namespace
1516
Daniel Jasper23376252014-09-09 14:37:39 +00001517tooling::Replacements reformat(const FormatStyle &Style,
1518 SourceManager &SourceMgr, FileID ID,
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001519 ArrayRef<CharSourceRange> Ranges,
1520 bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001521 if (Style.DisableFormat)
1522 return tooling::Replacements();
1523 Formatter formatter(Style, SourceMgr, ID, Ranges);
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001524 return formatter.format(IncompleteFormat);
Daniel Jasperf7935112012-12-03 18:12:45 +00001525}
1526
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001527tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001528 ArrayRef<tooling::Range> Ranges,
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001529 StringRef FileName, bool *IncompleteFormat) {
Daniel Jasper23376252014-09-09 14:37:39 +00001530 if (Style.DisableFormat)
1531 return tooling::Replacements();
1532
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001533 FileManager Files((FileSystemOptions()));
1534 DiagnosticsEngine Diagnostics(
1535 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1536 new DiagnosticOptions);
1537 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001538 std::unique_ptr<llvm::MemoryBuffer> Buf =
1539 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001540 const clang::FileEntry *Entry =
1541 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00001542 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001543 FileID ID =
1544 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001545 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1546 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001547 for (const tooling::Range &Range : Ranges) {
1548 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1549 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001550 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1551 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001552 return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001553}
1554
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001555LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001556 LangOptions LangOpts;
1557 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001558 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1559 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001560 LangOpts.LineComment = 1;
Daniel Jasper1662bfe2015-04-03 21:15:46 +00001561 bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
Daniel Jasper30a24062014-11-14 09:02:28 +00001562 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001563 LangOpts.Bool = 1;
1564 LangOpts.ObjC1 = 1;
1565 LangOpts.ObjC2 = 1;
Nico Weberfac23712015-02-04 15:26:27 +00001566 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001567 return LangOpts;
1568}
1569
Edwin Vaned544aa72013-09-30 13:31:48 +00001570const char *StyleOptionHelpDescription =
1571 "Coding style, currently supports:\n"
1572 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1573 "Use -style=file to load style configuration from\n"
1574 ".clang-format file located in one of the parent\n"
1575 "directories of the source file (or current\n"
1576 "directory for stdin).\n"
1577 "Use -style=\"{key: value, ...}\" to set specific\n"
1578 "parameters, e.g.:\n"
1579 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1580
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001581static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001582 if (FileName.endswith(".java")) {
1583 return FormatStyle::LK_Java;
Daniel Jasper8c68a642015-03-11 14:58:38 +00001584 } else if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) {
1585 // JavaScript or TypeScript.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001586 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001587 } else if (FileName.endswith_lower(".proto") ||
1588 FileName.endswith_lower(".protodevel")) {
1589 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001590 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001591 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001592}
1593
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001594FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1595 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001596 FormatStyle Style = getLLVMStyle();
1597 Style.Language = getLanguageByFileName(FileName);
1598 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001599 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1600 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001601 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001602 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001603
1604 if (StyleName.startswith("{")) {
1605 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00001606 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001607 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1608 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001609 }
1610 return Style;
1611 }
1612
1613 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001614 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001615 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1616 << " style\n";
1617 return Style;
1618 }
1619
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001620 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001621 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001622 SmallString<128> Path(FileName);
1623 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001624 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001625 Directory = llvm::sys::path::parent_path(Directory)) {
1626 if (!llvm::sys::fs::is_directory(Directory))
1627 continue;
1628 SmallString<128> ConfigFile(Directory);
1629
1630 llvm::sys::path::append(ConfigFile, ".clang-format");
1631 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1632 bool IsFile = false;
1633 // Ignore errors from is_regular_file: we only need to know if we can read
1634 // the file or not.
1635 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1636
1637 if (!IsFile) {
1638 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1639 ConfigFile = Directory;
1640 llvm::sys::path::append(ConfigFile, "_clang-format");
1641 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1642 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1643 }
1644
1645 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001646 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1647 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1648 if (std::error_code EC = Text.getError()) {
1649 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001650 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001651 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001652 if (std::error_code ec =
1653 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00001654 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001655 if (!UnsuitableConfigFiles.empty())
1656 UnsuitableConfigFiles.append(", ");
1657 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001658 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001659 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001660 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1661 << "\n";
1662 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001663 }
1664 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1665 return Style;
1666 }
1667 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001668 if (!UnsuitableConfigFiles.empty()) {
1669 llvm::errs() << "Configuration file(s) do(es) not support "
1670 << getLanguageName(Style.Language) << ": "
1671 << UnsuitableConfigFiles << "\n";
1672 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001673 return Style;
1674}
1675
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001676} // namespace format
1677} // namespace clang