blob: c40aa5387ca9ec908d1fa2ad60bdb1a304a565e7 [file] [log] [blame]
Daniel Jasperbac016b2012-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
19#include "clang/Format/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperbac016b2012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasper71607512013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasper8134e1e2013-01-13 08:12:18 +000037 TT_IncludePath,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Weberbcfdd262013-01-12 06:18:40 +000042 TT_ObjCMethodExpr,
Nico Webercd52bda2013-01-10 23:11:41 +000043 TT_ObjCSelectorStart,
Nico Weber70848232013-01-10 21:30:42 +000044 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000045 TT_OverloadedOperator,
46 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000047 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000048 TT_TemplateCloser,
49 TT_TemplateOpener,
50 TT_TrailingUnaryOperator,
51 TT_UnaryOperator,
52 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000053};
54
55enum LineType {
56 LT_Invalid,
57 LT_Other,
58 LT_PreprocessorDirective,
59 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000060 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000061 LT_ObjCMethodDecl,
62 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000063};
64
Daniel Jasper26f7e782013-01-08 14:56:18 +000065class AnnotatedToken {
66public:
67 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000068 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
69 CanBreakBefore(false), MustBreakBefore(false),
70 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000071
Daniel Jasperfeb18f52013-01-14 14:14:23 +000072 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
73 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
74
Daniel Jasper26f7e782013-01-08 14:56:18 +000075 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
76 return FormatTok.Tok.isObjCAtKeyword(Kind);
77 }
78
79 FormatToken FormatTok;
80
Daniel Jasperbac016b2012-12-03 18:12:45 +000081 TokenType Type;
82
Daniel Jasperbac016b2012-12-03 18:12:45 +000083 bool SpaceRequiredBefore;
84 bool CanBreakBefore;
85 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000086
87 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000088
89 std::vector<AnnotatedToken> Children;
90 AnnotatedToken *Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +000091};
92
Daniel Jasper995e8202013-01-14 13:08:07 +000093class AnnotatedLine {
94public:
95 AnnotatedLine(const FormatToken &FormatTok, unsigned Level,
96 bool InPPDirective)
97 : First(FormatTok), Level(Level), InPPDirective(InPPDirective) {}
98 AnnotatedToken First;
99 AnnotatedToken *Last;
100
101 LineType Type;
102 unsigned Level;
103 bool InPPDirective;
104};
105
Daniel Jasper26f7e782013-01-08 14:56:18 +0000106static prec::Level getPrecedence(const AnnotatedToken &Tok) {
107 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +0000108}
109
Daniel Jasperbac016b2012-12-03 18:12:45 +0000110FormatStyle getLLVMStyle() {
111 FormatStyle LLVMStyle;
112 LLVMStyle.ColumnLimit = 80;
113 LLVMStyle.MaxEmptyLinesToKeep = 1;
114 LLVMStyle.PointerAndReferenceBindToType = false;
115 LLVMStyle.AccessModifierOffset = -2;
116 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000117 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000118 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000119 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000120 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000121 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Webercd52bda2013-01-10 23:11:41 +0000122 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000123 return LLVMStyle;
124}
125
126FormatStyle getGoogleStyle() {
127 FormatStyle GoogleStyle;
128 GoogleStyle.ColumnLimit = 80;
129 GoogleStyle.MaxEmptyLinesToKeep = 1;
130 GoogleStyle.PointerAndReferenceBindToType = true;
131 GoogleStyle.AccessModifierOffset = -1;
132 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000133 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000134 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000135 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000136 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber5f500df2013-01-10 20:12:55 +0000137 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Webercd52bda2013-01-10 23:11:41 +0000138 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000139 return GoogleStyle;
140}
141
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000142FormatStyle getChromiumStyle() {
143 FormatStyle ChromiumStyle = getGoogleStyle();
144 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
145 return ChromiumStyle;
146}
147
Daniel Jasperbac016b2012-12-03 18:12:45 +0000148struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000149 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000150 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000151 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000152};
153
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000154/// \brief Replaces the whitespace in front of \p Tok. Only call once for
155/// each \c FormatToken.
156static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
157 unsigned Spaces, const FormatStyle &Style,
158 SourceManager &SourceMgr,
159 tooling::Replacements &Replaces) {
160 Replaces.insert(tooling::Replacement(
161 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
162 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
163}
164
165/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
166/// backslashes to escape newlines inside a preprocessor directive.
167///
168/// This function and \c replaceWhitespace have the same behavior if
169/// \c Newlines == 0.
170static void replacePPWhitespace(
171 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
172 unsigned WhitespaceStartColumn, const FormatStyle &Style,
173 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
174 std::string NewLineText;
175 if (NewLines > 0) {
176 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
177 WhitespaceStartColumn);
178 for (unsigned i = 0; i < NewLines; ++i) {
179 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
180 NewLineText += "\\\n";
181 Offset = 0;
182 }
183 }
184 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
185 Tok.FormatTok.WhiteSpaceLength,
186 NewLineText + std::string(Spaces, ' ')));
187}
188
Daniel Jasper995e8202013-01-14 13:08:07 +0000189/// \brief Calculates whether the (remaining) \c AnnotatedLine starting with
190/// \p RootToken fits into \p Limit columns on a single line.
191///
192/// If true, sets \p Length to the required length.
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000193static bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit,
194 unsigned *Length = 0) {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000195 unsigned Columns = RootToken.FormatTok.TokenLength;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000196 if (Columns > Limit) return false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000197 const AnnotatedToken *Tok = &RootToken;
198 while (!Tok->Children.empty()) {
199 Tok = &Tok->Children[0];
200 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
201 // A special case for the colon of a constructor initializer as this only
202 // needs to be put on a new line if the line needs to be split.
203 if (Columns > Limit ||
204 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000205 // FIXME: Remove this hack.
206 return false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000207 }
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000208 }
Daniel Jasper995e8202013-01-14 13:08:07 +0000209 if (Length != 0)
210 *Length = Columns;
211 return true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000212}
213
Nico Webere8ccc812013-01-12 22:48:47 +0000214/// \brief Returns if a token is an Objective-C selector name.
215///
Nico Weberea865632013-01-12 22:51:13 +0000216/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Webere8ccc812013-01-12 22:48:47 +0000217static bool isObjCSelectorName(const AnnotatedToken &Tok) {
218 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
219 Tok.Children[0].is(tok::colon) &&
220 Tok.Children[0].Type == TT_ObjCMethodExpr;
221}
222
Daniel Jasperbac016b2012-12-03 18:12:45 +0000223class UnwrappedLineFormatter {
224public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000225 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000226 const AnnotatedLine &Line, unsigned FirstIndent,
Rafael Espindolab14d1ca2013-01-12 14:22:42 +0000227 bool FitsOnALine, const AnnotatedToken &RootToken,
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000228 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000229 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000230 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Rafael Espindolab14d1ca2013-01-12 14:22:42 +0000231 RootToken(RootToken), Replaces(Replaces) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000232 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000233 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000234 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000235 }
236
Manuel Klimekd4397b92013-01-04 23:34:14 +0000237 /// \brief Formats an \c UnwrappedLine.
238 ///
239 /// \returns The column after the last token in the last line of the
240 /// \c UnwrappedLine.
241 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000242 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000243 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000244 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000245 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000246 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000247 State.ForLoopVariablePos = 0;
248 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000249 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000250
251 // The first token has already been indented and thus consumed.
252 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000253
254 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000255 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000256 if (FitsOnALine) {
257 addTokenToState(false, false, State);
258 } else {
259 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
260 unsigned Break = calcPenalty(State, true, NoBreak);
261 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000262 if (State.NextToken != NULL &&
263 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
264 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
265 !fitsIntoLimit(*State.NextToken,
266 getColumnLimit() - State.Column - 1))
267 State.Stack.back().BreakAfterComma = true;
268 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000269 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000271 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272 }
273
274private:
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000275 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000276 ParenState(unsigned Indent, unsigned LastSpace)
277 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
278 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000279
Daniel Jasperbac016b2012-12-03 18:12:45 +0000280 /// \brief The position to which a specific parenthesis level needs to be
281 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000282 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000283
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000284 /// \brief The position of the last space on each level.
285 ///
286 /// Used e.g. to break like:
287 /// functionCall(Parameter, otherCall(
288 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000289 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000290
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000291 /// \brief The position the first "<<" operator encountered on each level.
292 ///
293 /// Used to align "<<" operators. 0 if no such operator has been encountered
294 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000295 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000296
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000297 /// \brief Whether a newline needs to be inserted before the block's closing
298 /// brace.
299 ///
300 /// We only want to insert a newline before the closing brace if there also
301 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000302 bool BreakBeforeClosingBrace;
303
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000304 bool BreakAfterComma;
305
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000306 bool operator<(const ParenState &Other) const {
307 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000308 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000309 if (LastSpace != Other.LastSpace)
310 return LastSpace < Other.LastSpace;
311 if (FirstLessLess != Other.FirstLessLess)
312 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000313 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
314 return BreakBeforeClosingBrace;
Daniel Jasperb3123142013-01-12 07:36:22 +0000315 if (BreakAfterComma != Other.BreakAfterComma)
316 return BreakAfterComma;
317 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000318 }
319 };
320
321 /// \brief The current state when indenting a unwrapped line.
322 ///
323 /// As the indenting tries different combinations this is copied by value.
324 struct LineState {
325 /// \brief The number of used columns in the current line.
326 unsigned Column;
327
328 /// \brief The token that needs to be next formatted.
329 const AnnotatedToken *NextToken;
330
331 /// \brief The parenthesis level of the first token on the current line.
332 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000333
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000334 /// \brief The column of the first variable in a for-loop declaration.
335 ///
336 /// Used to align the second variable if necessary.
337 unsigned ForLoopVariablePos;
338
339 /// \brief \c true if this line contains a continued for-loop section.
340 bool LineContainsContinuedForLoopSection;
341
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000342 /// \brief A stack keeping track of properties applying to parenthesis
343 /// levels.
344 std::vector<ParenState> Stack;
345
346 /// \brief Comparison operator to be able to used \c LineState in \c map.
347 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000348 if (Other.NextToken != NextToken)
349 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000350 if (Other.Column != Column)
351 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000352 if (Other.StartOfLineLevel != StartOfLineLevel)
353 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000354 if (Other.ForLoopVariablePos != ForLoopVariablePos)
355 return Other.ForLoopVariablePos < ForLoopVariablePos;
356 if (Other.LineContainsContinuedForLoopSection !=
357 LineContainsContinuedForLoopSection)
358 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000359 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000360 }
361 };
362
Daniel Jasper20409152012-12-04 14:54:30 +0000363 /// \brief Appends the next token to \p State and updates information
364 /// necessary for indentation.
365 ///
366 /// Puts the token on the current line if \p Newline is \c true and adds a
367 /// line break and necessary indentation otherwise.
368 ///
369 /// If \p DryRun is \c false, also creates and stores the required
370 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000371 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000372 const AnnotatedToken &Current = *State.NextToken;
373 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000374 assert(State.Stack.size());
375 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000376
377 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000378 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000379 if (Current.is(tok::r_brace)) {
380 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000381 } else if (Current.is(tok::string_literal) &&
382 Previous.is(tok::string_literal)) {
383 State.Column = State.Column - Previous.FormatTok.TokenLength;
384 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000385 State.Stack[ParenLevel].FirstLessLess != 0) {
386 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000387 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000388 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
389 Current.is(tok::period) || Previous.is(tok::question) ||
390 Previous.Type == TT_ConditionalExpr)) {
391 // Indent and extra 4 spaces after if we know the current expression is
392 // continued. Don't do that on the top level, as we already indent 4
393 // there.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000394 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000395 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000396 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000397 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000398 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000399 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000400 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000401 }
402
Manuel Klimek2851c162013-01-10 14:36:46 +0000403 // A line starting with a closing brace is assumed to be correct for the
404 // same level as before the opening brace.
405 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000406
Daniel Jasper26f7e782013-01-08 14:56:18 +0000407 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000408 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000409
Manuel Klimek060143e2013-01-02 18:33:23 +0000410 if (!DryRun) {
411 if (!Line.InPPDirective)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000412 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
413 SourceMgr, Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000414 else
Daniel Jasper9c837d02013-01-09 07:06:56 +0000415 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000416 WhitespaceStartColumn, Style, SourceMgr,
417 Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000418 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000419
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000420 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Weberf681fa82013-01-12 07:05:25 +0000421 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000422 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000423 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000424 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
425 State.ForLoopVariablePos = State.Column -
426 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000427
Daniel Jasper26f7e782013-01-08 14:56:18 +0000428 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
429 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000430 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000431
Daniel Jasperbac016b2012-12-03 18:12:45 +0000432 if (!DryRun)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000433 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000434
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000435 // FIXME: Do we need to do this for assignments nested in other
436 // expressions?
437 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000438 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000439 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000440 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000441 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000442 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000443 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000444
Daniel Jasper9cda8002013-01-07 13:08:40 +0000445 // Top-level spaces that are not part of assignments are exempt as that
446 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000447 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000448 if (Spaces > 0 &&
449 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000450 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000451 }
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000452 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000453 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000454 }
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000455 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000456 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457
Daniel Jasper20409152012-12-04 14:54:30 +0000458 /// \brief Mark the next token as consumed in \p State and modify its stacks
459 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000460 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000461 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000462 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000463
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000464 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
465 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000466
Daniel Jaspercf225b62012-12-24 13:43:52 +0000467 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000468 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000469 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
470 Current.is(tok::l_brace) ||
471 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000472 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000473 if (Current.is(tok::l_brace)) {
474 // FIXME: This does not work with nested static initializers.
475 // Implement a better handling for static initializers and similar
476 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000477 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000478 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000479 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000480 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000481 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000482 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000483 }
484
Daniel Jaspercf225b62012-12-24 13:43:52 +0000485 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000486 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000487 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
488 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
489 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000490 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000491 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000492
Daniel Jasper26f7e782013-01-08 14:56:18 +0000493 if (State.NextToken->Children.empty())
494 State.NextToken = NULL;
495 else
496 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000497
498 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000499 }
500
Nico Weberdecf7bc2013-01-07 15:15:29 +0000501 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000502 unsigned splitPenalty(const AnnotatedToken &Tok) {
503 const AnnotatedToken &Left = Tok;
504 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000505
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000506 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
507 return 50;
508 if (Left.is(tok::equal) && Right.is(tok::l_brace))
509 return 150;
510
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000511 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000512 if (RootToken.is(tok::kw_for) &&
513 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000514 return 20;
515
Daniel Jasper26f7e782013-01-08 14:56:18 +0000516 if (Left.is(tok::semi) || Left.is(tok::comma) ||
517 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000518 return 0;
Nico Webere8ccc812013-01-12 22:48:47 +0000519
520 // In Objective-C method expressions, prefer breaking before "param:" over
521 // breaking after it.
522 if (isObjCSelectorName(Right))
523 return 0;
524 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
525 return 20;
526
Daniel Jasper26f7e782013-01-08 14:56:18 +0000527 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000528 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000529
Daniel Jasper9c837d02013-01-09 07:06:56 +0000530 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
531 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000532 prec::Level Level = getPrecedence(Left);
533
534 // Breaking after an assignment leads to a bad result as the two sides of
535 // the assignment are visually very close together.
536 if (Level == prec::Assignment)
537 return 50;
538
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000539 if (Level != prec::Unknown)
540 return Level;
541
Daniel Jasper26f7e782013-01-08 14:56:18 +0000542 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000543 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000544
Daniel Jasperbac016b2012-12-03 18:12:45 +0000545 return 3;
546 }
547
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000548 unsigned getColumnLimit() {
549 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
550 }
551
Daniel Jasperbac016b2012-12-03 18:12:45 +0000552 /// \brief Calculate the number of lines needed to format the remaining part
553 /// of the unwrapped line.
554 ///
555 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000556 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000557 /// added after the previous token.
558 ///
559 /// \param StopAt is used for optimization. If we can determine that we'll
560 /// definitely need at least \p StopAt additional lines, we already know of a
561 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000562 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000563 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000564 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000565 return 0;
566
Daniel Jasper26f7e782013-01-08 14:56:18 +0000567 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000568 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000569 if (NewLine && !State.NextToken->CanBreakBefore &&
570 !(State.NextToken->is(tok::r_brace) &&
571 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000573 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000574 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000575 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000576 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000577 State.LineContainsContinuedForLoopSection)
578 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000579 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
580 State.NextToken->Type != TT_LineComment &&
581 State.Stack.back().BreakAfterComma)
582 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000583
Daniel Jasper33182dd2012-12-05 14:57:28 +0000584 unsigned CurrentPenalty = 0;
585 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000586 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000587 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000588 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000589 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000590 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000591 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000592 }
593
Daniel Jasper20409152012-12-04 14:54:30 +0000594 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000595
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000596 // Exceeding column limit is bad, assign penalty.
597 if (State.Column > getColumnLimit()) {
598 unsigned ExcessCharacters = State.Column - getColumnLimit();
599 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
600 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601
Daniel Jasperbac016b2012-12-03 18:12:45 +0000602 if (StopAt <= CurrentPenalty)
603 return UINT_MAX;
604 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000605 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000606 if (I != Memory.end()) {
607 // If this state has already been examined, we can safely return the
608 // previous result if we
609 // - have not hit the optimatization (and thus returned UINT_MAX) OR
610 // - are now computing for a smaller or equal StopAt.
611 unsigned SavedResult = I->second.first;
612 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000613 if (SavedResult != UINT_MAX)
614 return SavedResult + CurrentPenalty;
615 else if (StopAt <= SavedStopAt)
616 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000617 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618
619 unsigned NoBreak = calcPenalty(State, false, StopAt);
620 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
621 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000622
623 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
624 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000625 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000626
627 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000628 }
629
Daniel Jasperbac016b2012-12-03 18:12:45 +0000630 FormatStyle Style;
631 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000632 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000633 const unsigned FirstIndent;
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000634 const bool FitsOnALine;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000635 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000636 tooling::Replacements &Replaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000637
Daniel Jasper33182dd2012-12-05 14:57:28 +0000638 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000639 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000640 StateMap Memory;
641
Daniel Jasperbac016b2012-12-03 18:12:45 +0000642 OptimizationParameters Parameters;
643};
644
645/// \brief Determines extra information about the tokens comprising an
646/// \c UnwrappedLine.
647class TokenAnnotator {
648public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000649 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
650 AnnotatedLine &Line)
651 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000652
653 /// \brief A parser that gathers additional information about tokens.
654 ///
655 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
656 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
657 /// into template parameter lists.
658 class AnnotatingParser {
659 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000660 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000661 : CurrentToken(&RootToken), KeywordVirtualFound(false),
662 ColonIsObjCMethodExpr(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000663
Daniel Jasper20409152012-12-04 14:54:30 +0000664 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000665 while (CurrentToken != NULL) {
666 if (CurrentToken->is(tok::greater)) {
667 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000668 next();
669 return true;
670 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000671 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
672 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000673 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000674 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
675 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000676 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000677 if (!consumeToken())
678 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000679 }
680 return false;
681 }
682
Daniel Jasper20409152012-12-04 14:54:30 +0000683 bool parseParens() {
Daniel Jasper46ef8522013-01-10 13:08:12 +0000684 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
685 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000686 while (CurrentToken != NULL) {
687 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000688 next();
689 return true;
690 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000691 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000692 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000693 if (!consumeToken())
694 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000695 }
696 return false;
697 }
698
Daniel Jasper20409152012-12-04 14:54:30 +0000699 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000700 if (!CurrentToken)
701 return false;
702
703 // A '[' could be an index subscript (after an indentifier or after
704 // ')' or ']'), or it could be the start of an Objective-C method
705 // expression.
706 AnnotatedToken *LSquare = CurrentToken->Parent;
707 bool StartsObjCMethodExpr =
708 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
709 LSquare->Parent->is(tok::l_square) ||
710 LSquare->Parent->is(tok::l_paren) ||
711 LSquare->Parent->is(tok::kw_return) ||
712 LSquare->Parent->is(tok::kw_throw) ||
713 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
714 true, true) > prec::Unknown;
715
716 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
717 if (StartsObjCMethodExpr) {
718 ColonIsObjCMethodExpr = true;
719 LSquare->Type = TT_ObjCMethodExpr;
720 }
721
Daniel Jasper26f7e782013-01-08 14:56:18 +0000722 while (CurrentToken != NULL) {
723 if (CurrentToken->is(tok::r_square)) {
Nico Weberbcfdd262013-01-12 06:18:40 +0000724 if (StartsObjCMethodExpr) {
725 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
726 CurrentToken->Type = TT_ObjCMethodExpr;
727 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000728 next();
729 return true;
730 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000731 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000733 if (!consumeToken())
734 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000735 }
736 return false;
737 }
738
Daniel Jasper700e7102013-01-10 09:26:47 +0000739 bool parseBrace() {
740 while (CurrentToken != NULL) {
741 if (CurrentToken->is(tok::r_brace)) {
742 next();
743 return true;
744 }
745 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
746 return false;
747 if (!consumeToken())
748 return false;
749 }
750 // Lines can currently end with '{'.
751 return true;
752 }
753
Daniel Jasper20409152012-12-04 14:54:30 +0000754 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000755 while (CurrentToken != NULL) {
756 if (CurrentToken->is(tok::colon)) {
757 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000758 next();
759 return true;
760 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000761 if (!consumeToken())
762 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000763 }
764 return false;
765 }
766
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000767 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000768 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
769 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000770 next();
771 if (!parseAngle())
772 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000773 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000774 parseLine();
775 return true;
776 }
777 return false;
778 }
779
Daniel Jasper1f42f112013-01-04 18:52:56 +0000780 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000781 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000782 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000783 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +0000784 case tok::plus:
785 case tok::minus:
786 // At the start of the line, +/- specific ObjectiveC method
787 // declarations.
788 if (Tok->Parent == NULL)
789 Tok->Type = TT_ObjCMethodSpecifier;
790 break;
Nico Weberbcfdd262013-01-12 06:18:40 +0000791 case tok::colon:
792 // Colons from ?: are handled in parseConditional().
793 if (ColonIsObjCMethodExpr)
794 Tok->Type = TT_ObjCMethodExpr;
795 break;
Nico Webercd52bda2013-01-10 23:11:41 +0000796 case tok::l_paren: {
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000797 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
798 TT_ObjCMethodSpecifier;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000799 if (!parseParens())
800 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000801 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
802 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000803 next();
Nico Webercd52bda2013-01-10 23:11:41 +0000804 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
805 CurrentToken->Type = TT_ObjCSelectorStart;
806 next();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000807 }
Nico Webercd52bda2013-01-10 23:11:41 +0000808 } break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000810 if (!parseSquare())
811 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000812 break;
Daniel Jasper700e7102013-01-10 09:26:47 +0000813 case tok::l_brace:
814 if (!parseBrace())
815 return false;
816 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000817 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000818 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000819 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000821 Tok->Type = TT_BinaryOperator;
822 CurrentToken = Tok;
823 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000824 }
825 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000826 case tok::r_paren:
827 case tok::r_square:
828 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +0000829 case tok::r_brace:
830 // Lines can start with '}'.
831 if (Tok->Parent != NULL)
832 return false;
833 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000834 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000835 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000836 break;
837 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000838 if (CurrentToken->is(tok::l_paren)) {
839 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000840 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000841 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
842 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000843 next();
844 }
845 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000846 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
847 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000848 next();
849 }
850 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000851 break;
852 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000853 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000854 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000855 case tok::kw_template:
856 parseTemplateDeclaration();
857 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858 default:
859 break;
860 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000861 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000862 }
863
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000864 void parseIncludeDirective() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000865 while (CurrentToken != NULL) {
Daniel Jasper8134e1e2013-01-13 08:12:18 +0000866 CurrentToken->Type = TT_IncludePath;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000867 next();
868 }
869 }
870
871 void parsePreprocessorDirective() {
872 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000873 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000874 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000875 // Hashes in the middle of a line can lead to any strange token
876 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000877 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000878 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000879 switch (
880 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000881 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000882 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000883 parseIncludeDirective();
884 break;
885 default:
886 break;
887 }
888 }
889
Daniel Jasper71607512013-01-07 10:48:50 +0000890 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000891 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000892 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000893 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000894 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000895 while (CurrentToken != NULL) {
896 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000897 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000898 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000899 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000900 }
Daniel Jasper71607512013-01-07 10:48:50 +0000901 if (KeywordVirtualFound)
902 return LT_VirtualFunctionDecl;
903 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000904 }
905
906 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000907 if (CurrentToken != NULL && !CurrentToken->Children.empty())
908 CurrentToken = &CurrentToken->Children[0];
909 else
910 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000911 }
912
913 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000914 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000915 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +0000916 bool ColonIsObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000917 };
918
Daniel Jasper26f7e782013-01-08 14:56:18 +0000919 void createAnnotatedTokens(AnnotatedToken &Current) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000920 if (Current.FormatTok.Children.empty()) {
921 Line.Last = &Current;
922 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000923 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
924 Current.Children.back().Parent = &Current;
925 createAnnotatedTokens(Current.Children.back());
926 }
927 }
Daniel Jasper71607512013-01-07 10:48:50 +0000928
Daniel Jasper26f7e782013-01-08 14:56:18 +0000929 void calculateExtraInformation(AnnotatedToken &Current) {
930 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
931
Manuel Klimek526ed112013-01-09 15:25:02 +0000932 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000933 Current.MustBreakBefore = true;
934 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +0000935 if (Current.Type == TT_LineComment) {
936 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
937 } else if (Current.Type == TT_CtorInitializerColon ||
938 Current.Parent->Type == TT_LineComment ||
939 (Current.is(tok::string_literal) &&
940 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +0000941 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +0000942 } else {
943 Current.MustBreakBefore = false;
944 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000945 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000946 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000947 if (!Current.Children.empty())
948 calculateExtraInformation(Current.Children[0]);
949 }
950
Daniel Jasper995e8202013-01-14 13:08:07 +0000951 void annotate() {
952 Line.Last = &Line.First;
953 createAnnotatedTokens(Line.First);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000954
Daniel Jasper995e8202013-01-14 13:08:07 +0000955 AnnotatingParser Parser(Line.First);
956 Line.Type = Parser.parseLine();
957 if (Line.Type == LT_Invalid)
958 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000959
Daniel Jasper995e8202013-01-14 13:08:07 +0000960 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000961
Daniel Jasper995e8202013-01-14 13:08:07 +0000962 if (Line.First.Type == TT_ObjCMethodSpecifier)
963 Line.Type = LT_ObjCMethodDecl;
964 else if (Line.First.Type == TT_ObjCDecl)
965 Line.Type = LT_ObjCDecl;
966 else if (Line.First.Type == TT_ObjCProperty)
967 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +0000968
Daniel Jasper995e8202013-01-14 13:08:07 +0000969 Line.First.SpaceRequiredBefore = true;
970 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
971 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000972
Daniel Jasper995e8202013-01-14 13:08:07 +0000973 if (!Line.First.Children.empty())
974 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000975 }
976
977private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000978 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
979 if (getPrecedence(Current) == prec::Assignment ||
980 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
981 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000982
Daniel Jasper26f7e782013-01-08 14:56:18 +0000983 if (Current.Type == TT_Unknown) {
984 if (Current.is(tok::star) || Current.is(tok::amp)) {
985 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +0000986 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
987 Current.is(tok::caret)) {
988 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000989 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
990 Current.Type = determineIncrementUsage(Current);
991 } else if (Current.is(tok::exclaim)) {
992 Current.Type = TT_UnaryOperator;
993 } else if (isBinaryOperator(Current)) {
994 Current.Type = TT_BinaryOperator;
995 } else if (Current.is(tok::comment)) {
996 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
997 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +0000998 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000999 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001000 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001001 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001002 } else if (Current.is(tok::r_paren) &&
1003 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001004 Current.Parent->Type == TT_TemplateCloser) &&
1005 (Current.Children.empty() ||
1006 (Current.Children[0].isNot(tok::equal) &&
1007 Current.Children[0].isNot(tok::semi) &&
1008 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001009 // FIXME: We need to get smarter and understand more cases of casts.
1010 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001011 } else if (Current.is(tok::at) && Current.Children.size()) {
1012 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1013 case tok::objc_interface:
1014 case tok::objc_implementation:
1015 case tok::objc_protocol:
1016 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001017 break;
1018 case tok::objc_property:
1019 Current.Type = TT_ObjCProperty;
1020 break;
Nico Webered91bba2013-01-10 19:19:14 +00001021 default:
1022 break;
1023 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001024 }
1025 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001026
1027 if (!Current.Children.empty())
1028 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001029 }
1030
Daniel Jasper26f7e782013-01-08 14:56:18 +00001031 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001032 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +00001033 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001034 }
1035
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001036 /// \brief Returns the previous token ignoring comments.
1037 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1038 const AnnotatedToken *PrevToken = Tok.Parent;
1039 while (PrevToken != NULL && PrevToken->is(tok::comment))
1040 PrevToken = PrevToken->Parent;
1041 return PrevToken;
1042 }
1043
1044 /// \brief Returns the next token ignoring comments.
1045 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1046 if (Tok.Children.empty())
1047 return NULL;
1048 const AnnotatedToken *NextToken = &Tok.Children[0];
1049 while (NextToken->is(tok::comment)) {
1050 if (NextToken->Children.empty())
1051 return NULL;
1052 NextToken = &NextToken->Children[0];
1053 }
1054 return NextToken;
1055 }
1056
1057 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001058 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001059 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1060 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001061 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001062
1063 const AnnotatedToken *NextToken = getNextToken(Tok);
1064 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001065 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001066
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001067 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1068 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1069 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1070 PrevToken->Type == TT_BinaryOperator ||
1071 PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001072 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001073
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001074 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1075 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1076 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1077 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1078 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1079 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1080 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001081 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001082
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001083 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1084 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001085 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001086
Daniel Jasper112fb272012-12-05 07:51:39 +00001087 // It is very unlikely that we are going to find a pointer or reference type
1088 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +00001089 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +00001090 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001091
Daniel Jasper71607512013-01-07 10:48:50 +00001092 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001093 }
1094
Daniel Jasper886568d2013-01-09 08:36:49 +00001095 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001096 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1097 if (PrevToken == NULL)
1098 return TT_UnaryOperator;
1099
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001100 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001101 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1102 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1103 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1104 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1105 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001106 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001107
1108 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001109 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001110 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001111
1112 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001113 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001114 }
1115
1116 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001117 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001118 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1119 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001120 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001121 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1122 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001123 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001124
Daniel Jasper71607512013-01-07 10:48:50 +00001125 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001126 }
1127
Daniel Jasper26f7e782013-01-08 14:56:18 +00001128 bool spaceRequiredBetween(const AnnotatedToken &Left,
1129 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001130 if (Right.is(tok::hashhash))
1131 return Left.is(tok::hash);
1132 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1133 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001134 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1135 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001136 if (Right.is(tok::less) &&
1137 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001138 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001139 return true;
1140 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1141 return false;
1142 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1143 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001144 if (Left.is(tok::at) &&
1145 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1146 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001147 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1148 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001149 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1151 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001152 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001153 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001154 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1155 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001156 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001157 return Right.FormatTok.Tok.isLiteral() ||
1158 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001159 if (Right.is(tok::star) && Left.is(tok::l_paren))
1160 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001161 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1162 return false;
1163 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001164 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001165 if (Left.is(tok::coloncolon) ||
1166 (Right.is(tok::coloncolon) &&
1167 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001168 return false;
1169 if (Left.is(tok::period) || Right.is(tok::period))
1170 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001171 if (Left.is(tok::colon))
1172 return Left.Type != TT_ObjCMethodExpr;
1173 if (Right.is(tok::colon))
1174 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001175 if (Left.is(tok::l_paren))
1176 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001177 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001178 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001179 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001180 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001181 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1182 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001183 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001184 if (Left.is(tok::at) &&
1185 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001186 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001187 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1188 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001189 return true;
1190 }
1191
Daniel Jasper26f7e782013-01-08 14:56:18 +00001192 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001193 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001194 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1195 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001196 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001197 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001198 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001199 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Webercd52bda2013-01-10 23:11:41 +00001200 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1201 if (Tok.Type == TT_ObjCSelectorStart)
1202 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001203 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001204 // Don't space between ')' and <id>
1205 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001206 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001207 // Don't space between ':' and '('
1208 return false;
1209 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001210 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001211 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1212 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001213
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001214 if (Tok.Parent->is(tok::comma))
1215 return true;
Daniel Jasper8134e1e2013-01-13 08:12:18 +00001216 if (Tok.Type == TT_IncludePath)
1217 return Tok.is(tok::less) || Tok.is(tok::string_literal);
Daniel Jasper46ef8522013-01-10 13:08:12 +00001218 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001219 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001220 if (Tok.Type == TT_OverloadedOperator)
1221 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001222 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001223 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001224 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001225 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001226 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001227 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001228 if (Tok.Parent->Type == TT_UnaryOperator ||
1229 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001230 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001231 if (Tok.Type == TT_UnaryOperator)
1232 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001233 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1234 (Tok.Parent->isNot(tok::colon) ||
1235 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001236 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1237 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001238 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1239 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001240 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001241 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001242 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001243 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001244 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001245 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001246 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001247 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001248 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001249 }
1250
Daniel Jasper26f7e782013-01-08 14:56:18 +00001251 bool canBreakBefore(const AnnotatedToken &Right) {
1252 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001253 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001254 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1255 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001256 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001257 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1258 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001259 // Don't break this identifier as ':' or identifier
1260 // before it will break.
1261 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001262 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1263 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001264 // Don't break at ':' if identifier before it can beak.
1265 return false;
1266 }
Daniel Jasper8134e1e2013-01-13 08:12:18 +00001267 if (Right.Type == TT_IncludePath)
1268 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001269 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1270 return false;
1271 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1272 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001273 if (isObjCSelectorName(Right))
1274 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001275 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001276 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001277 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001278 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001279 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001280 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001281 return false;
1282
Daniel Jasper043835a2013-01-09 09:33:39 +00001283 if (Right.is(tok::comment))
Daniel Jasper487f64b2013-01-13 16:10:20 +00001284 // We rely on MustBreakBefore being set correctly here as we should not
1285 // change the "binding" behavior of a comment.
1286 return false;
1287
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001288 // We only break before r_brace if there was a corresponding break before
1289 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1290 if (Right.is(tok::r_brace))
1291 return false;
1292
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001293 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001294 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001295 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1296 Left.is(tok::comma) || Right.is(tok::lessless) ||
1297 Right.is(tok::arrow) || Right.is(tok::period) ||
1298 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001299 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1300 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1301 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001302 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001303 }
1304
Daniel Jasperbac016b2012-12-03 18:12:45 +00001305 FormatStyle Style;
1306 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001307 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001308 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001309};
1310
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001311class LexerBasedFormatTokenSource : public FormatTokenSource {
1312public:
1313 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001314 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001315 IdentTable(Lex.getLangOpts()) {
1316 Lex.SetKeepWhitespaceMode(true);
1317 }
1318
1319 virtual FormatToken getNextToken() {
1320 if (GreaterStashed) {
1321 FormatTok.NewlinesBefore = 0;
1322 FormatTok.WhiteSpaceStart =
1323 FormatTok.Tok.getLocation().getLocWithOffset(1);
1324 FormatTok.WhiteSpaceLength = 0;
1325 GreaterStashed = false;
1326 return FormatTok;
1327 }
1328
1329 FormatTok = FormatToken();
1330 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001331 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001332 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001333 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1334 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001335
1336 // Consume and record whitespace until we find a significant token.
1337 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001338 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001339 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1340 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001341 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1342
1343 if (FormatTok.Tok.is(tok::eof))
1344 return FormatTok;
1345 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001346 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001347 }
Manuel Klimek95419382013-01-07 07:56:50 +00001348
1349 // Now FormatTok is the next non-whitespace token.
1350 FormatTok.TokenLength = Text.size();
1351
Manuel Klimekd4397b92013-01-04 23:34:14 +00001352 // In case the token starts with escaped newlines, we want to
1353 // take them into account as whitespace - this pattern is quite frequent
1354 // in macro definitions.
1355 // FIXME: What do we want to do with other escaped spaces, and escaped
1356 // spaces or newlines in the middle of tokens?
1357 // FIXME: Add a more explicit test.
1358 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001359 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001360 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001361 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001362 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001363 }
1364
1365 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001366 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001367 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001368 FormatTok.Tok.setKind(Info.getTokenID());
1369 }
1370
1371 if (FormatTok.Tok.is(tok::greatergreater)) {
1372 FormatTok.Tok.setKind(tok::greater);
1373 GreaterStashed = true;
1374 }
1375
1376 return FormatTok;
1377 }
1378
1379private:
1380 FormatToken FormatTok;
1381 bool GreaterStashed;
1382 Lexer &Lex;
1383 SourceManager &SourceMgr;
1384 IdentifierTable IdentTable;
1385
1386 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001387 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001388 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1389 Tok.getLength());
1390 }
1391};
1392
Daniel Jasperbac016b2012-12-03 18:12:45 +00001393class Formatter : public UnwrappedLineConsumer {
1394public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001395 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1396 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001397 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001398 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001399 Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001400
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001401 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001402
Daniel Jasperbac016b2012-12-03 18:12:45 +00001403 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001404 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001405 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001406 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001407 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001408 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1409 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1410 Annotator.annotate();
1411 }
1412 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1413 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001414 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001415 const AnnotatedLine &TheLine = *I;
1416 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1417 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1418 TheLine.InPPDirective,
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001419 PreviousEndOfLineColumn);
Daniel Jasper995e8202013-01-14 13:08:07 +00001420 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, I, E);
1421 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1422 FitsOnALine, TheLine.First, Replaces,
1423 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001424 PreviousEndOfLineColumn = Formatter.format();
1425 } else {
1426 // If we did not reformat this unwrapped line, the column at the end of
1427 // the last token is unchanged - thus, we can calculate the end of the
1428 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001429 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001430 SourceMgr.getSpellingColumnNumber(
1431 TheLine.Last->FormatTok.Tok.getLocation()) +
1432 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1433 SourceMgr, Lex.getLangOpts()) -
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001434 1;
1435 }
1436 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001437 return Replaces;
1438 }
1439
1440private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001441 /// \brief Tries to merge lines into one.
1442 ///
1443 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1444 /// if possible; note that \c I will be incremented when lines are merged.
1445 ///
1446 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001447 bool tryFitMultipleLinesInOne(unsigned Indent,
1448 std::vector<AnnotatedLine>::iterator &I,
1449 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001450 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1451
1452 // Check whether the UnwrappedLine can be put onto a single line. If
1453 // so, this is bound to be the optimal solution (by definition) and we
1454 // don't need to analyze the entire solution space.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001455 unsigned Length = 0;
1456 if (!fitsIntoLimit(I->First, Limit, &Length))
Daniel Jasper995e8202013-01-14 13:08:07 +00001457 return false;
Daniel Jasperfd0ca972013-01-14 16:02:06 +00001458 if (Limit == Length)
1459 return true; // Couldn't fit a space.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001460 Limit -= Length + 1; // One space.
1461 if (I + 1 == E)
1462 return true;
Manuel Klimek517e8942013-01-11 17:54:10 +00001463
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001464 if (I->Last->is(tok::l_brace)) {
1465 tryMergeSimpleBlock(I, E, Limit);
1466 } else if (I->First.is(tok::kw_if)) {
1467 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001468 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1469 I->First.FormatTok.IsFirst)) {
1470 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001471 }
1472 return true;
1473 }
1474
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001475 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1476 std::vector<AnnotatedLine>::iterator E,
1477 unsigned Limit) {
1478 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001479 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1480 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001481 if (I + 2 != E && (I + 2)->InPPDirective &&
1482 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1483 return;
1484 if (!fitsIntoLimit((I + 1)->First, Limit)) return;
1485 join(Line, *(++I));
1486 }
1487
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001488 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1489 std::vector<AnnotatedLine>::iterator E,
1490 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001491 if (!Style.AllowShortIfStatementsOnASingleLine)
1492 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001493 AnnotatedLine &Line = *I;
1494 if (!fitsIntoLimit((I + 1)->First, Limit))
1495 return;
1496 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1497 return;
1498 // Only inline simple if's (no nested if or else).
1499 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1500 return;
1501 join(Line, *(++I));
1502 }
1503
1504 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1505 std::vector<AnnotatedLine>::iterator E,
1506 unsigned Limit){
Daniel Jasper995e8202013-01-14 13:08:07 +00001507 // Check that we still have three lines and they fit into the limit.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001508 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1509 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001510
1511 // First, check that the current line allows merging. This is the case if
1512 // we're not in a control flow statement and the last token is an opening
1513 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001514 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001515 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001516 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1517 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1518 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1519 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001520 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001521 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1522 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001523 if (!AllowedTokens)
1524 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001525
1526 // Second, check that the next line does not contain any braces - if it
1527 // does, readability declines when putting it into a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001528 const AnnotatedToken *Tok = &(I + 1)->First;
1529 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001530 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001531 do {
1532 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001533 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001534 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1535 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001536
1537 // Last, check that the third line contains a single closing brace.
Daniel Jasper995e8202013-01-14 13:08:07 +00001538 Tok = &(I + 2)->First;
1539 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1540 Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001541 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001542
Daniel Jasper995e8202013-01-14 13:08:07 +00001543 // If the merged line fits, we use that instead and skip the next two lines.
1544 Line.Last->Children.push_back((I + 1)->First);
1545 while (!Line.Last->Children.empty()) {
1546 Line.Last->Children[0].Parent = Line.Last;
1547 Line.Last = &Line.Last->Children[0];
Manuel Klimek517e8942013-01-11 17:54:10 +00001548 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001549
1550 join(Line, *(I + 1));
1551 join(Line, *(I + 2));
1552 I += 2;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001553 }
1554
1555 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1556 unsigned Limit) {
1557 unsigned LengthLine1 = 0;
1558 unsigned LengthLine2 = 0;
1559 if (!fitsIntoLimit((I + 1)->First, Limit, &LengthLine1) ||
1560 !fitsIntoLimit((I + 2)->First, Limit, &LengthLine2))
1561 return false;
1562 return LengthLine1 + LengthLine2 + 1 <= Limit; // One space.
Manuel Klimek517e8942013-01-11 17:54:10 +00001563 }
1564
Daniel Jasper995e8202013-01-14 13:08:07 +00001565 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1566 A.Last->Children.push_back(B.First);
1567 while (!A.Last->Children.empty()) {
1568 A.Last->Children[0].Parent = A.Last;
1569 A.Last = &A.Last->Children[0];
1570 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001571 }
1572
Daniel Jasper995e8202013-01-14 13:08:07 +00001573 bool touchesRanges(const AnnotatedLine &TheLine) {
1574 const FormatToken *First = &TheLine.First.FormatTok;
1575 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001576 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001577 First->Tok.getLocation(),
1578 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001579 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001580 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1581 Ranges[i].getBegin()) &&
1582 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1583 LineRange.getBegin()))
1584 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001585 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001586 return false;
1587 }
1588
1589 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001590 AnnotatedLines.push_back(
1591 AnnotatedLine(TheLine.RootToken, TheLine.Level, TheLine.InPPDirective));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001592 }
1593
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001594 /// \brief Add a new line and the required indent before the first Token
1595 /// of the \c UnwrappedLine if there was no structural parsing error.
1596 /// Returns the indent level of the \c UnwrappedLine.
1597 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1598 bool InPPDirective,
1599 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001600 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001601 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1602 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1603
1604 unsigned Newlines = std::min(Tok.NewlinesBefore,
1605 Style.MaxEmptyLinesToKeep + 1);
1606 if (Newlines == 0 && !Tok.IsFirst)
1607 Newlines = 1;
1608 unsigned Indent = Level * 2;
1609
1610 bool IsAccessModifier = false;
1611 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1612 RootToken.is(tok::kw_private))
1613 IsAccessModifier = true;
1614 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1615 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1616 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1617 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1618 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1619 IsAccessModifier = true;
1620
1621 if (IsAccessModifier &&
1622 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1623 Indent += Style.AccessModifierOffset;
1624 if (!InPPDirective || Tok.HasUnescapedNewline) {
1625 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1626 } else {
1627 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1628 SourceMgr, Replaces);
1629 }
1630 return Indent;
1631 }
1632
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001633 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001634 FormatStyle Style;
1635 Lexer &Lex;
1636 SourceManager &SourceMgr;
1637 tooling::Replacements Replaces;
1638 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001639 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001640 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001641};
1642
1643tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1644 SourceManager &SourceMgr,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001645 std::vector<CharSourceRange> Ranges,
1646 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001647 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001648 OwningPtr<DiagnosticConsumer> DiagPrinter;
1649 if (DiagClient == 0) {
1650 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1651 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1652 DiagClient = DiagPrinter.get();
1653 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001654 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001655 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001656 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001657 Diagnostics.setSourceManager(&SourceMgr);
1658 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001659 return formatter.format();
1660}
1661
Daniel Jasper46ef8522013-01-10 13:08:12 +00001662LangOptions getFormattingLangOpts() {
1663 LangOptions LangOpts;
1664 LangOpts.CPlusPlus = 1;
1665 LangOpts.CPlusPlus11 = 1;
1666 LangOpts.Bool = 1;
1667 LangOpts.ObjC1 = 1;
1668 LangOpts.ObjC2 = 1;
1669 return LangOpts;
1670}
1671
Daniel Jaspercd162382013-01-07 13:26:07 +00001672} // namespace format
1673} // namespace clang