blob: ebf493c628a328d00732325effa40e80a9d0e890 [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///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Weber9efe2912013-01-10 23:11:41 +000049 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000050 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000051 TT_OverloadedOperator,
52 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000053 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000054 TT_TemplateCloser,
55 TT_TemplateOpener,
56 TT_TrailingUnaryOperator,
57 TT_UnaryOperator,
58 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000059};
60
61enum LineType {
62 LT_Invalid,
63 LT_Other,
64 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000069};
70
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
73 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper9278eb92013-01-16 14:59:02 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000077
Daniel Jasper25837aa2013-01-14 14:14:23 +000078 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
79 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
80
Daniel Jasper7c85fde2013-01-08 14:56:18 +000081 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
82 return FormatTok.Tok.isObjCAtKeyword(Kind);
83 }
84
85 FormatToken FormatTok;
86
Daniel Jasperf7935112012-12-03 18:12:45 +000087 TokenType Type;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 bool SpaceRequiredBefore;
90 bool CanBreakBefore;
91 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000092
93 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000094
Daniel Jasper9278eb92013-01-16 14:59:02 +000095 AnnotatedToken *MatchingParen;
96
Daniel Jaspera67a8f02013-01-16 10:41:46 +000097 /// \brief The total length of the line up to and including this token.
98 unsigned TotalLength;
99
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000100 std::vector<AnnotatedToken> Children;
101 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000102};
103
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000104class AnnotatedLine {
105public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000106 AnnotatedLine(const UnwrappedLine &Line)
107 : First(Line.Tokens.front()), Level(Line.Level),
108 InPPDirective(Line.InPPDirective) {
109 assert(!Line.Tokens.empty());
110 AnnotatedToken *Current = &First;
111 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
112 E = Line.Tokens.end();
113 I != E; ++I) {
114 Current->Children.push_back(*I);
115 Current->Children[0].Parent = Current;
116 Current = &Current->Children[0];
117 }
118 Last = Current;
119 }
120 AnnotatedLine(const AnnotatedLine &Other)
121 : First(Other.First), Type(Other.Type), Level(Other.Level),
122 InPPDirective(Other.InPPDirective) {
123 Last = &First;
124 while (!Last->Children.empty()) {
125 Last->Children[0].Parent = Last;
126 Last = &Last->Children[0];
127 }
128 }
129
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000130 AnnotatedToken First;
131 AnnotatedToken *Last;
132
133 LineType Type;
134 unsigned Level;
135 bool InPPDirective;
136};
137
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000138static prec::Level getPrecedence(const AnnotatedToken &Tok) {
139 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000140}
141
Daniel Jasperf7935112012-12-03 18:12:45 +0000142FormatStyle getLLVMStyle() {
143 FormatStyle LLVMStyle;
144 LLVMStyle.ColumnLimit = 80;
145 LLVMStyle.MaxEmptyLinesToKeep = 1;
146 LLVMStyle.PointerAndReferenceBindToType = false;
147 LLVMStyle.AccessModifierOffset = -2;
148 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000149 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000150 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000151 LLVMStyle.BinPackParameters = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000152 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000153 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000154 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000155 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000156 return LLVMStyle;
157}
158
159FormatStyle getGoogleStyle() {
160 FormatStyle GoogleStyle;
161 GoogleStyle.ColumnLimit = 80;
162 GoogleStyle.MaxEmptyLinesToKeep = 1;
163 GoogleStyle.PointerAndReferenceBindToType = true;
164 GoogleStyle.AccessModifierOffset = -1;
165 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000166 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000167 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000168 GoogleStyle.BinPackParameters = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000169 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000170 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000171 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000172 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000173 return GoogleStyle;
174}
175
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000176FormatStyle getChromiumStyle() {
177 FormatStyle ChromiumStyle = getGoogleStyle();
178 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
179 return ChromiumStyle;
180}
181
Daniel Jasperf7935112012-12-03 18:12:45 +0000182struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000183 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000184 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000185 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000186};
187
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000188/// \brief Replaces the whitespace in front of \p Tok. Only call once for
189/// each \c FormatToken.
190static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
191 unsigned Spaces, const FormatStyle &Style,
192 SourceManager &SourceMgr,
193 tooling::Replacements &Replaces) {
194 Replaces.insert(tooling::Replacement(
195 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
196 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
197}
198
199/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
200/// backslashes to escape newlines inside a preprocessor directive.
201///
202/// This function and \c replaceWhitespace have the same behavior if
203/// \c Newlines == 0.
204static void replacePPWhitespace(
205 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
206 unsigned WhitespaceStartColumn, const FormatStyle &Style,
207 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
208 std::string NewLineText;
209 if (NewLines > 0) {
210 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
211 WhitespaceStartColumn);
212 for (unsigned i = 0; i < NewLines; ++i) {
213 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
214 NewLineText += "\\\n";
215 Offset = 0;
216 }
217 }
218 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
219 Tok.FormatTok.WhiteSpaceLength,
220 NewLineText + std::string(Spaces, ' ')));
221}
222
Nico Weberc9d73612013-01-12 22:48:47 +0000223/// \brief Returns if a token is an Objective-C selector name.
224///
Nico Weber92c05392013-01-12 22:51:13 +0000225/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000226static bool isObjCSelectorName(const AnnotatedToken &Tok) {
227 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
228 Tok.Children[0].is(tok::colon) &&
229 Tok.Children[0].Type == TT_ObjCMethodExpr;
230}
231
Daniel Jasperf7935112012-12-03 18:12:45 +0000232class UnwrappedLineFormatter {
233public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000234 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000235 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000236 const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000237 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000238 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000239 FirstIndent(FirstIndent), RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000240 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000241 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000242 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000243 }
244
Manuel Klimek1abf7892013-01-04 23:34:14 +0000245 /// \brief Formats an \c UnwrappedLine.
246 ///
247 /// \returns The column after the last token in the last line of the
248 /// \c UnwrappedLine.
249 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000250 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000251 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000252 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000253 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000254 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000255 State.ForLoopVariablePos = 0;
256 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000257 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000258
Manuel Klimek24998102013-01-16 14:55:28 +0000259 DEBUG({
260 DebugTokenState(*State.NextToken);
261 });
262
Daniel Jaspere9de2602012-12-06 09:56:08 +0000263 // The first token has already been indented and thus consumed.
264 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000265
266 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000267 while (State.NextToken != NULL) {
Manuel Klimeka31e58b2013-01-15 16:41:02 +0000268 if (State.NextToken->Type == TT_ImplicitStringLiteral)
269 // We will not touch the rest of the white space in this
270 // \c UnwrappedLine. The returned value can also not matter, as we
271 // cannot continue an top-level implicit string literal on the next
272 // line.
273 return 0;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000274 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000275 addTokenToState(false, false, State);
276 } else {
277 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
278 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000279 DEBUG({
280 if (Break < NoBreak)
281 llvm::errs() << "\n";
282 else
283 llvm::errs() << " ";
284 llvm::errs() << "<";
285 DebugPenalty(Break, Break < NoBreak);
286 llvm::errs() << "/";
287 DebugPenalty(NoBreak, !(Break < NoBreak));
288 llvm::errs() << "> ";
289 DebugTokenState(*State.NextToken);
290 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000291 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000292 if (State.NextToken != NULL &&
293 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
294 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000295 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000296 State.Stack.back().BreakAfterComma = true;
297 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000298 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000299 }
Manuel Klimek24998102013-01-16 14:55:28 +0000300 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000301 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000302 }
303
304private:
Manuel Klimek24998102013-01-16 14:55:28 +0000305 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
306 const Token &Tok = AnnotatedTok.FormatTok.Tok;
307 llvm::errs()
308 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
309 Tok.getLength());
310 llvm::errs();
311 }
312
313 void DebugPenalty(unsigned Penalty, bool Winner) {
314 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
315 if (Penalty == UINT_MAX)
316 llvm::errs() << "MAX";
317 else
318 llvm::errs() << Penalty;
319 llvm::errs().resetColor();
320 }
321
Daniel Jasper337816e2013-01-11 10:22:12 +0000322 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000323 ParenState(unsigned Indent, unsigned LastSpace)
324 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000325 BreakBeforeClosingBrace(false), BreakAfterComma(false),
326 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000327
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 /// \brief The position to which a specific parenthesis level needs to be
329 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000330 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000331
Daniel Jaspere9de2602012-12-06 09:56:08 +0000332 /// \brief The position of the last space on each level.
333 ///
334 /// Used e.g. to break like:
335 /// functionCall(Parameter, otherCall(
336 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000337 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000338
Daniel Jaspere9de2602012-12-06 09:56:08 +0000339 /// \brief The position the first "<<" operator encountered on each level.
340 ///
341 /// Used to align "<<" operators. 0 if no such operator has been encountered
342 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000343 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000344
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000345 /// \brief Whether a newline needs to be inserted before the block's closing
346 /// brace.
347 ///
348 /// We only want to insert a newline before the closing brace if there also
349 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000350 bool BreakBeforeClosingBrace;
351
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000352 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000353 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000354
Daniel Jasper337816e2013-01-11 10:22:12 +0000355 bool operator<(const ParenState &Other) const {
356 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000357 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000358 if (LastSpace != Other.LastSpace)
359 return LastSpace < Other.LastSpace;
360 if (FirstLessLess != Other.FirstLessLess)
361 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000362 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
363 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000364 if (BreakAfterComma != Other.BreakAfterComma)
365 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000366 if (HasMultiParameterLine != Other.HasMultiParameterLine)
367 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000368 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000369 }
370 };
371
372 /// \brief The current state when indenting a unwrapped line.
373 ///
374 /// As the indenting tries different combinations this is copied by value.
375 struct LineState {
376 /// \brief The number of used columns in the current line.
377 unsigned Column;
378
379 /// \brief The token that needs to be next formatted.
380 const AnnotatedToken *NextToken;
381
382 /// \brief The parenthesis level of the first token on the current line.
383 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000384
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000385 /// \brief The column of the first variable in a for-loop declaration.
386 ///
387 /// Used to align the second variable if necessary.
388 unsigned ForLoopVariablePos;
389
390 /// \brief \c true if this line contains a continued for-loop section.
391 bool LineContainsContinuedForLoopSection;
392
Daniel Jasper337816e2013-01-11 10:22:12 +0000393 /// \brief A stack keeping track of properties applying to parenthesis
394 /// levels.
395 std::vector<ParenState> Stack;
396
397 /// \brief Comparison operator to be able to used \c LineState in \c map.
398 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000399 if (Other.NextToken != NextToken)
400 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000401 if (Other.Column != Column)
402 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000403 if (Other.StartOfLineLevel != StartOfLineLevel)
404 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000405 if (Other.ForLoopVariablePos != ForLoopVariablePos)
406 return Other.ForLoopVariablePos < ForLoopVariablePos;
407 if (Other.LineContainsContinuedForLoopSection !=
408 LineContainsContinuedForLoopSection)
409 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000410 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
412 };
413
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000414 /// \brief Appends the next token to \p State and updates information
415 /// necessary for indentation.
416 ///
417 /// Puts the token on the current line if \p Newline is \c true and adds a
418 /// line break and necessary indentation otherwise.
419 ///
420 /// If \p DryRun is \c false, also creates and stores the required
421 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000422 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000423 const AnnotatedToken &Current = *State.NextToken;
424 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000425 assert(State.Stack.size());
426 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000427
428 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000429 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000430 if (Current.is(tok::r_brace)) {
431 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000432 } else if (Current.is(tok::string_literal) &&
433 Previous.is(tok::string_literal)) {
434 State.Column = State.Column - Previous.FormatTok.TokenLength;
435 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000436 State.Stack[ParenLevel].FirstLessLess != 0) {
437 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000438 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000439 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
440 Current.is(tok::period) || Previous.is(tok::question) ||
441 Previous.Type == TT_ConditionalExpr)) {
442 // Indent and extra 4 spaces after if we know the current expression is
443 // continued. Don't do that on the top level, as we already indent 4
444 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000446 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000447 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000448 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000450 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000451 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000452 }
453
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000454 // A line starting with a closing brace is assumed to be correct for the
455 // same level as before the opening brace.
456 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000457
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000458 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000459 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000460
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000461 if (!DryRun) {
462 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000463 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
464 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000465 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000466 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000467 WhitespaceStartColumn, Style, SourceMgr,
468 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000469 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000470
Daniel Jasper337816e2013-01-11 10:22:12 +0000471 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000472 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000473 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000474 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000475 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
476 State.ForLoopVariablePos = State.Column -
477 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000478
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000479 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
480 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000481 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000482
Daniel Jasperf7935112012-12-03 18:12:45 +0000483 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000484 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000485
Daniel Jasperbcab4302013-01-09 10:40:23 +0000486 // FIXME: Do we need to do this for assignments nested in other
487 // expressions?
488 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000489 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000490 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000491 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000492 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000493 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000494 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000495 if (Previous.is(tok::comma))
496 State.Stack[ParenLevel].HasMultiParameterLine = true;
497
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000498
Daniel Jasper206df732013-01-07 13:08:40 +0000499 // Top-level spaces that are not part of assignments are exempt as that
500 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000501 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000502 if (Spaces > 0 &&
503 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000504 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000505 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000506
507 // If we break after an {, we should also break before the corresponding }.
508 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000509 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000510
511 // If we are breaking after '(', '{', '<' or ',', we need to break after
512 // future commas as well to avoid bin packing.
513 if (!Style.BinPackParameters && Newline &&
514 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
515 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
516 State.Stack.back().BreakAfterComma = true;
517
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000518 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000519 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000520
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000521 /// \brief Mark the next token as consumed in \p State and modify its stacks
522 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000523 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000524 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000525 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000526
Daniel Jasper337816e2013-01-11 10:22:12 +0000527 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
528 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000529
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000530 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000531 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000532 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
533 Current.is(tok::l_brace) ||
534 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000535 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000536 if (Current.is(tok::l_brace)) {
537 // FIXME: This does not work with nested static initializers.
538 // Implement a better handling for static initializers and similar
539 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000541 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000543 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000545 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000546
547 // If the entire set of parameters will not fit on the current line, we
548 // will need to break after commas on this level to avoid bin-packing.
549 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
550 !Current.Children.empty()) {
551 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
552 Current.MatchingParen->TotalLength -
553 Current.Children[0].TotalLength) {
554 State.Stack.back().BreakAfterComma = true;
555 }
556 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 }
558
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000559 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000560 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000561 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
562 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
563 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000566
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000567 if (State.NextToken->Children.empty())
568 State.NextToken = NULL;
569 else
570 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000571
572 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000573 }
574
Nico Weber49cbc2c2013-01-07 15:15:29 +0000575 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000576 unsigned splitPenalty(const AnnotatedToken &Tok) {
577 const AnnotatedToken &Left = Tok;
578 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000579
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000580 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
581 return 50;
582 if (Left.is(tok::equal) && Right.is(tok::l_brace))
583 return 150;
584
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000585 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000586 if (RootToken.is(tok::kw_for) &&
587 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000588 return 20;
589
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 if (Left.is(tok::semi) || Left.is(tok::comma) ||
591 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000593
594 // In Objective-C method expressions, prefer breaking before "param:" over
595 // breaking after it.
596 if (isObjCSelectorName(Right))
597 return 0;
598 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
599 return 20;
600
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000601 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000602 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000603
Daniel Jasper399d24b2013-01-09 07:06:56 +0000604 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
605 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000606 prec::Level Level = getPrecedence(Left);
607
608 // Breaking after an assignment leads to a bad result as the two sides of
609 // the assignment are visually very close together.
610 if (Level == prec::Assignment)
611 return 50;
612
Daniel Jasperde5c2072012-12-24 00:13:23 +0000613 if (Level != prec::Unknown)
614 return Level;
615
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000616 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000617 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000618
Daniel Jasperf7935112012-12-03 18:12:45 +0000619 return 3;
620 }
621
Daniel Jasper2df93312013-01-09 10:16:05 +0000622 unsigned getColumnLimit() {
623 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
624 }
625
Daniel Jasperf7935112012-12-03 18:12:45 +0000626 /// \brief Calculate the number of lines needed to format the remaining part
627 /// of the unwrapped line.
628 ///
629 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000630 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000631 /// added after the previous token.
632 ///
633 /// \param StopAt is used for optimization. If we can determine that we'll
634 /// definitely need at least \p StopAt additional lines, we already know of a
635 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000636 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000637 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000638 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000639 return 0;
640
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000641 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000642 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000643 if (NewLine && !State.NextToken->CanBreakBefore &&
644 !(State.NextToken->is(tok::r_brace) &&
645 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000647 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000648 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000649 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000650 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000651 State.LineContainsContinuedForLoopSection)
652 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000653 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
654 State.NextToken->Type != TT_LineComment &&
655 State.Stack.back().BreakAfterComma)
656 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000657 // Trying to insert a parameter on a new line if there are already more than
658 // one parameter on the current line is bin packing.
659 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
660 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
661 return UINT_MAX;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000662 if (!NewLine && State.NextToken->Type == TT_CtorInitializerColon)
663 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000664
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000665 unsigned CurrentPenalty = 0;
666 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000667 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000668 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000669 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000670 if (State.Stack.size() < State.StartOfLineLevel &&
671 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000672 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000673 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000674 }
675
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000676 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000677
Daniel Jasper2df93312013-01-09 10:16:05 +0000678 // Exceeding column limit is bad, assign penalty.
679 if (State.Column > getColumnLimit()) {
680 unsigned ExcessCharacters = State.Column - getColumnLimit();
681 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
682 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000683
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 if (StopAt <= CurrentPenalty)
685 return UINT_MAX;
686 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000687 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000688 if (I != Memory.end()) {
689 // If this state has already been examined, we can safely return the
690 // previous result if we
691 // - have not hit the optimatization (and thus returned UINT_MAX) OR
692 // - are now computing for a smaller or equal StopAt.
693 unsigned SavedResult = I->second.first;
694 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000695 if (SavedResult != UINT_MAX)
696 return SavedResult + CurrentPenalty;
697 else if (StopAt <= SavedStopAt)
698 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000699 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000700
701 unsigned NoBreak = calcPenalty(State, false, StopAt);
702 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
703 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000704
705 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
706 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000707 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000708
709 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 }
711
Daniel Jasperf7935112012-12-03 18:12:45 +0000712 FormatStyle Style;
713 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000714 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000715 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000716 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000718
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000719 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000720 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000721 StateMap Memory;
722
Daniel Jasperf7935112012-12-03 18:12:45 +0000723 OptimizationParameters Parameters;
724};
725
726/// \brief Determines extra information about the tokens comprising an
727/// \c UnwrappedLine.
728class TokenAnnotator {
729public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000730 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
731 AnnotatedLine &Line)
732 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000733
734 /// \brief A parser that gathers additional information about tokens.
735 ///
736 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
737 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
738 /// into template parameter lists.
739 class AnnotatingParser {
740 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000741 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000742 : CurrentToken(&RootToken), KeywordVirtualFound(false),
743 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000744
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000745 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000746 if (CurrentToken == NULL)
747 return false;
748 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000749 while (CurrentToken != NULL) {
750 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000751 Left->MatchingParen = CurrentToken;
752 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000753 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000754 next();
755 return true;
756 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000757 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
758 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000760 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
761 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000763 if (!consumeToken())
764 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 }
766 return false;
767 }
768
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000769 bool parseParens() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000770 if (CurrentToken == NULL)
771 return false;
772 AnnotatedToken *Left = CurrentToken->Parent;
773 if (CurrentToken->is(tok::caret))
774 Left->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000775 while (CurrentToken != NULL) {
776 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000777 Left->MatchingParen = CurrentToken;
778 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000779 next();
780 return true;
781 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000782 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000783 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000784 if (!consumeToken())
785 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000786 }
787 return false;
788 }
789
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000790 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000791 if (!CurrentToken)
792 return false;
793
794 // A '[' could be an index subscript (after an indentifier or after
795 // ')' or ']'), or it could be the start of an Objective-C method
796 // expression.
797 AnnotatedToken *LSquare = CurrentToken->Parent;
798 bool StartsObjCMethodExpr =
799 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
800 LSquare->Parent->is(tok::l_square) ||
801 LSquare->Parent->is(tok::l_paren) ||
802 LSquare->Parent->is(tok::kw_return) ||
803 LSquare->Parent->is(tok::kw_throw) ||
804 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
805 true, true) > prec::Unknown;
806
807 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
808 if (StartsObjCMethodExpr) {
809 ColonIsObjCMethodExpr = true;
810 LSquare->Type = TT_ObjCMethodExpr;
811 }
812
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000813 while (CurrentToken != NULL) {
814 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000815 if (StartsObjCMethodExpr) {
816 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
817 CurrentToken->Type = TT_ObjCMethodExpr;
818 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000819 next();
820 return true;
821 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000822 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000824 if (!consumeToken())
825 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000826 }
827 return false;
828 }
829
Daniel Jasper83a54d22013-01-10 09:26:47 +0000830 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000831 // Lines are fine to end with '{'.
832 if (CurrentToken == NULL)
833 return true;
834 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000835 while (CurrentToken != NULL) {
836 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000837 Left->MatchingParen = CurrentToken;
838 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000839 next();
840 return true;
841 }
842 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
843 return false;
844 if (!consumeToken())
845 return false;
846 }
Daniel Jasper83a54d22013-01-10 09:26:47 +0000847 return true;
848 }
849
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000850 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000851 while (CurrentToken != NULL) {
852 if (CurrentToken->is(tok::colon)) {
853 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000854 next();
855 return true;
856 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000857 if (!consumeToken())
858 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000859 }
860 return false;
861 }
862
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000863 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
865 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000866 next();
867 if (!parseAngle())
868 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000869 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000870 parseLine();
871 return true;
872 }
873 return false;
874 }
875
Daniel Jasperc0880a92013-01-04 18:52:56 +0000876 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000877 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000878 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000879 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000880 case tok::plus:
881 case tok::minus:
882 // At the start of the line, +/- specific ObjectiveC method
883 // declarations.
884 if (Tok->Parent == NULL)
885 Tok->Type = TT_ObjCMethodSpecifier;
886 break;
Nico Webera7252d82013-01-12 06:18:40 +0000887 case tok::colon:
888 // Colons from ?: are handled in parseConditional().
889 if (ColonIsObjCMethodExpr)
890 Tok->Type = TT_ObjCMethodExpr;
891 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000892 case tok::l_paren: {
Daniel Jasper25837aa2013-01-14 14:14:23 +0000893 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
894 TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000895 if (!parseParens())
896 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000897 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
898 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000899 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000900 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
901 CurrentToken->Type = TT_ObjCSelectorStart;
902 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000903 }
Nico Weber9efe2912013-01-10 23:11:41 +0000904 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000905 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000906 if (!parseSquare())
907 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000908 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000909 case tok::l_brace:
910 if (!parseBrace())
911 return false;
912 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000913 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000914 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000916 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 Tok->Type = TT_BinaryOperator;
918 CurrentToken = Tok;
919 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 }
921 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000922 case tok::r_paren:
923 case tok::r_square:
924 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000925 case tok::r_brace:
926 // Lines can start with '}'.
927 if (Tok->Parent != NULL)
928 return false;
929 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000930 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000931 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000932 break;
933 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000934 if (CurrentToken->is(tok::l_paren)) {
935 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000936 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000937 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
938 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000939 next();
940 }
941 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000942 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
943 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000944 next();
945 }
946 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000947 break;
948 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000949 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000950 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000951 case tok::kw_template:
952 parseTemplateDeclaration();
953 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000954 default:
955 break;
956 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000957 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 }
959
Daniel Jasper050948a52012-12-21 17:58:39 +0000960 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000961 next();
962 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
963 next();
964 while (CurrentToken != NULL) {
965 CurrentToken->Type = TT_ImplicitStringLiteral;
966 next();
967 }
968 } else {
969 while (CurrentToken != NULL) {
970 next();
971 }
972 }
973 }
974
975 void parseWarningOrError() {
976 next();
977 // We still want to format the whitespace left of the first token of the
978 // warning or error.
979 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000980 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000981 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +0000982 next();
983 }
984 }
985
986 void parsePreprocessorDirective() {
987 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000988 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000989 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000990 // Hashes in the middle of a line can lead to any strange token
991 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000992 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000993 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000994 switch (
995 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000996 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000997 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000998 parseIncludeDirective();
999 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001000 case tok::pp_error:
1001 case tok::pp_warning:
1002 parseWarningOrError();
1003 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001004 default:
1005 break;
1006 }
1007 }
1008
Daniel Jasperda16db32013-01-07 10:48:50 +00001009 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001011 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001012 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001013 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001014 while (CurrentToken != NULL) {
1015 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001016 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001017 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001018 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001019 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001020 if (KeywordVirtualFound)
1021 return LT_VirtualFunctionDecl;
1022 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 }
1024
1025 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001026 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1027 CurrentToken = &CurrentToken->Children[0];
1028 else
1029 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 }
1031
1032 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001033 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001034 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001035 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 };
1037
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001038 void calculateExtraInformation(AnnotatedToken &Current) {
1039 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1040
Manuel Klimek52b15152013-01-09 15:25:02 +00001041 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001042 Current.MustBreakBefore = true;
1043 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001044 if (Current.Type == TT_LineComment) {
1045 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001046 } else if (Current.Parent->Type == TT_LineComment ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001047 (Current.is(tok::string_literal) &&
1048 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001049 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001050 } else {
1051 Current.MustBreakBefore = false;
1052 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001053 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001055 if (Current.MustBreakBefore)
1056 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1057 else
1058 Current.TotalLength = Current.Parent->TotalLength +
1059 Current.FormatTok.TokenLength +
1060 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001061 if (!Current.Children.empty())
1062 calculateExtraInformation(Current.Children[0]);
1063 }
1064
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001065 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001066 AnnotatingParser Parser(Line.First);
1067 Line.Type = Parser.parseLine();
1068 if (Line.Type == LT_Invalid)
1069 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001070
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001071 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001072
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001073 if (Line.First.Type == TT_ObjCMethodSpecifier)
1074 Line.Type = LT_ObjCMethodDecl;
1075 else if (Line.First.Type == TT_ObjCDecl)
1076 Line.Type = LT_ObjCDecl;
1077 else if (Line.First.Type == TT_ObjCProperty)
1078 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001079
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001080 Line.First.SpaceRequiredBefore = true;
1081 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1082 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001083
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001084 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001085 if (!Line.First.Children.empty())
1086 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001087 }
1088
1089private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001090 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1091 if (getPrecedence(Current) == prec::Assignment ||
1092 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1093 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001094
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001095 if (Current.Type == TT_Unknown) {
1096 if (Current.is(tok::star) || Current.is(tok::amp)) {
1097 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001098 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1099 Current.is(tok::caret)) {
1100 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001101 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1102 Current.Type = determineIncrementUsage(Current);
1103 } else if (Current.is(tok::exclaim)) {
1104 Current.Type = TT_UnaryOperator;
1105 } else if (isBinaryOperator(Current)) {
1106 Current.Type = TT_BinaryOperator;
1107 } else if (Current.is(tok::comment)) {
1108 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1109 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001110 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001111 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001113 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001114 } else if (Current.is(tok::r_paren) &&
1115 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001116 Current.Parent->Type == TT_TemplateCloser) &&
1117 (Current.Children.empty() ||
1118 (Current.Children[0].isNot(tok::equal) &&
1119 Current.Children[0].isNot(tok::semi) &&
1120 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001121 // FIXME: We need to get smarter and understand more cases of casts.
1122 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001123 } else if (Current.is(tok::at) && Current.Children.size()) {
1124 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1125 case tok::objc_interface:
1126 case tok::objc_implementation:
1127 case tok::objc_protocol:
1128 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001129 break;
1130 case tok::objc_property:
1131 Current.Type = TT_ObjCProperty;
1132 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001133 default:
1134 break;
1135 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001136 }
1137 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001138
1139 if (!Current.Children.empty())
1140 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001141 }
1142
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001143 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001144 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001145 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001146 }
1147
Daniel Jasper71945272013-01-15 14:27:39 +00001148 /// \brief Returns the previous token ignoring comments.
1149 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1150 const AnnotatedToken *PrevToken = Tok.Parent;
1151 while (PrevToken != NULL && PrevToken->is(tok::comment))
1152 PrevToken = PrevToken->Parent;
1153 return PrevToken;
1154 }
1155
1156 /// \brief Returns the next token ignoring comments.
1157 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1158 if (Tok.Children.empty())
1159 return NULL;
1160 const AnnotatedToken *NextToken = &Tok.Children[0];
1161 while (NextToken->is(tok::comment)) {
1162 if (NextToken->Children.empty())
1163 return NULL;
1164 NextToken = &NextToken->Children[0];
1165 }
1166 return NextToken;
1167 }
1168
1169 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001170 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001171 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1172 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001173 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001174
1175 const AnnotatedToken *NextToken = getNextToken(Tok);
1176 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001177 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001178
Daniel Jasper71945272013-01-15 14:27:39 +00001179 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1180 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1181 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1182 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001183 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001184 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001185
Daniel Jasper71945272013-01-15 14:27:39 +00001186 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1187 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1188 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1189 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1190 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1191 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1192 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001193 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001194
Daniel Jasper71945272013-01-15 14:27:39 +00001195 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1196 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001197 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001198
Daniel Jasper426702d2012-12-05 07:51:39 +00001199 // It is very unlikely that we are going to find a pointer or reference type
1200 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001201 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001202 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001203
Daniel Jasperda16db32013-01-07 10:48:50 +00001204 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001205 }
1206
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001207 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001208 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1209 if (PrevToken == NULL)
1210 return TT_UnaryOperator;
1211
Daniel Jasper8dd40472012-12-21 09:41:31 +00001212 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001213 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1214 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1215 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1216 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1217 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001218 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001219
1220 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001221 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001222 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001223
1224 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001225 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001226 }
1227
1228 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001229 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001230 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1231 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001232 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001233 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1234 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001235 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001236
Daniel Jasperda16db32013-01-07 10:48:50 +00001237 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001238 }
1239
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001240 bool spaceRequiredBetween(const AnnotatedToken &Left,
1241 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001242 if (Right.is(tok::hashhash))
1243 return Left.is(tok::hash);
1244 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1245 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001246 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1247 return false;
Nico Webera6087752013-01-10 20:12:55 +00001248 if (Right.is(tok::less) &&
1249 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001250 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001251 return true;
1252 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1253 return false;
1254 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1255 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001256 if (Left.is(tok::at) &&
1257 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1258 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001259 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1260 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001261 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001262 if (Left.is(tok::coloncolon))
1263 return false;
1264 if (Right.is(tok::coloncolon))
1265 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001266 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1267 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001268 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001269 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001270 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1271 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001272 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001273 return Right.FormatTok.Tok.isLiteral() ||
1274 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001275 if (Right.is(tok::star) && Left.is(tok::l_paren))
1276 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001277 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1278 return false;
1279 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001280 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001281 if (Left.is(tok::period) || Right.is(tok::period))
1282 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001283 if (Left.is(tok::colon))
1284 return Left.Type != TT_ObjCMethodExpr;
1285 if (Right.is(tok::colon))
1286 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001287 if (Left.is(tok::l_paren))
1288 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001289 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001290 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001291 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001292 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001293 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1294 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001295 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001296 if (Left.is(tok::at) &&
1297 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001298 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001299 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1300 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001301 return true;
1302 }
1303
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001304 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001305 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001306 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1307 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001308 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001309 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001310 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001311 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001312 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1313 if (Tok.Type == TT_ObjCSelectorStart)
1314 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001315 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001316 // Don't space between ')' and <id>
1317 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001318 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001319 // Don't space between ':' and '('
1320 return false;
1321 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001322 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001323 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1324 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001325
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001326 if (Tok.Parent->is(tok::comma))
1327 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001328 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001329 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001330 if (Tok.Type == TT_OverloadedOperator)
1331 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001332 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001333 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001334 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001335 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001336 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001337 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001338 if (Tok.Parent->Type == TT_UnaryOperator ||
1339 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001340 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001341 if (Tok.Type == TT_UnaryOperator)
1342 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001343 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1344 (Tok.Parent->isNot(tok::colon) ||
1345 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001346 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1347 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001348 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1349 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001350 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001351 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001352 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001353 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001354 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001355 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001356 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001357 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001358 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001359 }
1360
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001361 bool canBreakBefore(const AnnotatedToken &Right) {
1362 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001363 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001364 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1365 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001366 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001367 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1368 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001369 // Don't break this identifier as ':' or identifier
1370 // before it will break.
1371 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001372 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1373 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001374 // Don't break at ':' if identifier before it can beak.
1375 return false;
1376 }
Nico Webera7252d82013-01-12 06:18:40 +00001377 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1378 return false;
1379 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1380 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001381 if (isObjCSelectorName(Right))
1382 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001383 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001384 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001385 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001386 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001387 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001388 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001389 return false;
1390
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001391 if (Right.is(tok::comment))
Daniel Jasper942ee722013-01-13 16:10:20 +00001392 // We rely on MustBreakBefore being set correctly here as we should not
1393 // change the "binding" behavior of a comment.
1394 return false;
1395
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001396 // We only break before r_brace if there was a corresponding break before
1397 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1398 if (Right.is(tok::r_brace))
1399 return false;
1400
Daniel Jasper71945272013-01-15 14:27:39 +00001401 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001402 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001403 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1404 Left.is(tok::comma) || Right.is(tok::lessless) ||
1405 Right.is(tok::arrow) || Right.is(tok::period) ||
1406 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001407 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1408 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1409 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001410 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001411 }
1412
Daniel Jasperf7935112012-12-03 18:12:45 +00001413 FormatStyle Style;
1414 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001415 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001416 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001417};
1418
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001419class LexerBasedFormatTokenSource : public FormatTokenSource {
1420public:
1421 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001422 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001423 IdentTable(Lex.getLangOpts()) {
1424 Lex.SetKeepWhitespaceMode(true);
1425 }
1426
1427 virtual FormatToken getNextToken() {
1428 if (GreaterStashed) {
1429 FormatTok.NewlinesBefore = 0;
1430 FormatTok.WhiteSpaceStart =
1431 FormatTok.Tok.getLocation().getLocWithOffset(1);
1432 FormatTok.WhiteSpaceLength = 0;
1433 GreaterStashed = false;
1434 return FormatTok;
1435 }
1436
1437 FormatTok = FormatToken();
1438 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001439 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001440 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001441 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1442 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001443
1444 // Consume and record whitespace until we find a significant token.
1445 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001446 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001447 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1448 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001449 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1450
1451 if (FormatTok.Tok.is(tok::eof))
1452 return FormatTok;
1453 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001454 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001455 }
Manuel Klimekef920692013-01-07 07:56:50 +00001456
1457 // Now FormatTok is the next non-whitespace token.
1458 FormatTok.TokenLength = Text.size();
1459
Manuel Klimek1abf7892013-01-04 23:34:14 +00001460 // In case the token starts with escaped newlines, we want to
1461 // take them into account as whitespace - this pattern is quite frequent
1462 // in macro definitions.
1463 // FIXME: What do we want to do with other escaped spaces, and escaped
1464 // spaces or newlines in the middle of tokens?
1465 // FIXME: Add a more explicit test.
1466 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001467 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001468 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001469 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001470 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001471 }
1472
1473 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001474 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001475 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001476 FormatTok.Tok.setKind(Info.getTokenID());
1477 }
1478
1479 if (FormatTok.Tok.is(tok::greatergreater)) {
1480 FormatTok.Tok.setKind(tok::greater);
1481 GreaterStashed = true;
1482 }
1483
1484 return FormatTok;
1485 }
1486
1487private:
1488 FormatToken FormatTok;
1489 bool GreaterStashed;
1490 Lexer &Lex;
1491 SourceManager &SourceMgr;
1492 IdentifierTable IdentTable;
1493
1494 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001495 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001496 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1497 Tok.getLength());
1498 }
1499};
1500
Daniel Jasperf7935112012-12-03 18:12:45 +00001501class Formatter : public UnwrappedLineConsumer {
1502public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001503 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1504 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001505 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001506 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001507 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001508
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001509 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001510
Daniel Jasperf7935112012-12-03 18:12:45 +00001511 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001512 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001513 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001514 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001515 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001516 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1517 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1518 Annotator.annotate();
1519 }
1520 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1521 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001522 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001523 const AnnotatedLine &TheLine = *I;
1524 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1525 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1526 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001527 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001528 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001529 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001530 TheLine.First, Replaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001531 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001532 PreviousEndOfLineColumn = Formatter.format();
1533 } else {
1534 // If we did not reformat this unwrapped line, the column at the end of
1535 // the last token is unchanged - thus, we can calculate the end of the
1536 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001537 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001538 SourceMgr.getSpellingColumnNumber(
1539 TheLine.Last->FormatTok.Tok.getLocation()) +
1540 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1541 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001542 1;
1543 }
1544 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001545 return Replaces;
1546 }
1547
1548private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001549 /// \brief Tries to merge lines into one.
1550 ///
1551 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1552 /// if possible; note that \c I will be incremented when lines are merged.
1553 ///
1554 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001555 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001556 std::vector<AnnotatedLine>::iterator &I,
1557 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001558 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1559
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001560 // We can never merge stuff if there are trailing line comments.
1561 if (I->Last->Type == TT_LineComment)
1562 return;
1563
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001564 // Check whether the UnwrappedLine can be put onto a single line. If
1565 // so, this is bound to be the optimal solution (by definition) and we
1566 // don't need to analyze the entire solution space.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001567 if (I->Last->TotalLength >= Limit)
1568 return;
1569 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasperc36492b2013-01-16 07:02:34 +00001570
Daniel Jasper25837aa2013-01-14 14:14:23 +00001571 if (I + 1 == E)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001572 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001573
Daniel Jasper25837aa2013-01-14 14:14:23 +00001574 if (I->Last->is(tok::l_brace)) {
1575 tryMergeSimpleBlock(I, E, Limit);
1576 } else if (I->First.is(tok::kw_if)) {
1577 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001578 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1579 I->First.FormatTok.IsFirst)) {
1580 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001581 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001582 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001583 }
1584
Daniel Jasper39825ea2013-01-14 15:40:57 +00001585 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1586 std::vector<AnnotatedLine>::iterator E,
1587 unsigned Limit) {
1588 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001589 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1590 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001591 if (I + 2 != E && (I + 2)->InPPDirective &&
1592 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1593 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001594 if ((I + 1)->Last->TotalLength > Limit)
1595 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001596 join(Line, *(++I));
1597 }
1598
Daniel Jasper25837aa2013-01-14 14:14:23 +00001599 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1600 std::vector<AnnotatedLine>::iterator E,
1601 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001602 if (!Style.AllowShortIfStatementsOnASingleLine)
1603 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001604 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001605 if (Line.Last->isNot(tok::r_paren))
1606 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001607 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001608 return;
1609 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1610 return;
1611 // Only inline simple if's (no nested if or else).
1612 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1613 return;
1614 join(Line, *(++I));
1615 }
1616
1617 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1618 std::vector<AnnotatedLine>::iterator E,
1619 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001620 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001621 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1622 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001623
1624 // First, check that the current line allows merging. This is the case if
1625 // we're not in a control flow statement and the last token is an opening
1626 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001627 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001628 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001629 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1630 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1631 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1632 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001633 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001634 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1635 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001636 if (!AllowedTokens)
1637 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001638
1639 // Second, check that the next line does not contain any braces - if it
1640 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001641 const AnnotatedToken *Tok = &(I + 1)->First;
1642 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001643 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001644 do {
1645 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001646 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001647 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1648 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001649
1650 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001651 Tok = &(I + 2)->First;
1652 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1653 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001654 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001655
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001656 // If the merged line fits, we use that instead and skip the next two lines.
1657 Line.Last->Children.push_back((I + 1)->First);
1658 while (!Line.Last->Children.empty()) {
1659 Line.Last->Children[0].Parent = Line.Last;
1660 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001661 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001662
1663 join(Line, *(I + 1));
1664 join(Line, *(I + 2));
1665 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001666 }
1667
1668 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1669 unsigned Limit) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001670 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001671 }
1672
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001673 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1674 A.Last->Children.push_back(B.First);
1675 while (!A.Last->Children.empty()) {
1676 A.Last->Children[0].Parent = A.Last;
1677 A.Last = &A.Last->Children[0];
1678 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001679 }
1680
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001681 bool touchesRanges(const AnnotatedLine &TheLine) {
1682 const FormatToken *First = &TheLine.First.FormatTok;
1683 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001684 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001685 First->Tok.getLocation(),
1686 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001687 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001688 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1689 Ranges[i].getBegin()) &&
1690 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1691 LineRange.getBegin()))
1692 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001693 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001694 return false;
1695 }
1696
1697 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001698 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001699 }
1700
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001701 /// \brief Add a new line and the required indent before the first Token
1702 /// of the \c UnwrappedLine if there was no structural parsing error.
1703 /// Returns the indent level of the \c UnwrappedLine.
1704 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1705 bool InPPDirective,
1706 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001707 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001708 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1709 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1710
1711 unsigned Newlines = std::min(Tok.NewlinesBefore,
1712 Style.MaxEmptyLinesToKeep + 1);
1713 if (Newlines == 0 && !Tok.IsFirst)
1714 Newlines = 1;
1715 unsigned Indent = Level * 2;
1716
1717 bool IsAccessModifier = false;
1718 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1719 RootToken.is(tok::kw_private))
1720 IsAccessModifier = true;
1721 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1722 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1723 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1724 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1725 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1726 IsAccessModifier = true;
1727
1728 if (IsAccessModifier &&
1729 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1730 Indent += Style.AccessModifierOffset;
1731 if (!InPPDirective || Tok.HasUnescapedNewline) {
1732 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1733 } else {
1734 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1735 SourceMgr, Replaces);
1736 }
1737 return Indent;
1738 }
1739
Alexander Kornienko116ba682013-01-14 11:34:14 +00001740 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001741 FormatStyle Style;
1742 Lexer &Lex;
1743 SourceManager &SourceMgr;
1744 tooling::Replacements Replaces;
1745 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001746 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001747 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001748};
1749
1750tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1751 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001752 std::vector<CharSourceRange> Ranges,
1753 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001754 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001755 OwningPtr<DiagnosticConsumer> DiagPrinter;
1756 if (DiagClient == 0) {
1757 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1758 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1759 DiagClient = DiagPrinter.get();
1760 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001761 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001762 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001763 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001764 Diagnostics.setSourceManager(&SourceMgr);
1765 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001766 return formatter.format();
1767}
1768
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001769LangOptions getFormattingLangOpts() {
1770 LangOptions LangOpts;
1771 LangOpts.CPlusPlus = 1;
1772 LangOpts.CPlusPlus11 = 1;
1773 LangOpts.Bool = 1;
1774 LangOpts.ObjC1 = 1;
1775 LangOpts.ObjC2 = 1;
1776 return LangOpts;
1777}
1778
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001779} // namespace format
1780} // namespace clang