blob: 445a4064b46d2d3cabf394ca6368d01e4371a251 [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,
Manuel Klimek407a31a2013-01-15 15:50:27 +000037 TT_ImplicitStringLiteral,
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) {
Manuel Klimek19132302013-01-15 16:41:02 +0000256 if (State.NextToken->Type == TT_ImplicitStringLiteral)
257 // We will not touch the rest of the white space in this
258 // \c UnwrappedLine. The returned value can also not matter, as we
259 // cannot continue an top-level implicit string literal on the next
260 // line.
261 return 0;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000262 if (FitsOnALine) {
263 addTokenToState(false, false, State);
264 } else {
265 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
266 unsigned Break = calcPenalty(State, true, NoBreak);
267 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000268 if (State.NextToken != NULL &&
269 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
270 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
271 !fitsIntoLimit(*State.NextToken,
272 getColumnLimit() - State.Column - 1))
273 State.Stack.back().BreakAfterComma = true;
274 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000275 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000276 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000277 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000278 }
279
280private:
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000281 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000282 ParenState(unsigned Indent, unsigned LastSpace)
283 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
284 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000285
Daniel Jasperbac016b2012-12-03 18:12:45 +0000286 /// \brief The position to which a specific parenthesis level needs to be
287 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000288 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000289
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000290 /// \brief The position of the last space on each level.
291 ///
292 /// Used e.g. to break like:
293 /// functionCall(Parameter, otherCall(
294 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000295 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000296
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000297 /// \brief The position the first "<<" operator encountered on each level.
298 ///
299 /// Used to align "<<" operators. 0 if no such operator has been encountered
300 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000301 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000302
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000303 /// \brief Whether a newline needs to be inserted before the block's closing
304 /// brace.
305 ///
306 /// We only want to insert a newline before the closing brace if there also
307 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000308 bool BreakBeforeClosingBrace;
309
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000310 bool BreakAfterComma;
311
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000312 bool operator<(const ParenState &Other) const {
313 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000314 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000315 if (LastSpace != Other.LastSpace)
316 return LastSpace < Other.LastSpace;
317 if (FirstLessLess != Other.FirstLessLess)
318 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000319 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
320 return BreakBeforeClosingBrace;
Daniel Jasperb3123142013-01-12 07:36:22 +0000321 if (BreakAfterComma != Other.BreakAfterComma)
322 return BreakAfterComma;
323 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000324 }
325 };
326
327 /// \brief The current state when indenting a unwrapped line.
328 ///
329 /// As the indenting tries different combinations this is copied by value.
330 struct LineState {
331 /// \brief The number of used columns in the current line.
332 unsigned Column;
333
334 /// \brief The token that needs to be next formatted.
335 const AnnotatedToken *NextToken;
336
337 /// \brief The parenthesis level of the first token on the current line.
338 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000339
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000340 /// \brief The column of the first variable in a for-loop declaration.
341 ///
342 /// Used to align the second variable if necessary.
343 unsigned ForLoopVariablePos;
344
345 /// \brief \c true if this line contains a continued for-loop section.
346 bool LineContainsContinuedForLoopSection;
347
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000348 /// \brief A stack keeping track of properties applying to parenthesis
349 /// levels.
350 std::vector<ParenState> Stack;
351
352 /// \brief Comparison operator to be able to used \c LineState in \c map.
353 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000354 if (Other.NextToken != NextToken)
355 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000356 if (Other.Column != Column)
357 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000358 if (Other.StartOfLineLevel != StartOfLineLevel)
359 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000360 if (Other.ForLoopVariablePos != ForLoopVariablePos)
361 return Other.ForLoopVariablePos < ForLoopVariablePos;
362 if (Other.LineContainsContinuedForLoopSection !=
363 LineContainsContinuedForLoopSection)
364 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000365 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000366 }
367 };
368
Daniel Jasper20409152012-12-04 14:54:30 +0000369 /// \brief Appends the next token to \p State and updates information
370 /// necessary for indentation.
371 ///
372 /// Puts the token on the current line if \p Newline is \c true and adds a
373 /// line break and necessary indentation otherwise.
374 ///
375 /// If \p DryRun is \c false, also creates and stores the required
376 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000377 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000378 const AnnotatedToken &Current = *State.NextToken;
379 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000380 assert(State.Stack.size());
381 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000382
383 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000384 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000385 if (Current.is(tok::r_brace)) {
386 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000387 } else if (Current.is(tok::string_literal) &&
388 Previous.is(tok::string_literal)) {
389 State.Column = State.Column - Previous.FormatTok.TokenLength;
390 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000391 State.Stack[ParenLevel].FirstLessLess != 0) {
392 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000393 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000394 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
395 Current.is(tok::period) || Previous.is(tok::question) ||
396 Previous.Type == TT_ConditionalExpr)) {
397 // Indent and extra 4 spaces after if we know the current expression is
398 // continued. Don't do that on the top level, as we already indent 4
399 // there.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000400 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000401 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000402 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000403 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000404 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000405 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000406 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000407 }
408
Manuel Klimek2851c162013-01-10 14:36:46 +0000409 // A line starting with a closing brace is assumed to be correct for the
410 // same level as before the opening brace.
411 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000412
Daniel Jasper26f7e782013-01-08 14:56:18 +0000413 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000414 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000415
Manuel Klimek060143e2013-01-02 18:33:23 +0000416 if (!DryRun) {
417 if (!Line.InPPDirective)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000418 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
419 SourceMgr, Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000420 else
Daniel Jasper9c837d02013-01-09 07:06:56 +0000421 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000422 WhitespaceStartColumn, Style, SourceMgr,
423 Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000424 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000426 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Weberf681fa82013-01-12 07:05:25 +0000427 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000428 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000429 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000430 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
431 State.ForLoopVariablePos = State.Column -
432 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000433
Daniel Jasper26f7e782013-01-08 14:56:18 +0000434 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
435 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000436 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000437
Daniel Jasperbac016b2012-12-03 18:12:45 +0000438 if (!DryRun)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000439 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000440
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000441 // FIXME: Do we need to do this for assignments nested in other
442 // expressions?
443 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000444 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000445 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000446 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000447 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000448 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000449 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000450
Daniel Jasper9cda8002013-01-07 13:08:40 +0000451 // Top-level spaces that are not part of assignments are exempt as that
452 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000453 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000454 if (Spaces > 0 &&
455 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000456 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457 }
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000458 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000459 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000460 }
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000461 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000462 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000463
Daniel Jasper20409152012-12-04 14:54:30 +0000464 /// \brief Mark the next token as consumed in \p State and modify its stacks
465 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000466 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000467 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000468 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000469
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000470 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
471 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000472
Daniel Jaspercf225b62012-12-24 13:43:52 +0000473 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000474 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000475 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
476 Current.is(tok::l_brace) ||
477 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000478 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000479 if (Current.is(tok::l_brace)) {
480 // FIXME: This does not work with nested static initializers.
481 // Implement a better handling for static initializers and similar
482 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000483 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000484 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000485 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000486 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000487 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000488 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000489 }
490
Daniel Jaspercf225b62012-12-24 13:43:52 +0000491 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000492 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000493 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
494 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
495 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000496 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000497 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000498
Daniel Jasper26f7e782013-01-08 14:56:18 +0000499 if (State.NextToken->Children.empty())
500 State.NextToken = NULL;
501 else
502 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000503
504 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000505 }
506
Nico Weberdecf7bc2013-01-07 15:15:29 +0000507 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000508 unsigned splitPenalty(const AnnotatedToken &Tok) {
509 const AnnotatedToken &Left = Tok;
510 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000511
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000512 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
513 return 50;
514 if (Left.is(tok::equal) && Right.is(tok::l_brace))
515 return 150;
516
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000517 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000518 if (RootToken.is(tok::kw_for) &&
519 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000520 return 20;
521
Daniel Jasper26f7e782013-01-08 14:56:18 +0000522 if (Left.is(tok::semi) || Left.is(tok::comma) ||
523 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000524 return 0;
Nico Webere8ccc812013-01-12 22:48:47 +0000525
526 // In Objective-C method expressions, prefer breaking before "param:" over
527 // breaking after it.
528 if (isObjCSelectorName(Right))
529 return 0;
530 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
531 return 20;
532
Daniel Jasper26f7e782013-01-08 14:56:18 +0000533 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000534 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000535
Daniel Jasper9c837d02013-01-09 07:06:56 +0000536 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
537 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000538 prec::Level Level = getPrecedence(Left);
539
540 // Breaking after an assignment leads to a bad result as the two sides of
541 // the assignment are visually very close together.
542 if (Level == prec::Assignment)
543 return 50;
544
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000545 if (Level != prec::Unknown)
546 return Level;
547
Daniel Jasper26f7e782013-01-08 14:56:18 +0000548 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000549 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000550
Daniel Jasperbac016b2012-12-03 18:12:45 +0000551 return 3;
552 }
553
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000554 unsigned getColumnLimit() {
555 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
556 }
557
Daniel Jasperbac016b2012-12-03 18:12:45 +0000558 /// \brief Calculate the number of lines needed to format the remaining part
559 /// of the unwrapped line.
560 ///
561 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000562 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000563 /// added after the previous token.
564 ///
565 /// \param StopAt is used for optimization. If we can determine that we'll
566 /// definitely need at least \p StopAt additional lines, we already know of a
567 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000568 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000569 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000570 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000571 return 0;
572
Daniel Jasper26f7e782013-01-08 14:56:18 +0000573 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000575 if (NewLine && !State.NextToken->CanBreakBefore &&
576 !(State.NextToken->is(tok::r_brace) &&
577 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000578 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000579 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000580 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000581 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000582 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000583 State.LineContainsContinuedForLoopSection)
584 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000585 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
586 State.NextToken->Type != TT_LineComment &&
587 State.Stack.back().BreakAfterComma)
588 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000589
Daniel Jasper33182dd2012-12-05 14:57:28 +0000590 unsigned CurrentPenalty = 0;
591 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000592 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000593 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000594 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000595 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000596 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000597 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000598 }
599
Daniel Jasper20409152012-12-04 14:54:30 +0000600 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000602 // Exceeding column limit is bad, assign penalty.
603 if (State.Column > getColumnLimit()) {
604 unsigned ExcessCharacters = State.Column - getColumnLimit();
605 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
606 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000607
Daniel Jasperbac016b2012-12-03 18:12:45 +0000608 if (StopAt <= CurrentPenalty)
609 return UINT_MAX;
610 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000611 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000612 if (I != Memory.end()) {
613 // If this state has already been examined, we can safely return the
614 // previous result if we
615 // - have not hit the optimatization (and thus returned UINT_MAX) OR
616 // - are now computing for a smaller or equal StopAt.
617 unsigned SavedResult = I->second.first;
618 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000619 if (SavedResult != UINT_MAX)
620 return SavedResult + CurrentPenalty;
621 else if (StopAt <= SavedStopAt)
622 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000623 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000624
625 unsigned NoBreak = calcPenalty(State, false, StopAt);
626 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
627 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000628
629 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
630 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000631 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000632
633 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 }
635
Daniel Jasperbac016b2012-12-03 18:12:45 +0000636 FormatStyle Style;
637 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000638 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000639 const unsigned FirstIndent;
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000640 const bool FitsOnALine;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000641 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000642 tooling::Replacements &Replaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000643
Daniel Jasper33182dd2012-12-05 14:57:28 +0000644 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000645 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000646 StateMap Memory;
647
Daniel Jasperbac016b2012-12-03 18:12:45 +0000648 OptimizationParameters Parameters;
649};
650
651/// \brief Determines extra information about the tokens comprising an
652/// \c UnwrappedLine.
653class TokenAnnotator {
654public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000655 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
656 AnnotatedLine &Line)
657 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000658
659 /// \brief A parser that gathers additional information about tokens.
660 ///
661 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
662 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
663 /// into template parameter lists.
664 class AnnotatingParser {
665 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000666 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000667 : CurrentToken(&RootToken), KeywordVirtualFound(false),
668 ColonIsObjCMethodExpr(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000669
Daniel Jasper20409152012-12-04 14:54:30 +0000670 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000671 while (CurrentToken != NULL) {
672 if (CurrentToken->is(tok::greater)) {
673 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000674 next();
675 return true;
676 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000677 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
678 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000679 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000680 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
681 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000682 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000683 if (!consumeToken())
684 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000685 }
686 return false;
687 }
688
Daniel Jasper20409152012-12-04 14:54:30 +0000689 bool parseParens() {
Daniel Jasper46ef8522013-01-10 13:08:12 +0000690 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
691 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000692 while (CurrentToken != NULL) {
693 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000694 next();
695 return true;
696 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000697 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000698 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000699 if (!consumeToken())
700 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000701 }
702 return false;
703 }
704
Daniel Jasper20409152012-12-04 14:54:30 +0000705 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000706 if (!CurrentToken)
707 return false;
708
709 // A '[' could be an index subscript (after an indentifier or after
710 // ')' or ']'), or it could be the start of an Objective-C method
711 // expression.
712 AnnotatedToken *LSquare = CurrentToken->Parent;
713 bool StartsObjCMethodExpr =
714 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
715 LSquare->Parent->is(tok::l_square) ||
716 LSquare->Parent->is(tok::l_paren) ||
717 LSquare->Parent->is(tok::kw_return) ||
718 LSquare->Parent->is(tok::kw_throw) ||
719 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
720 true, true) > prec::Unknown;
721
722 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
723 if (StartsObjCMethodExpr) {
724 ColonIsObjCMethodExpr = true;
725 LSquare->Type = TT_ObjCMethodExpr;
726 }
727
Daniel Jasper26f7e782013-01-08 14:56:18 +0000728 while (CurrentToken != NULL) {
729 if (CurrentToken->is(tok::r_square)) {
Nico Weberbcfdd262013-01-12 06:18:40 +0000730 if (StartsObjCMethodExpr) {
731 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
732 CurrentToken->Type = TT_ObjCMethodExpr;
733 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 next();
735 return true;
736 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000737 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000738 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000739 if (!consumeToken())
740 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 }
742 return false;
743 }
744
Daniel Jasper700e7102013-01-10 09:26:47 +0000745 bool parseBrace() {
746 while (CurrentToken != NULL) {
747 if (CurrentToken->is(tok::r_brace)) {
748 next();
749 return true;
750 }
751 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
752 return false;
753 if (!consumeToken())
754 return false;
755 }
756 // Lines can currently end with '{'.
757 return true;
758 }
759
Daniel Jasper20409152012-12-04 14:54:30 +0000760 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000761 while (CurrentToken != NULL) {
762 if (CurrentToken->is(tok::colon)) {
763 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000764 next();
765 return true;
766 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000767 if (!consumeToken())
768 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000769 }
770 return false;
771 }
772
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000773 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000774 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
775 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000776 next();
777 if (!parseAngle())
778 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000779 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000780 parseLine();
781 return true;
782 }
783 return false;
784 }
785
Daniel Jasper1f42f112013-01-04 18:52:56 +0000786 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000787 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000788 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000789 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +0000790 case tok::plus:
791 case tok::minus:
792 // At the start of the line, +/- specific ObjectiveC method
793 // declarations.
794 if (Tok->Parent == NULL)
795 Tok->Type = TT_ObjCMethodSpecifier;
796 break;
Nico Weberbcfdd262013-01-12 06:18:40 +0000797 case tok::colon:
798 // Colons from ?: are handled in parseConditional().
799 if (ColonIsObjCMethodExpr)
800 Tok->Type = TT_ObjCMethodExpr;
801 break;
Nico Webercd52bda2013-01-10 23:11:41 +0000802 case tok::l_paren: {
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000803 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
804 TT_ObjCMethodSpecifier;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000805 if (!parseParens())
806 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000807 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
808 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000809 next();
Nico Webercd52bda2013-01-10 23:11:41 +0000810 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
811 CurrentToken->Type = TT_ObjCSelectorStart;
812 next();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000813 }
Nico Webercd52bda2013-01-10 23:11:41 +0000814 } break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000815 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000816 if (!parseSquare())
817 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000818 break;
Daniel Jasper700e7102013-01-10 09:26:47 +0000819 case tok::l_brace:
820 if (!parseBrace())
821 return false;
822 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000823 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000824 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000825 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000826 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000827 Tok->Type = TT_BinaryOperator;
828 CurrentToken = Tok;
829 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000830 }
831 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000832 case tok::r_paren:
833 case tok::r_square:
834 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +0000835 case tok::r_brace:
836 // Lines can start with '}'.
837 if (Tok->Parent != NULL)
838 return false;
839 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000840 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000841 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000842 break;
843 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000844 if (CurrentToken->is(tok::l_paren)) {
845 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000846 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000847 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
848 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000849 next();
850 }
851 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000852 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
853 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000854 next();
855 }
856 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000857 break;
858 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000859 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000860 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000861 case tok::kw_template:
862 parseTemplateDeclaration();
863 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000864 default:
865 break;
866 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000867 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000868 }
869
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000870 void parseIncludeDirective() {
Manuel Klimek407a31a2013-01-15 15:50:27 +0000871 next();
872 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
873 next();
874 while (CurrentToken != NULL) {
875 CurrentToken->Type = TT_ImplicitStringLiteral;
876 next();
877 }
878 } else {
879 while (CurrentToken != NULL) {
880 next();
881 }
882 }
883 }
884
885 void parseWarningOrError() {
886 next();
887 // We still want to format the whitespace left of the first token of the
888 // warning or error.
889 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000890 while (CurrentToken != NULL) {
Manuel Klimek407a31a2013-01-15 15:50:27 +0000891 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000892 next();
893 }
894 }
895
896 void parsePreprocessorDirective() {
897 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000898 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000899 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000900 // Hashes in the middle of a line can lead to any strange token
901 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000902 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000903 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000904 switch (
905 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000906 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000907 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000908 parseIncludeDirective();
909 break;
Manuel Klimek407a31a2013-01-15 15:50:27 +0000910 case tok::pp_error:
911 case tok::pp_warning:
912 parseWarningOrError();
913 break;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000914 default:
915 break;
916 }
917 }
918
Daniel Jasper71607512013-01-07 10:48:50 +0000919 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000920 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000921 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000922 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000923 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000924 while (CurrentToken != NULL) {
925 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000926 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000927 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000928 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000929 }
Daniel Jasper71607512013-01-07 10:48:50 +0000930 if (KeywordVirtualFound)
931 return LT_VirtualFunctionDecl;
932 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000933 }
934
935 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000936 if (CurrentToken != NULL && !CurrentToken->Children.empty())
937 CurrentToken = &CurrentToken->Children[0];
938 else
939 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000940 }
941
942 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000943 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000944 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +0000945 bool ColonIsObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000946 };
947
Daniel Jasper26f7e782013-01-08 14:56:18 +0000948 void createAnnotatedTokens(AnnotatedToken &Current) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000949 if (Current.FormatTok.Children.empty()) {
950 Line.Last = &Current;
951 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000952 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
953 Current.Children.back().Parent = &Current;
954 createAnnotatedTokens(Current.Children.back());
955 }
956 }
Daniel Jasper71607512013-01-07 10:48:50 +0000957
Daniel Jasper26f7e782013-01-08 14:56:18 +0000958 void calculateExtraInformation(AnnotatedToken &Current) {
959 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
960
Manuel Klimek526ed112013-01-09 15:25:02 +0000961 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000962 Current.MustBreakBefore = true;
963 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +0000964 if (Current.Type == TT_LineComment) {
965 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
966 } else if (Current.Type == TT_CtorInitializerColon ||
967 Current.Parent->Type == TT_LineComment ||
968 (Current.is(tok::string_literal) &&
969 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +0000970 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +0000971 } else {
972 Current.MustBreakBefore = false;
973 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000974 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000975 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000976 if (!Current.Children.empty())
977 calculateExtraInformation(Current.Children[0]);
978 }
979
Daniel Jasper995e8202013-01-14 13:08:07 +0000980 void annotate() {
981 Line.Last = &Line.First;
982 createAnnotatedTokens(Line.First);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000983
Daniel Jasper995e8202013-01-14 13:08:07 +0000984 AnnotatingParser Parser(Line.First);
985 Line.Type = Parser.parseLine();
986 if (Line.Type == LT_Invalid)
987 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000988
Daniel Jasper995e8202013-01-14 13:08:07 +0000989 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000990
Daniel Jasper995e8202013-01-14 13:08:07 +0000991 if (Line.First.Type == TT_ObjCMethodSpecifier)
992 Line.Type = LT_ObjCMethodDecl;
993 else if (Line.First.Type == TT_ObjCDecl)
994 Line.Type = LT_ObjCDecl;
995 else if (Line.First.Type == TT_ObjCProperty)
996 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +0000997
Daniel Jasper995e8202013-01-14 13:08:07 +0000998 Line.First.SpaceRequiredBefore = true;
999 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1000 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001001
Daniel Jasper995e8202013-01-14 13:08:07 +00001002 if (!Line.First.Children.empty())
1003 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001004 }
1005
1006private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001007 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1008 if (getPrecedence(Current) == prec::Assignment ||
1009 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1010 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011
Daniel Jasper26f7e782013-01-08 14:56:18 +00001012 if (Current.Type == TT_Unknown) {
1013 if (Current.is(tok::star) || Current.is(tok::amp)) {
1014 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +00001015 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1016 Current.is(tok::caret)) {
1017 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001018 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1019 Current.Type = determineIncrementUsage(Current);
1020 } else if (Current.is(tok::exclaim)) {
1021 Current.Type = TT_UnaryOperator;
1022 } else if (isBinaryOperator(Current)) {
1023 Current.Type = TT_BinaryOperator;
1024 } else if (Current.is(tok::comment)) {
1025 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1026 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +00001027 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001028 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001029 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001030 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001031 } else if (Current.is(tok::r_paren) &&
1032 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001033 Current.Parent->Type == TT_TemplateCloser) &&
1034 (Current.Children.empty() ||
1035 (Current.Children[0].isNot(tok::equal) &&
1036 Current.Children[0].isNot(tok::semi) &&
1037 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001038 // FIXME: We need to get smarter and understand more cases of casts.
1039 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001040 } else if (Current.is(tok::at) && Current.Children.size()) {
1041 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1042 case tok::objc_interface:
1043 case tok::objc_implementation:
1044 case tok::objc_protocol:
1045 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001046 break;
1047 case tok::objc_property:
1048 Current.Type = TT_ObjCProperty;
1049 break;
Nico Webered91bba2013-01-10 19:19:14 +00001050 default:
1051 break;
1052 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001053 }
1054 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001055
1056 if (!Current.Children.empty())
1057 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001058 }
1059
Daniel Jasper26f7e782013-01-08 14:56:18 +00001060 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001061 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +00001062 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001063 }
1064
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001065 /// \brief Returns the previous token ignoring comments.
1066 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1067 const AnnotatedToken *PrevToken = Tok.Parent;
1068 while (PrevToken != NULL && PrevToken->is(tok::comment))
1069 PrevToken = PrevToken->Parent;
1070 return PrevToken;
1071 }
1072
1073 /// \brief Returns the next token ignoring comments.
1074 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1075 if (Tok.Children.empty())
1076 return NULL;
1077 const AnnotatedToken *NextToken = &Tok.Children[0];
1078 while (NextToken->is(tok::comment)) {
1079 if (NextToken->Children.empty())
1080 return NULL;
1081 NextToken = &NextToken->Children[0];
1082 }
1083 return NextToken;
1084 }
1085
1086 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001087 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001088 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1089 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001090 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001091
1092 const AnnotatedToken *NextToken = getNextToken(Tok);
1093 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001094 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001095
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001096 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1097 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1098 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1099 PrevToken->Type == TT_BinaryOperator ||
1100 PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001101 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001102
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001103 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1104 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1105 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1106 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1107 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1108 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1109 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001110 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001111
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001112 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1113 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001114 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001115
Daniel Jasper112fb272012-12-05 07:51:39 +00001116 // It is very unlikely that we are going to find a pointer or reference type
1117 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +00001118 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +00001119 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001120
Daniel Jasper71607512013-01-07 10:48:50 +00001121 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001122 }
1123
Daniel Jasper886568d2013-01-09 08:36:49 +00001124 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001125 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1126 if (PrevToken == NULL)
1127 return TT_UnaryOperator;
1128
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001129 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001130 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1131 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1132 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1133 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1134 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001135 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001136
1137 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001138 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001139 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001140
1141 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001142 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001143 }
1144
1145 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001146 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001147 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1148 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001149 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001150 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1151 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001152 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001153
Daniel Jasper71607512013-01-07 10:48:50 +00001154 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001155 }
1156
Daniel Jasper26f7e782013-01-08 14:56:18 +00001157 bool spaceRequiredBetween(const AnnotatedToken &Left,
1158 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001159 if (Right.is(tok::hashhash))
1160 return Left.is(tok::hash);
1161 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1162 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001163 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1164 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001165 if (Right.is(tok::less) &&
1166 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001167 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001168 return true;
1169 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1170 return false;
1171 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1172 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001173 if (Left.is(tok::at) &&
1174 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1175 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001176 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1177 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001178 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001179 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1180 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001181 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001182 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001183 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1184 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001185 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001186 return Right.FormatTok.Tok.isLiteral() ||
1187 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001188 if (Right.is(tok::star) && Left.is(tok::l_paren))
1189 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001190 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1191 return false;
1192 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001193 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001194 if (Left.is(tok::coloncolon) ||
1195 (Right.is(tok::coloncolon) &&
1196 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001197 return false;
1198 if (Left.is(tok::period) || Right.is(tok::period))
1199 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001200 if (Left.is(tok::colon))
1201 return Left.Type != TT_ObjCMethodExpr;
1202 if (Right.is(tok::colon))
1203 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001204 if (Left.is(tok::l_paren))
1205 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001206 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001207 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001208 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001209 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001210 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1211 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001212 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001213 if (Left.is(tok::at) &&
1214 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001215 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001216 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1217 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001218 return true;
1219 }
1220
Daniel Jasper26f7e782013-01-08 14:56:18 +00001221 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001222 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001223 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1224 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001225 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001226 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001227 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001228 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Webercd52bda2013-01-10 23:11:41 +00001229 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1230 if (Tok.Type == TT_ObjCSelectorStart)
1231 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001232 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001233 // Don't space between ')' and <id>
1234 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001235 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001236 // Don't space between ':' and '('
1237 return false;
1238 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001239 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001240 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1241 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001242
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001243 if (Tok.Parent->is(tok::comma))
1244 return true;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001245 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001246 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001247 if (Tok.Type == TT_OverloadedOperator)
1248 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001249 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001250 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001251 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001252 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001253 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001254 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001255 if (Tok.Parent->Type == TT_UnaryOperator ||
1256 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001257 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001258 if (Tok.Type == TT_UnaryOperator)
1259 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001260 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1261 (Tok.Parent->isNot(tok::colon) ||
1262 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001263 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1264 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001265 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1266 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001267 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001268 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001269 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001270 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001271 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001272 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001273 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001274 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001275 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001276 }
1277
Daniel Jasper26f7e782013-01-08 14:56:18 +00001278 bool canBreakBefore(const AnnotatedToken &Right) {
1279 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001280 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001281 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1282 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001283 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001284 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1285 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001286 // Don't break this identifier as ':' or identifier
1287 // before it will break.
1288 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001289 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1290 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001291 // Don't break at ':' if identifier before it can beak.
1292 return false;
1293 }
Nico Weberbcfdd262013-01-12 06:18:40 +00001294 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1295 return false;
1296 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1297 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001298 if (isObjCSelectorName(Right))
1299 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001300 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001301 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001302 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001303 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001304 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001305 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001306 return false;
1307
Daniel Jasper043835a2013-01-09 09:33:39 +00001308 if (Right.is(tok::comment))
Daniel Jasper487f64b2013-01-13 16:10:20 +00001309 // We rely on MustBreakBefore being set correctly here as we should not
1310 // change the "binding" behavior of a comment.
1311 return false;
1312
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001313 // We only break before r_brace if there was a corresponding break before
1314 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1315 if (Right.is(tok::r_brace))
1316 return false;
1317
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001318 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001319 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001320 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1321 Left.is(tok::comma) || Right.is(tok::lessless) ||
1322 Right.is(tok::arrow) || Right.is(tok::period) ||
1323 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001324 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1325 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1326 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001327 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001328 }
1329
Daniel Jasperbac016b2012-12-03 18:12:45 +00001330 FormatStyle Style;
1331 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001332 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001333 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001334};
1335
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001336class LexerBasedFormatTokenSource : public FormatTokenSource {
1337public:
1338 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001339 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001340 IdentTable(Lex.getLangOpts()) {
1341 Lex.SetKeepWhitespaceMode(true);
1342 }
1343
1344 virtual FormatToken getNextToken() {
1345 if (GreaterStashed) {
1346 FormatTok.NewlinesBefore = 0;
1347 FormatTok.WhiteSpaceStart =
1348 FormatTok.Tok.getLocation().getLocWithOffset(1);
1349 FormatTok.WhiteSpaceLength = 0;
1350 GreaterStashed = false;
1351 return FormatTok;
1352 }
1353
1354 FormatTok = FormatToken();
1355 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001356 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001357 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001358 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1359 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001360
1361 // Consume and record whitespace until we find a significant token.
1362 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001363 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001364 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1365 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001366 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1367
1368 if (FormatTok.Tok.is(tok::eof))
1369 return FormatTok;
1370 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001371 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001372 }
Manuel Klimek95419382013-01-07 07:56:50 +00001373
1374 // Now FormatTok is the next non-whitespace token.
1375 FormatTok.TokenLength = Text.size();
1376
Manuel Klimekd4397b92013-01-04 23:34:14 +00001377 // In case the token starts with escaped newlines, we want to
1378 // take them into account as whitespace - this pattern is quite frequent
1379 // in macro definitions.
1380 // FIXME: What do we want to do with other escaped spaces, and escaped
1381 // spaces or newlines in the middle of tokens?
1382 // FIXME: Add a more explicit test.
1383 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001384 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001385 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001386 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001387 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001388 }
1389
1390 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001391 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001392 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001393 FormatTok.Tok.setKind(Info.getTokenID());
1394 }
1395
1396 if (FormatTok.Tok.is(tok::greatergreater)) {
1397 FormatTok.Tok.setKind(tok::greater);
1398 GreaterStashed = true;
1399 }
1400
1401 return FormatTok;
1402 }
1403
1404private:
1405 FormatToken FormatTok;
1406 bool GreaterStashed;
1407 Lexer &Lex;
1408 SourceManager &SourceMgr;
1409 IdentifierTable IdentTable;
1410
1411 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001412 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001413 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1414 Tok.getLength());
1415 }
1416};
1417
Daniel Jasperbac016b2012-12-03 18:12:45 +00001418class Formatter : public UnwrappedLineConsumer {
1419public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001420 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1421 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001422 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001423 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001424 Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001425
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001426 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001427
Daniel Jasperbac016b2012-12-03 18:12:45 +00001428 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001429 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001430 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001431 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001432 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001433 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1434 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1435 Annotator.annotate();
1436 }
1437 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1438 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001439 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001440 const AnnotatedLine &TheLine = *I;
1441 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1442 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1443 TheLine.InPPDirective,
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001444 PreviousEndOfLineColumn);
Daniel Jasper995e8202013-01-14 13:08:07 +00001445 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, I, E);
1446 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1447 FitsOnALine, TheLine.First, Replaces,
1448 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001449 PreviousEndOfLineColumn = Formatter.format();
1450 } else {
1451 // If we did not reformat this unwrapped line, the column at the end of
1452 // the last token is unchanged - thus, we can calculate the end of the
1453 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001454 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001455 SourceMgr.getSpellingColumnNumber(
1456 TheLine.Last->FormatTok.Tok.getLocation()) +
1457 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1458 SourceMgr, Lex.getLangOpts()) -
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001459 1;
1460 }
1461 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001462 return Replaces;
1463 }
1464
1465private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001466 /// \brief Tries to merge lines into one.
1467 ///
1468 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1469 /// if possible; note that \c I will be incremented when lines are merged.
1470 ///
1471 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001472 bool tryFitMultipleLinesInOne(unsigned Indent,
1473 std::vector<AnnotatedLine>::iterator &I,
1474 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001475 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1476
1477 // Check whether the UnwrappedLine can be put onto a single line. If
1478 // so, this is bound to be the optimal solution (by definition) and we
1479 // don't need to analyze the entire solution space.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001480 unsigned Length = 0;
1481 if (!fitsIntoLimit(I->First, Limit, &Length))
Daniel Jasper995e8202013-01-14 13:08:07 +00001482 return false;
Daniel Jasperfd0ca972013-01-14 16:02:06 +00001483 if (Limit == Length)
1484 return true; // Couldn't fit a space.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001485 Limit -= Length + 1; // One space.
1486 if (I + 1 == E)
1487 return true;
Manuel Klimek517e8942013-01-11 17:54:10 +00001488
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001489 if (I->Last->is(tok::l_brace)) {
1490 tryMergeSimpleBlock(I, E, Limit);
1491 } else if (I->First.is(tok::kw_if)) {
1492 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001493 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1494 I->First.FormatTok.IsFirst)) {
1495 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001496 }
1497 return true;
1498 }
1499
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001500 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1501 std::vector<AnnotatedLine>::iterator E,
1502 unsigned Limit) {
1503 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001504 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1505 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001506 if (I + 2 != E && (I + 2)->InPPDirective &&
1507 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1508 return;
1509 if (!fitsIntoLimit((I + 1)->First, Limit)) return;
1510 join(Line, *(++I));
1511 }
1512
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001513 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1514 std::vector<AnnotatedLine>::iterator E,
1515 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001516 if (!Style.AllowShortIfStatementsOnASingleLine)
1517 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001518 AnnotatedLine &Line = *I;
1519 if (!fitsIntoLimit((I + 1)->First, Limit))
1520 return;
1521 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1522 return;
1523 // Only inline simple if's (no nested if or else).
1524 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1525 return;
1526 join(Line, *(++I));
1527 }
1528
1529 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1530 std::vector<AnnotatedLine>::iterator E,
1531 unsigned Limit){
Daniel Jasper995e8202013-01-14 13:08:07 +00001532 // Check that we still have three lines and they fit into the limit.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001533 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1534 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001535
1536 // First, check that the current line allows merging. This is the case if
1537 // we're not in a control flow statement and the last token is an opening
1538 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001539 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001540 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001541 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1542 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1543 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1544 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001545 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001546 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1547 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001548 if (!AllowedTokens)
1549 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001550
1551 // Second, check that the next line does not contain any braces - if it
1552 // does, readability declines when putting it into a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001553 const AnnotatedToken *Tok = &(I + 1)->First;
1554 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001555 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001556 do {
1557 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001558 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001559 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1560 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001561
1562 // Last, check that the third line contains a single closing brace.
Daniel Jasper995e8202013-01-14 13:08:07 +00001563 Tok = &(I + 2)->First;
1564 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1565 Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001566 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001567
Daniel Jasper995e8202013-01-14 13:08:07 +00001568 // If the merged line fits, we use that instead and skip the next two lines.
1569 Line.Last->Children.push_back((I + 1)->First);
1570 while (!Line.Last->Children.empty()) {
1571 Line.Last->Children[0].Parent = Line.Last;
1572 Line.Last = &Line.Last->Children[0];
Manuel Klimek517e8942013-01-11 17:54:10 +00001573 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001574
1575 join(Line, *(I + 1));
1576 join(Line, *(I + 2));
1577 I += 2;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001578 }
1579
1580 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1581 unsigned Limit) {
1582 unsigned LengthLine1 = 0;
1583 unsigned LengthLine2 = 0;
1584 if (!fitsIntoLimit((I + 1)->First, Limit, &LengthLine1) ||
1585 !fitsIntoLimit((I + 2)->First, Limit, &LengthLine2))
1586 return false;
1587 return LengthLine1 + LengthLine2 + 1 <= Limit; // One space.
Manuel Klimek517e8942013-01-11 17:54:10 +00001588 }
1589
Daniel Jasper995e8202013-01-14 13:08:07 +00001590 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1591 A.Last->Children.push_back(B.First);
1592 while (!A.Last->Children.empty()) {
1593 A.Last->Children[0].Parent = A.Last;
1594 A.Last = &A.Last->Children[0];
1595 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001596 }
1597
Daniel Jasper995e8202013-01-14 13:08:07 +00001598 bool touchesRanges(const AnnotatedLine &TheLine) {
1599 const FormatToken *First = &TheLine.First.FormatTok;
1600 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001601 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001602 First->Tok.getLocation(),
1603 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001604 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001605 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1606 Ranges[i].getBegin()) &&
1607 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1608 LineRange.getBegin()))
1609 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001610 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001611 return false;
1612 }
1613
1614 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001615 AnnotatedLines.push_back(
1616 AnnotatedLine(TheLine.RootToken, TheLine.Level, TheLine.InPPDirective));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001617 }
1618
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001619 /// \brief Add a new line and the required indent before the first Token
1620 /// of the \c UnwrappedLine if there was no structural parsing error.
1621 /// Returns the indent level of the \c UnwrappedLine.
1622 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1623 bool InPPDirective,
1624 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001625 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001626 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1627 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1628
1629 unsigned Newlines = std::min(Tok.NewlinesBefore,
1630 Style.MaxEmptyLinesToKeep + 1);
1631 if (Newlines == 0 && !Tok.IsFirst)
1632 Newlines = 1;
1633 unsigned Indent = Level * 2;
1634
1635 bool IsAccessModifier = false;
1636 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1637 RootToken.is(tok::kw_private))
1638 IsAccessModifier = true;
1639 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1640 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1641 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1642 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1643 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1644 IsAccessModifier = true;
1645
1646 if (IsAccessModifier &&
1647 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1648 Indent += Style.AccessModifierOffset;
1649 if (!InPPDirective || Tok.HasUnescapedNewline) {
1650 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1651 } else {
1652 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1653 SourceMgr, Replaces);
1654 }
1655 return Indent;
1656 }
1657
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001658 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001659 FormatStyle Style;
1660 Lexer &Lex;
1661 SourceManager &SourceMgr;
1662 tooling::Replacements Replaces;
1663 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001664 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001665 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001666};
1667
1668tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1669 SourceManager &SourceMgr,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001670 std::vector<CharSourceRange> Ranges,
1671 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001672 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001673 OwningPtr<DiagnosticConsumer> DiagPrinter;
1674 if (DiagClient == 0) {
1675 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1676 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1677 DiagClient = DiagPrinter.get();
1678 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001679 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001680 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001681 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001682 Diagnostics.setSourceManager(&SourceMgr);
1683 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001684 return formatter.format();
1685}
1686
Daniel Jasper46ef8522013-01-10 13:08:12 +00001687LangOptions getFormattingLangOpts() {
1688 LangOptions LangOpts;
1689 LangOpts.CPlusPlus = 1;
1690 LangOpts.CPlusPlus11 = 1;
1691 LangOpts.Bool = 1;
1692 LangOpts.ObjC1 = 1;
1693 LangOpts.ObjC2 = 1;
1694 return LangOpts;
1695}
1696
Daniel Jaspercd162382013-01-07 13:26:07 +00001697} // namespace format
1698} // namespace clang