blob: 108ae7a73621f4781d544c25797534d878583e40 [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 Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
63 LT_PreprocessorDirective,
64 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000065 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000066 LT_ObjCMethodDecl,
67 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000068};
69
Daniel Jasper7c85fde2013-01-08 14:56:18 +000070class AnnotatedToken {
71public:
72 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000073 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
74 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper9278eb92013-01-16 14:59:02 +000075 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000076
Daniel Jasper25837aa2013-01-14 14:14:23 +000077 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
78 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
79
Daniel Jasper7c85fde2013-01-08 14:56:18 +000080 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
81 return FormatTok.Tok.isObjCAtKeyword(Kind);
82 }
83
84 FormatToken FormatTok;
85
Daniel Jasperf7935112012-12-03 18:12:45 +000086 TokenType Type;
87
Daniel Jasperf7935112012-12-03 18:12:45 +000088 bool SpaceRequiredBefore;
89 bool CanBreakBefore;
90 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000091
92 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000093
Daniel Jasper9278eb92013-01-16 14:59:02 +000094 AnnotatedToken *MatchingParen;
95
Daniel Jaspera67a8f02013-01-16 10:41:46 +000096 /// \brief The total length of the line up to and including this token.
97 unsigned TotalLength;
98
Daniel Jasper7c85fde2013-01-08 14:56:18 +000099 std::vector<AnnotatedToken> Children;
100 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000101
102 const AnnotatedToken *getPreviousNoneComment() const {
103 AnnotatedToken *Tok = Parent;
104 while (Tok != NULL && Tok->is(tok::comment))
105 Tok = Tok->Parent;
106 return Tok;
107 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000108};
109
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000110class AnnotatedLine {
111public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000112 AnnotatedLine(const UnwrappedLine &Line)
113 : First(Line.Tokens.front()), Level(Line.Level),
114 InPPDirective(Line.InPPDirective) {
115 assert(!Line.Tokens.empty());
116 AnnotatedToken *Current = &First;
117 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
118 E = Line.Tokens.end();
119 I != E; ++I) {
120 Current->Children.push_back(*I);
121 Current->Children[0].Parent = Current;
122 Current = &Current->Children[0];
123 }
124 Last = Current;
125 }
126 AnnotatedLine(const AnnotatedLine &Other)
127 : First(Other.First), Type(Other.Type), Level(Other.Level),
128 InPPDirective(Other.InPPDirective) {
129 Last = &First;
130 while (!Last->Children.empty()) {
131 Last->Children[0].Parent = Last;
132 Last = &Last->Children[0];
133 }
134 }
135
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000136 AnnotatedToken First;
137 AnnotatedToken *Last;
138
139 LineType Type;
140 unsigned Level;
141 bool InPPDirective;
142};
143
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000144static prec::Level getPrecedence(const AnnotatedToken &Tok) {
145 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000146}
147
Daniel Jasperf7935112012-12-03 18:12:45 +0000148FormatStyle getLLVMStyle() {
149 FormatStyle LLVMStyle;
150 LLVMStyle.ColumnLimit = 80;
151 LLVMStyle.MaxEmptyLinesToKeep = 1;
152 LLVMStyle.PointerAndReferenceBindToType = false;
153 LLVMStyle.AccessModifierOffset = -2;
154 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000155 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000156 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000157 LLVMStyle.BinPackParameters = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000158 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000160 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000161 return LLVMStyle;
162}
163
164FormatStyle getGoogleStyle() {
165 FormatStyle GoogleStyle;
166 GoogleStyle.ColumnLimit = 80;
167 GoogleStyle.MaxEmptyLinesToKeep = 1;
168 GoogleStyle.PointerAndReferenceBindToType = true;
169 GoogleStyle.AccessModifierOffset = -1;
170 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000171 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000172 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000173 GoogleStyle.BinPackParameters = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000174 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000175 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000176 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000177 return GoogleStyle;
178}
179
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000180FormatStyle getChromiumStyle() {
181 FormatStyle ChromiumStyle = getGoogleStyle();
182 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
183 return ChromiumStyle;
184}
185
Daniel Jasperf7935112012-12-03 18:12:45 +0000186struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000187 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000188 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000189 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000190};
191
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000192/// \brief Replaces the whitespace in front of \p Tok. Only call once for
193/// each \c FormatToken.
194static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
195 unsigned Spaces, const FormatStyle &Style,
196 SourceManager &SourceMgr,
197 tooling::Replacements &Replaces) {
198 Replaces.insert(tooling::Replacement(
199 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
200 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
201}
202
203/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
204/// backslashes to escape newlines inside a preprocessor directive.
205///
206/// This function and \c replaceWhitespace have the same behavior if
207/// \c Newlines == 0.
208static void replacePPWhitespace(
209 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
210 unsigned WhitespaceStartColumn, const FormatStyle &Style,
211 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
212 std::string NewLineText;
213 if (NewLines > 0) {
214 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
215 WhitespaceStartColumn);
216 for (unsigned i = 0; i < NewLines; ++i) {
217 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
218 NewLineText += "\\\n";
219 Offset = 0;
220 }
221 }
222 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
223 Tok.FormatTok.WhiteSpaceLength,
224 NewLineText + std::string(Spaces, ' ')));
225}
226
Nico Weberc9d73612013-01-12 22:48:47 +0000227/// \brief Returns if a token is an Objective-C selector name.
228///
Nico Weber92c05392013-01-12 22:51:13 +0000229/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000230static bool isObjCSelectorName(const AnnotatedToken &Tok) {
231 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
232 Tok.Children[0].is(tok::colon) &&
233 Tok.Children[0].Type == TT_ObjCMethodExpr;
234}
235
Daniel Jasperf7935112012-12-03 18:12:45 +0000236class UnwrappedLineFormatter {
237public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000238 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000239 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000240 const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000241 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000242 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000243 FirstIndent(FirstIndent), RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000244 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000245 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000246 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000247 }
248
Manuel Klimek1abf7892013-01-04 23:34:14 +0000249 /// \brief Formats an \c UnwrappedLine.
250 ///
251 /// \returns The column after the last token in the last line of the
252 /// \c UnwrappedLine.
253 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000254 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000255 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000256 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000257 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000258 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000259 State.ForLoopVariablePos = 0;
260 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000261 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000262
Manuel Klimek24998102013-01-16 14:55:28 +0000263 DEBUG({
264 DebugTokenState(*State.NextToken);
265 });
266
Daniel Jaspere9de2602012-12-06 09:56:08 +0000267 // The first token has already been indented and thus consumed.
268 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000269
270 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000271 while (State.NextToken != NULL) {
Manuel Klimeka31e58b2013-01-15 16:41:02 +0000272 if (State.NextToken->Type == TT_ImplicitStringLiteral)
273 // We will not touch the rest of the white space in this
274 // \c UnwrappedLine. The returned value can also not matter, as we
275 // cannot continue an top-level implicit string literal on the next
276 // line.
277 return 0;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000278 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000279 addTokenToState(false, false, State);
280 } else {
281 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
282 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000283 DEBUG({
284 if (Break < NoBreak)
285 llvm::errs() << "\n";
286 else
287 llvm::errs() << " ";
288 llvm::errs() << "<";
289 DebugPenalty(Break, Break < NoBreak);
290 llvm::errs() << "/";
291 DebugPenalty(NoBreak, !(Break < NoBreak));
292 llvm::errs() << "> ";
293 DebugTokenState(*State.NextToken);
294 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000295 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000296 if (State.NextToken != NULL &&
297 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
298 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000299 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000300 State.Stack.back().BreakAfterComma = true;
301 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000302 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000303 }
Manuel Klimek24998102013-01-16 14:55:28 +0000304 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000305 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000306 }
307
308private:
Manuel Klimek24998102013-01-16 14:55:28 +0000309 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
310 const Token &Tok = AnnotatedTok.FormatTok.Tok;
311 llvm::errs()
312 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
313 Tok.getLength());
314 llvm::errs();
315 }
316
317 void DebugPenalty(unsigned Penalty, bool Winner) {
318 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
319 if (Penalty == UINT_MAX)
320 llvm::errs() << "MAX";
321 else
322 llvm::errs() << Penalty;
323 llvm::errs().resetColor();
324 }
325
Daniel Jasper337816e2013-01-11 10:22:12 +0000326 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000327 ParenState(unsigned Indent, unsigned LastSpace)
328 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000329 BreakBeforeClosingBrace(false), BreakAfterComma(false),
330 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000331
Daniel Jasperf7935112012-12-03 18:12:45 +0000332 /// \brief The position to which a specific parenthesis level needs to be
333 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000334 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000335
Daniel Jaspere9de2602012-12-06 09:56:08 +0000336 /// \brief The position of the last space on each level.
337 ///
338 /// Used e.g. to break like:
339 /// functionCall(Parameter, otherCall(
340 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000342
Daniel Jaspere9de2602012-12-06 09:56:08 +0000343 /// \brief The position the first "<<" operator encountered on each level.
344 ///
345 /// Used to align "<<" operators. 0 if no such operator has been encountered
346 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000347 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000348
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000349 /// \brief Whether a newline needs to be inserted before the block's closing
350 /// brace.
351 ///
352 /// We only want to insert a newline before the closing brace if there also
353 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000354 bool BreakBeforeClosingBrace;
355
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000356 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000357 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000358
Daniel Jasper337816e2013-01-11 10:22:12 +0000359 bool operator<(const ParenState &Other) const {
360 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000361 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 if (LastSpace != Other.LastSpace)
363 return LastSpace < Other.LastSpace;
364 if (FirstLessLess != Other.FirstLessLess)
365 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000366 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
367 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000368 if (BreakAfterComma != Other.BreakAfterComma)
369 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000370 if (HasMultiParameterLine != Other.HasMultiParameterLine)
371 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000372 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000373 }
374 };
375
376 /// \brief The current state when indenting a unwrapped line.
377 ///
378 /// As the indenting tries different combinations this is copied by value.
379 struct LineState {
380 /// \brief The number of used columns in the current line.
381 unsigned Column;
382
383 /// \brief The token that needs to be next formatted.
384 const AnnotatedToken *NextToken;
385
386 /// \brief The parenthesis level of the first token on the current line.
387 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000388
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000389 /// \brief The column of the first variable in a for-loop declaration.
390 ///
391 /// Used to align the second variable if necessary.
392 unsigned ForLoopVariablePos;
393
394 /// \brief \c true if this line contains a continued for-loop section.
395 bool LineContainsContinuedForLoopSection;
396
Daniel Jasper337816e2013-01-11 10:22:12 +0000397 /// \brief A stack keeping track of properties applying to parenthesis
398 /// levels.
399 std::vector<ParenState> Stack;
400
401 /// \brief Comparison operator to be able to used \c LineState in \c map.
402 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000403 if (Other.NextToken != NextToken)
404 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000405 if (Other.Column != Column)
406 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000407 if (Other.StartOfLineLevel != StartOfLineLevel)
408 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000409 if (Other.ForLoopVariablePos != ForLoopVariablePos)
410 return Other.ForLoopVariablePos < ForLoopVariablePos;
411 if (Other.LineContainsContinuedForLoopSection !=
412 LineContainsContinuedForLoopSection)
413 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000414 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000415 }
416 };
417
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000418 /// \brief Appends the next token to \p State and updates information
419 /// necessary for indentation.
420 ///
421 /// Puts the token on the current line if \p Newline is \c true and adds a
422 /// line break and necessary indentation otherwise.
423 ///
424 /// If \p DryRun is \c false, also creates and stores the required
425 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000426 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000427 const AnnotatedToken &Current = *State.NextToken;
428 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000429 assert(State.Stack.size());
430 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000431
432 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000433 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000434 if (Current.is(tok::r_brace)) {
435 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000436 } else if (Current.is(tok::string_literal) &&
437 Previous.is(tok::string_literal)) {
438 State.Column = State.Column - Previous.FormatTok.TokenLength;
439 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000440 State.Stack[ParenLevel].FirstLessLess != 0) {
441 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000442 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000443 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
444 Current.is(tok::period) || Previous.is(tok::question) ||
445 Previous.Type == TT_ConditionalExpr)) {
446 // Indent and extra 4 spaces after if we know the current expression is
447 // continued. Don't do that on the top level, as we already indent 4
448 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000450 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000451 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000452 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000454 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000455 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000456 }
457
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000458 // A line starting with a closing brace is assumed to be correct for the
459 // same level as before the opening brace.
460 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000461
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000462 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000463 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000464
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000465 if (!DryRun) {
466 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000467 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
468 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000469 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000470 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000471 WhitespaceStartColumn, Style, SourceMgr,
472 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000473 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000474
Daniel Jasper337816e2013-01-11 10:22:12 +0000475 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000476 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000477 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000478 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000479 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
480 State.ForLoopVariablePos = State.Column -
481 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000482
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000483 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
484 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000485 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000486
Daniel Jasperf7935112012-12-03 18:12:45 +0000487 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000488 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000489
Daniel Jasperbcab4302013-01-09 10:40:23 +0000490 // FIXME: Do we need to do this for assignments nested in other
491 // expressions?
492 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000493 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000494 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000495 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000496 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000497 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000498 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000499 if (Current.getPreviousNoneComment()->is(tok::comma) &&
500 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000501 State.Stack[ParenLevel].HasMultiParameterLine = true;
502
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000503
Daniel Jasper206df732013-01-07 13:08:40 +0000504 // Top-level spaces that are not part of assignments are exempt as that
505 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000506 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000507 if (Spaces > 0 &&
508 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000509 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000510 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000511
512 // If we break after an {, we should also break before the corresponding }.
513 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000514 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000515
516 // If we are breaking after '(', '{', '<' or ',', we need to break after
517 // future commas as well to avoid bin packing.
518 if (!Style.BinPackParameters && Newline &&
519 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
520 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
521 State.Stack.back().BreakAfterComma = true;
522
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000523 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000524 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000525
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000526 /// \brief Mark the next token as consumed in \p State and modify its stacks
527 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000529 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000531
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
533 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000534
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000535 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000536 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000537 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
538 Current.is(tok::l_brace) ||
539 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000541 if (Current.is(tok::l_brace)) {
542 // FIXME: This does not work with nested static initializers.
543 // Implement a better handling for static initializers and similar
544 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000546 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000547 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000549 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000550 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000551
552 // If the entire set of parameters will not fit on the current line, we
553 // will need to break after commas on this level to avoid bin-packing.
554 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
555 !Current.Children.empty()) {
556 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
557 Current.MatchingParen->TotalLength -
558 Current.Children[0].TotalLength) {
559 State.Stack.back().BreakAfterComma = true;
560 }
561 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000562 }
563
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000564 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000565 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000566 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
567 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
568 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000569 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000571
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 if (State.NextToken->Children.empty())
573 State.NextToken = NULL;
574 else
575 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000576
577 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000578 }
579
Nico Weber49cbc2c2013-01-07 15:15:29 +0000580 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000581 unsigned splitPenalty(const AnnotatedToken &Tok) {
582 const AnnotatedToken &Left = Tok;
583 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000584
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000585 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
586 return 50;
587 if (Left.is(tok::equal) && Right.is(tok::l_brace))
588 return 150;
589
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000590 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000591 if (RootToken.is(tok::kw_for) &&
592 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000593 return 20;
594
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000595 if (Left.is(tok::semi) || Left.is(tok::comma) ||
596 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000598
599 // In Objective-C method expressions, prefer breaking before "param:" over
600 // breaking after it.
601 if (isObjCSelectorName(Right))
602 return 0;
603 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
604 return 20;
605
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000606 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000607 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000608
Daniel Jasper399d24b2013-01-09 07:06:56 +0000609 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
610 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000611 prec::Level Level = getPrecedence(Left);
612
613 // Breaking after an assignment leads to a bad result as the two sides of
614 // the assignment are visually very close together.
615 if (Level == prec::Assignment)
616 return 50;
617
Daniel Jasperde5c2072012-12-24 00:13:23 +0000618 if (Level != prec::Unknown)
619 return Level;
620
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000621 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000622 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000623
Daniel Jasperf7935112012-12-03 18:12:45 +0000624 return 3;
625 }
626
Daniel Jasper2df93312013-01-09 10:16:05 +0000627 unsigned getColumnLimit() {
628 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
629 }
630
Daniel Jasperf7935112012-12-03 18:12:45 +0000631 /// \brief Calculate the number of lines needed to format the remaining part
632 /// of the unwrapped line.
633 ///
634 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000635 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 /// added after the previous token.
637 ///
638 /// \param StopAt is used for optimization. If we can determine that we'll
639 /// definitely need at least \p StopAt additional lines, we already know of a
640 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000641 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000642 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000643 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000644 return 0;
645
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000646 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000648 if (NewLine && !State.NextToken->CanBreakBefore &&
649 !(State.NextToken->is(tok::r_brace) &&
650 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000651 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000652 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000653 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000654 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000655 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000656 State.LineContainsContinuedForLoopSection)
657 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000658 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000659 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000660 State.Stack.back().BreakAfterComma)
661 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000662 // Trying to insert a parameter on a new line if there are already more than
663 // one parameter on the current line is bin packing.
664 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
665 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
666 return UINT_MAX;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000667 if (!NewLine && State.NextToken->Type == TT_CtorInitializerColon)
668 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000669
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000670 unsigned CurrentPenalty = 0;
671 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000672 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000673 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000674 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000675 if (State.Stack.size() < State.StartOfLineLevel &&
676 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000677 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000678 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000679 }
680
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000681 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000682
Daniel Jasper2df93312013-01-09 10:16:05 +0000683 // Exceeding column limit is bad, assign penalty.
684 if (State.Column > getColumnLimit()) {
685 unsigned ExcessCharacters = State.Column - getColumnLimit();
686 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
687 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000688
Daniel Jasperf7935112012-12-03 18:12:45 +0000689 if (StopAt <= CurrentPenalty)
690 return UINT_MAX;
691 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000693 if (I != Memory.end()) {
694 // If this state has already been examined, we can safely return the
695 // previous result if we
696 // - have not hit the optimatization (and thus returned UINT_MAX) OR
697 // - are now computing for a smaller or equal StopAt.
698 unsigned SavedResult = I->second.first;
699 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000700 if (SavedResult != UINT_MAX)
701 return SavedResult + CurrentPenalty;
702 else if (StopAt <= SavedStopAt)
703 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000704 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000705
706 unsigned NoBreak = calcPenalty(State, false, StopAt);
707 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
708 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000709
710 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
711 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000712 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000713
714 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 }
716
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 FormatStyle Style;
718 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000719 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000720 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000721 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000723
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000724 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000725 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000726 StateMap Memory;
727
Daniel Jasperf7935112012-12-03 18:12:45 +0000728 OptimizationParameters Parameters;
729};
730
731/// \brief Determines extra information about the tokens comprising an
732/// \c UnwrappedLine.
733class TokenAnnotator {
734public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000735 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
736 AnnotatedLine &Line)
737 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000738
739 /// \brief A parser that gathers additional information about tokens.
740 ///
741 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
742 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
743 /// into template parameter lists.
744 class AnnotatingParser {
745 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000746 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000747 : CurrentToken(&RootToken), KeywordVirtualFound(false),
748 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000749
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000750 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000751 if (CurrentToken == NULL)
752 return false;
753 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000754 while (CurrentToken != NULL) {
755 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000756 Left->MatchingParen = CurrentToken;
757 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 next();
760 return true;
761 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000762 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
763 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000764 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000765 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
766 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000767 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000768 if (!consumeToken())
769 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000770 }
771 return false;
772 }
773
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000774 bool parseParens() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000775 if (CurrentToken == NULL)
776 return false;
777 AnnotatedToken *Left = CurrentToken->Parent;
778 if (CurrentToken->is(tok::caret))
779 Left->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000780 while (CurrentToken != NULL) {
781 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000782 Left->MatchingParen = CurrentToken;
783 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000784 next();
785 return true;
786 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000787 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000788 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000789 if (!consumeToken())
790 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000791 }
792 return false;
793 }
794
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000795 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000796 if (!CurrentToken)
797 return false;
798
799 // A '[' could be an index subscript (after an indentifier or after
800 // ')' or ']'), or it could be the start of an Objective-C method
801 // expression.
802 AnnotatedToken *LSquare = CurrentToken->Parent;
803 bool StartsObjCMethodExpr =
804 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
805 LSquare->Parent->is(tok::l_square) ||
806 LSquare->Parent->is(tok::l_paren) ||
807 LSquare->Parent->is(tok::kw_return) ||
808 LSquare->Parent->is(tok::kw_throw) ||
809 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
810 true, true) > prec::Unknown;
811
812 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
813 if (StartsObjCMethodExpr) {
814 ColonIsObjCMethodExpr = true;
815 LSquare->Type = TT_ObjCMethodExpr;
816 }
817
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000818 while (CurrentToken != NULL) {
819 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000820 if (StartsObjCMethodExpr) {
821 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
822 CurrentToken->Type = TT_ObjCMethodExpr;
823 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000824 next();
825 return true;
826 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000827 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000828 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000829 if (!consumeToken())
830 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000831 }
832 return false;
833 }
834
Daniel Jasper83a54d22013-01-10 09:26:47 +0000835 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000836 // Lines are fine to end with '{'.
837 if (CurrentToken == NULL)
838 return true;
839 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000840 while (CurrentToken != NULL) {
841 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000842 Left->MatchingParen = CurrentToken;
843 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000844 next();
845 return true;
846 }
847 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
848 return false;
849 if (!consumeToken())
850 return false;
851 }
Daniel Jasper83a54d22013-01-10 09:26:47 +0000852 return true;
853 }
854
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000855 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000856 while (CurrentToken != NULL) {
857 if (CurrentToken->is(tok::colon)) {
858 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000859 next();
860 return true;
861 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000862 if (!consumeToken())
863 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000864 }
865 return false;
866 }
867
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000868 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000869 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
870 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000871 next();
872 if (!parseAngle())
873 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000875 parseLine();
876 return true;
877 }
878 return false;
879 }
880
Daniel Jasperc0880a92013-01-04 18:52:56 +0000881 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000882 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000883 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000884 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000885 case tok::plus:
886 case tok::minus:
887 // At the start of the line, +/- specific ObjectiveC method
888 // declarations.
889 if (Tok->Parent == NULL)
890 Tok->Type = TT_ObjCMethodSpecifier;
891 break;
Nico Webera7252d82013-01-12 06:18:40 +0000892 case tok::colon:
893 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +0000894 if (Tok->Parent->is(tok::r_paren))
895 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +0000896 if (ColonIsObjCMethodExpr)
897 Tok->Type = TT_ObjCMethodExpr;
898 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000899 case tok::l_paren: {
Daniel Jasperc0880a92013-01-04 18:52:56 +0000900 if (!parseParens())
901 return false;
Nico Weber9efe2912013-01-10 23:11:41 +0000902 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000903 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000904 if (!parseSquare())
905 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000906 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000907 case tok::l_brace:
908 if (!parseBrace())
909 return false;
910 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000911 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000912 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000913 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000914 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 Tok->Type = TT_BinaryOperator;
916 CurrentToken = Tok;
917 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000918 }
919 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000920 case tok::r_paren:
921 case tok::r_square:
922 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000923 case tok::r_brace:
924 // Lines can start with '}'.
925 if (Tok->Parent != NULL)
926 return false;
927 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000929 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000930 break;
931 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (CurrentToken->is(tok::l_paren)) {
933 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000934 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000935 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
936 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000937 next();
938 }
939 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000940 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
941 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000942 next();
943 }
944 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000945 break;
946 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000947 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000948 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000949 case tok::kw_template:
950 parseTemplateDeclaration();
951 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000952 default:
953 break;
954 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000955 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 }
957
Daniel Jasper050948a52012-12-21 17:58:39 +0000958 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000959 next();
960 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
961 next();
962 while (CurrentToken != NULL) {
963 CurrentToken->Type = TT_ImplicitStringLiteral;
964 next();
965 }
966 } else {
967 while (CurrentToken != NULL) {
968 next();
969 }
970 }
971 }
972
973 void parseWarningOrError() {
974 next();
975 // We still want to format the whitespace left of the first token of the
976 // warning or error.
977 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000978 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000979 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +0000980 next();
981 }
982 }
983
984 void parsePreprocessorDirective() {
985 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000986 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000987 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000988 // Hashes in the middle of a line can lead to any strange token
989 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000990 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000991 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000992 switch (
993 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000994 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000995 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000996 parseIncludeDirective();
997 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000998 case tok::pp_error:
999 case tok::pp_warning:
1000 parseWarningOrError();
1001 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001002 default:
1003 break;
1004 }
1005 }
1006
Daniel Jasperda16db32013-01-07 10:48:50 +00001007 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001008 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001009 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001010 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001011 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001012 while (CurrentToken != NULL) {
1013 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001014 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001015 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001016 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001018 if (KeywordVirtualFound)
1019 return LT_VirtualFunctionDecl;
1020 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 }
1022
1023 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001024 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1025 CurrentToken = &CurrentToken->Children[0];
1026 else
1027 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001028 }
1029
1030 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001032 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001033 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001034 };
1035
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 void calculateExtraInformation(AnnotatedToken &Current) {
1037 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1038
Manuel Klimek52b15152013-01-09 15:25:02 +00001039 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001040 Current.MustBreakBefore = true;
1041 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001042 if (Current.Type == TT_LineComment) {
1043 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001044 } else if ((Current.Parent->is(tok::comment) &&
1045 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001046 (Current.is(tok::string_literal) &&
1047 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001048 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001049 } else {
1050 Current.MustBreakBefore = false;
1051 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001054 if (Current.MustBreakBefore)
1055 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1056 else
1057 Current.TotalLength = Current.Parent->TotalLength +
1058 Current.FormatTok.TokenLength +
1059 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001060 if (!Current.Children.empty())
1061 calculateExtraInformation(Current.Children[0]);
1062 }
1063
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001064 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001065 AnnotatingParser Parser(Line.First);
1066 Line.Type = Parser.parseLine();
1067 if (Line.Type == LT_Invalid)
1068 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001069
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001070 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001071
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001072 if (Line.First.Type == TT_ObjCMethodSpecifier)
1073 Line.Type = LT_ObjCMethodDecl;
1074 else if (Line.First.Type == TT_ObjCDecl)
1075 Line.Type = LT_ObjCDecl;
1076 else if (Line.First.Type == TT_ObjCProperty)
1077 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001078
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001079 Line.First.SpaceRequiredBefore = true;
1080 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1081 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001082
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001083 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001084 if (!Line.First.Children.empty())
1085 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001086 }
1087
1088private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001089 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1090 if (getPrecedence(Current) == prec::Assignment ||
1091 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1092 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001094 if (Current.Type == TT_Unknown) {
1095 if (Current.is(tok::star) || Current.is(tok::amp)) {
1096 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001097 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1098 Current.is(tok::caret)) {
1099 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001100 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1101 Current.Type = determineIncrementUsage(Current);
1102 } else if (Current.is(tok::exclaim)) {
1103 Current.Type = TT_UnaryOperator;
1104 } else if (isBinaryOperator(Current)) {
1105 Current.Type = TT_BinaryOperator;
1106 } else if (Current.is(tok::comment)) {
1107 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1108 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001109 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001110 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001111 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001112 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001113 } else if (Current.is(tok::r_paren) &&
1114 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001115 Current.Parent->Type == TT_TemplateCloser) &&
1116 (Current.Children.empty() ||
1117 (Current.Children[0].isNot(tok::equal) &&
1118 Current.Children[0].isNot(tok::semi) &&
1119 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001120 // FIXME: We need to get smarter and understand more cases of casts.
1121 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001122 } else if (Current.is(tok::at) && Current.Children.size()) {
1123 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1124 case tok::objc_interface:
1125 case tok::objc_implementation:
1126 case tok::objc_protocol:
1127 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001128 break;
1129 case tok::objc_property:
1130 Current.Type = TT_ObjCProperty;
1131 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001132 default:
1133 break;
1134 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001135 }
1136 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001137
1138 if (!Current.Children.empty())
1139 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001140 }
1141
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001143 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001144 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001145 }
1146
Daniel Jasper71945272013-01-15 14:27:39 +00001147 /// \brief Returns the previous token ignoring comments.
1148 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1149 const AnnotatedToken *PrevToken = Tok.Parent;
1150 while (PrevToken != NULL && PrevToken->is(tok::comment))
1151 PrevToken = PrevToken->Parent;
1152 return PrevToken;
1153 }
1154
1155 /// \brief Returns the next token ignoring comments.
1156 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1157 if (Tok.Children.empty())
1158 return NULL;
1159 const AnnotatedToken *NextToken = &Tok.Children[0];
1160 while (NextToken->is(tok::comment)) {
1161 if (NextToken->Children.empty())
1162 return NULL;
1163 NextToken = &NextToken->Children[0];
1164 }
1165 return NextToken;
1166 }
1167
1168 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001169 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001170 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1171 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001172 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001173
1174 const AnnotatedToken *NextToken = getNextToken(Tok);
1175 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001176 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001177
Daniel Jasper71945272013-01-15 14:27:39 +00001178 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1179 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1180 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1181 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001182 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001183 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001184
Daniel Jasper71945272013-01-15 14:27:39 +00001185 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1186 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1187 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1188 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1189 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1190 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1191 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001192 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001193
Daniel Jasper71945272013-01-15 14:27:39 +00001194 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1195 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001196 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001197
Daniel Jasper426702d2012-12-05 07:51:39 +00001198 // It is very unlikely that we are going to find a pointer or reference type
1199 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001200 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001201 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001202
Daniel Jasperda16db32013-01-07 10:48:50 +00001203 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001204 }
1205
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001206 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001207 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1208 if (PrevToken == NULL)
1209 return TT_UnaryOperator;
1210
Daniel Jasper8dd40472012-12-21 09:41:31 +00001211 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001212 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1213 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1214 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1215 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1216 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001217 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001218
1219 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001220 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001221 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001222
1223 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001224 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001225 }
1226
1227 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001228 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001229 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1230 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001231 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001232 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1233 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001234 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001235
Daniel Jasperda16db32013-01-07 10:48:50 +00001236 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001237 }
1238
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001239 bool spaceRequiredBetween(const AnnotatedToken &Left,
1240 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001241 if (Right.is(tok::hashhash))
1242 return Left.is(tok::hash);
1243 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1244 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001245 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1246 return false;
Nico Webera6087752013-01-10 20:12:55 +00001247 if (Right.is(tok::less) &&
1248 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001249 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001250 return true;
1251 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1252 return false;
1253 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1254 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001255 if (Left.is(tok::at) &&
1256 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1257 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001258 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1259 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001260 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001261 if (Left.is(tok::coloncolon))
1262 return false;
1263 if (Right.is(tok::coloncolon))
1264 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001265 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1266 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001267 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001268 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001269 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1270 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001271 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001272 return Right.FormatTok.Tok.isLiteral() ||
1273 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001274 if (Right.is(tok::star) && Left.is(tok::l_paren))
1275 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001276 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1277 return false;
1278 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001279 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001280 if (Left.is(tok::period) || Right.is(tok::period))
1281 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001282 if (Left.is(tok::colon))
1283 return Left.Type != TT_ObjCMethodExpr;
1284 if (Right.is(tok::colon))
1285 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001286 if (Left.is(tok::l_paren))
1287 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001288 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001289 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001290 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001291 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001292 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1293 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001294 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001295 if (Left.is(tok::at) &&
1296 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001297 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001298 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1299 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001300 return true;
1301 }
1302
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001303 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001304 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001305 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1306 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001307 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001308 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001309 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001310 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001311 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001312 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001313 // Don't space between ')' and <id>
1314 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001315 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001316 // Don't space between ':' and '('
1317 return false;
1318 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001319 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001320 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1321 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001322
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001323 if (Tok.Parent->is(tok::comma))
1324 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001325 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001326 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001327 if (Tok.Type == TT_OverloadedOperator)
1328 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001329 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001330 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001331 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001332 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001333 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001334 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001335 if (Tok.Parent->Type == TT_UnaryOperator ||
1336 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001337 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001338 if (Tok.Type == TT_UnaryOperator)
1339 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001340 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1341 (Tok.Parent->isNot(tok::colon) ||
1342 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001343 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1344 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001345 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1346 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001347 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001348 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001349 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001350 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001351 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001352 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001353 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001354 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001355 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001356 }
1357
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001358 bool canBreakBefore(const AnnotatedToken &Right) {
1359 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001360 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001361 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1362 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001363 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001364 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1365 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001366 // Don't break this identifier as ':' or identifier
1367 // before it will break.
1368 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001369 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1370 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001371 // Don't break at ':' if identifier before it can beak.
1372 return false;
1373 }
Nico Webera7252d82013-01-12 06:18:40 +00001374 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1375 return false;
1376 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1377 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001378 if (isObjCSelectorName(Right))
1379 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001380 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001381 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001382 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001383 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001384 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001385 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001386 return false;
1387
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001388 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001389 // We rely on MustBreakBefore being set correctly here as we should not
1390 // change the "binding" behavior of a comment.
1391 return false;
1392
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001393 // We only break before r_brace if there was a corresponding break before
1394 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1395 if (Right.is(tok::r_brace))
1396 return false;
1397
Daniel Jasper71945272013-01-15 14:27:39 +00001398 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001399 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001400 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1401 Left.is(tok::comma) || Right.is(tok::lessless) ||
1402 Right.is(tok::arrow) || Right.is(tok::period) ||
1403 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001404 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1405 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1406 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001407 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001408 }
1409
Daniel Jasperf7935112012-12-03 18:12:45 +00001410 FormatStyle Style;
1411 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001412 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001413 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001414};
1415
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001416class LexerBasedFormatTokenSource : public FormatTokenSource {
1417public:
1418 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001419 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001420 IdentTable(Lex.getLangOpts()) {
1421 Lex.SetKeepWhitespaceMode(true);
1422 }
1423
1424 virtual FormatToken getNextToken() {
1425 if (GreaterStashed) {
1426 FormatTok.NewlinesBefore = 0;
1427 FormatTok.WhiteSpaceStart =
1428 FormatTok.Tok.getLocation().getLocWithOffset(1);
1429 FormatTok.WhiteSpaceLength = 0;
1430 GreaterStashed = false;
1431 return FormatTok;
1432 }
1433
1434 FormatTok = FormatToken();
1435 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001436 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001437 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001438 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1439 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001440
1441 // Consume and record whitespace until we find a significant token.
1442 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001443 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001444 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1445 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001446 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1447
1448 if (FormatTok.Tok.is(tok::eof))
1449 return FormatTok;
1450 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001451 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001452 }
Manuel Klimekef920692013-01-07 07:56:50 +00001453
1454 // Now FormatTok is the next non-whitespace token.
1455 FormatTok.TokenLength = Text.size();
1456
Manuel Klimek1abf7892013-01-04 23:34:14 +00001457 // In case the token starts with escaped newlines, we want to
1458 // take them into account as whitespace - this pattern is quite frequent
1459 // in macro definitions.
1460 // FIXME: What do we want to do with other escaped spaces, and escaped
1461 // spaces or newlines in the middle of tokens?
1462 // FIXME: Add a more explicit test.
1463 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001464 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001465 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001466 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001467 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001468 }
1469
1470 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001471 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001472 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001473 FormatTok.Tok.setKind(Info.getTokenID());
1474 }
1475
1476 if (FormatTok.Tok.is(tok::greatergreater)) {
1477 FormatTok.Tok.setKind(tok::greater);
1478 GreaterStashed = true;
1479 }
1480
1481 return FormatTok;
1482 }
1483
1484private:
1485 FormatToken FormatTok;
1486 bool GreaterStashed;
1487 Lexer &Lex;
1488 SourceManager &SourceMgr;
1489 IdentifierTable IdentTable;
1490
1491 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001492 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001493 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1494 Tok.getLength());
1495 }
1496};
1497
Daniel Jasperf7935112012-12-03 18:12:45 +00001498class Formatter : public UnwrappedLineConsumer {
1499public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001500 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1501 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001502 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001503 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001504 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001505
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001506 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001507
Daniel Jasperf7935112012-12-03 18:12:45 +00001508 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001509 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001510 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001511 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001512 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001513 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1514 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1515 Annotator.annotate();
1516 }
1517 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1518 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001519 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001520 const AnnotatedLine &TheLine = *I;
1521 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1522 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1523 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001524 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001525 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001526 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001527 TheLine.First, Replaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001528 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001529 PreviousEndOfLineColumn = Formatter.format();
1530 } else {
1531 // If we did not reformat this unwrapped line, the column at the end of
1532 // the last token is unchanged - thus, we can calculate the end of the
1533 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001534 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001535 SourceMgr.getSpellingColumnNumber(
1536 TheLine.Last->FormatTok.Tok.getLocation()) +
1537 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1538 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001539 1;
1540 }
1541 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001542 return Replaces;
1543 }
1544
1545private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001546 /// \brief Tries to merge lines into one.
1547 ///
1548 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1549 /// if possible; note that \c I will be incremented when lines are merged.
1550 ///
1551 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001552 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001553 std::vector<AnnotatedLine>::iterator &I,
1554 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001555 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1556
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001557 // We can never merge stuff if there are trailing line comments.
1558 if (I->Last->Type == TT_LineComment)
1559 return;
1560
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001561 // Check whether the UnwrappedLine can be put onto a single line. If
1562 // so, this is bound to be the optimal solution (by definition) and we
1563 // don't need to analyze the entire solution space.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001564 if (I->Last->TotalLength >= Limit)
1565 return;
1566 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasperc36492b2013-01-16 07:02:34 +00001567
Daniel Jasper25837aa2013-01-14 14:14:23 +00001568 if (I + 1 == E)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001569 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001570
Daniel Jasper25837aa2013-01-14 14:14:23 +00001571 if (I->Last->is(tok::l_brace)) {
1572 tryMergeSimpleBlock(I, E, Limit);
1573 } else if (I->First.is(tok::kw_if)) {
1574 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001575 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1576 I->First.FormatTok.IsFirst)) {
1577 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001578 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001579 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001580 }
1581
Daniel Jasper39825ea2013-01-14 15:40:57 +00001582 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1583 std::vector<AnnotatedLine>::iterator E,
1584 unsigned Limit) {
1585 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001586 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1587 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001588 if (I + 2 != E && (I + 2)->InPPDirective &&
1589 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1590 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001591 if ((I + 1)->Last->TotalLength > Limit)
1592 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001593 join(Line, *(++I));
1594 }
1595
Daniel Jasper25837aa2013-01-14 14:14:23 +00001596 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1597 std::vector<AnnotatedLine>::iterator E,
1598 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001599 if (!Style.AllowShortIfStatementsOnASingleLine)
1600 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001601 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001602 if (Line.Last->isNot(tok::r_paren))
1603 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001604 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001605 return;
1606 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1607 return;
1608 // Only inline simple if's (no nested if or else).
1609 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1610 return;
1611 join(Line, *(++I));
1612 }
1613
1614 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1615 std::vector<AnnotatedLine>::iterator E,
1616 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001617 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001618 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1619 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001620
1621 // First, check that the current line allows merging. This is the case if
1622 // we're not in a control flow statement and the last token is an opening
1623 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001624 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001625 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001626 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1627 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1628 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1629 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001630 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001631 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1632 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001633 if (!AllowedTokens)
1634 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001635
1636 // Second, check that the next line does not contain any braces - if it
1637 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001638 const AnnotatedToken *Tok = &(I + 1)->First;
1639 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001640 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001641 do {
1642 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001643 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001644 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1645 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001646
1647 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001648 Tok = &(I + 2)->First;
1649 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1650 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001651 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001652
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001653 // If the merged line fits, we use that instead and skip the next two lines.
1654 Line.Last->Children.push_back((I + 1)->First);
1655 while (!Line.Last->Children.empty()) {
1656 Line.Last->Children[0].Parent = Line.Last;
1657 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001658 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001659
1660 join(Line, *(I + 1));
1661 join(Line, *(I + 2));
1662 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001663 }
1664
1665 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1666 unsigned Limit) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001667 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001668 }
1669
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001670 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1671 A.Last->Children.push_back(B.First);
1672 while (!A.Last->Children.empty()) {
1673 A.Last->Children[0].Parent = A.Last;
1674 A.Last = &A.Last->Children[0];
1675 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001676 }
1677
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001678 bool touchesRanges(const AnnotatedLine &TheLine) {
1679 const FormatToken *First = &TheLine.First.FormatTok;
1680 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001681 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001682 First->Tok.getLocation(),
1683 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001684 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001685 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1686 Ranges[i].getBegin()) &&
1687 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1688 LineRange.getBegin()))
1689 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001690 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001691 return false;
1692 }
1693
1694 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001695 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001696 }
1697
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001698 /// \brief Add a new line and the required indent before the first Token
1699 /// of the \c UnwrappedLine if there was no structural parsing error.
1700 /// Returns the indent level of the \c UnwrappedLine.
1701 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1702 bool InPPDirective,
1703 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001704 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001705 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1706 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1707
1708 unsigned Newlines = std::min(Tok.NewlinesBefore,
1709 Style.MaxEmptyLinesToKeep + 1);
1710 if (Newlines == 0 && !Tok.IsFirst)
1711 Newlines = 1;
1712 unsigned Indent = Level * 2;
1713
1714 bool IsAccessModifier = false;
1715 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1716 RootToken.is(tok::kw_private))
1717 IsAccessModifier = true;
1718 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1719 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1720 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1721 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1722 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1723 IsAccessModifier = true;
1724
1725 if (IsAccessModifier &&
1726 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1727 Indent += Style.AccessModifierOffset;
1728 if (!InPPDirective || Tok.HasUnescapedNewline) {
1729 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1730 } else {
1731 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1732 SourceMgr, Replaces);
1733 }
1734 return Indent;
1735 }
1736
Alexander Kornienko116ba682013-01-14 11:34:14 +00001737 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001738 FormatStyle Style;
1739 Lexer &Lex;
1740 SourceManager &SourceMgr;
1741 tooling::Replacements Replaces;
1742 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001743 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001744 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001745};
1746
1747tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1748 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001749 std::vector<CharSourceRange> Ranges,
1750 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001751 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001752 OwningPtr<DiagnosticConsumer> DiagPrinter;
1753 if (DiagClient == 0) {
1754 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1755 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1756 DiagClient = DiagPrinter.get();
1757 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001758 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001759 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001760 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001761 Diagnostics.setSourceManager(&SourceMgr);
1762 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001763 return formatter.format();
1764}
1765
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001766LangOptions getFormattingLangOpts() {
1767 LangOptions LangOpts;
1768 LangOpts.CPlusPlus = 1;
1769 LangOpts.CPlusPlus11 = 1;
1770 LangOpts.Bool = 1;
1771 LangOpts.ObjC1 = 1;
1772 LangOpts.ObjC2 = 1;
1773 return LangOpts;
1774}
1775
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001776} // namespace format
1777} // namespace clang