blob: a6b9e2031d3c8fe726ecb12077def68f9570545e [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperf7935112012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasperda16db32013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000037 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000042 TT_ObjCMethodExpr,
Nico Weber9efe2912013-01-10 23:11:41 +000043 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000044 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000045 TT_OverloadedOperator,
46 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000047 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000048 TT_TemplateCloser,
49 TT_TemplateOpener,
50 TT_TrailingUnaryOperator,
51 TT_UnaryOperator,
52 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000053};
54
55enum LineType {
56 LT_Invalid,
57 LT_Other,
58 LT_PreprocessorDirective,
59 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000060 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000061 LT_ObjCMethodDecl,
62 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000063};
64
Daniel Jasper7c85fde2013-01-08 14:56:18 +000065class AnnotatedToken {
66public:
67 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000068 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
69 CanBreakBefore(false), MustBreakBefore(false),
70 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071
Daniel Jasper25837aa2013-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 Jasper7c85fde2013-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 Jasperf7935112012-12-03 18:12:45 +000081 TokenType Type;
82
Daniel Jasperf7935112012-12-03 18:12:45 +000083 bool SpaceRequiredBefore;
84 bool CanBreakBefore;
85 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000086
87 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000088
89 std::vector<AnnotatedToken> Children;
90 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000091};
92
Daniel Jasperf1e4b7d2013-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 Jasper7c85fde2013-01-08 14:56:18 +0000106static prec::Level getPrecedence(const AnnotatedToken &Tok) {
107 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000108}
109
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +0000117 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000118 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000119 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000120 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000121 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000122 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +0000133 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000134 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000135 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000136 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000137 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000138 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000139 return GoogleStyle;
140}
141
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000142FormatStyle getChromiumStyle() {
143 FormatStyle ChromiumStyle = getGoogleStyle();
144 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
145 return ChromiumStyle;
146}
147
Daniel Jasperf7935112012-12-03 18:12:45 +0000148struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000149 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000150 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000151 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000152};
153
Manuel Klimek0b689fd2013-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 Jasperf1e4b7d2013-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 Jasper25837aa2013-01-14 14:14:23 +0000193static bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit,
194 unsigned *Length = 0) {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000195 unsigned Columns = RootToken.FormatTok.TokenLength;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000196 if (Columns > Limit) return false;
Daniel Jasper2408a8c2013-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 Jasperf1e4b7d2013-01-14 13:08:07 +0000205 // FIXME: Remove this hack.
206 return false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000207 }
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000208 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000209 if (Length != 0)
210 *Length = Columns;
211 return true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000212}
213
Nico Weberc9d73612013-01-12 22:48:47 +0000214/// \brief Returns if a token is an Objective-C selector name.
215///
Nico Weber92c05392013-01-12 22:51:13 +0000216/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-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 Jasperf7935112012-12-03 18:12:45 +0000223class UnwrappedLineFormatter {
224public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000225 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000226 const AnnotatedLine &Line, unsigned FirstIndent,
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000227 bool FitsOnALine, const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000228 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000229 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000230 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000231 RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000232 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000233 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000234 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000235 }
236
Manuel Klimek1abf7892013-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 Jaspere9de2602012-12-06 09:56:08 +0000242 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000243 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000244 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000245 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000246 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000247 State.ForLoopVariablePos = 0;
248 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000249 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000250
251 // The first token has already been indented and thus consumed.
252 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000253
254 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000255 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000256 if (FitsOnALine) {
257 addTokenToState(false, false, State);
258 } else {
259 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
260 unsigned Break = calcPenalty(State, true, NoBreak);
261 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000262 if (State.NextToken != NULL &&
263 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
264 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
265 !fitsIntoLimit(*State.NextToken,
266 getColumnLimit() - State.Column - 1))
267 State.Stack.back().BreakAfterComma = true;
268 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000269 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000270 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000271 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000272 }
273
274private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000275 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000276 ParenState(unsigned Indent, unsigned LastSpace)
277 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
278 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000279
Daniel Jasperf7935112012-12-03 18:12:45 +0000280 /// \brief The position to which a specific parenthesis level needs to be
281 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000282 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000283
Daniel Jaspere9de2602012-12-06 09:56:08 +0000284 /// \brief The position of the last space on each level.
285 ///
286 /// Used e.g. to break like:
287 /// functionCall(Parameter, otherCall(
288 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000289 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000290
Daniel Jaspere9de2602012-12-06 09:56:08 +0000291 /// \brief The position the first "<<" operator encountered on each level.
292 ///
293 /// Used to align "<<" operators. 0 if no such operator has been encountered
294 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000295 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000296
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000297 /// \brief Whether a newline needs to be inserted before the block's closing
298 /// brace.
299 ///
300 /// We only want to insert a newline before the closing brace if there also
301 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000302 bool BreakBeforeClosingBrace;
303
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000304 bool BreakAfterComma;
305
Daniel Jasper337816e2013-01-11 10:22:12 +0000306 bool operator<(const ParenState &Other) const {
307 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000308 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000309 if (LastSpace != Other.LastSpace)
310 return LastSpace < Other.LastSpace;
311 if (FirstLessLess != Other.FirstLessLess)
312 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000313 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
314 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000315 if (BreakAfterComma != Other.BreakAfterComma)
316 return BreakAfterComma;
317 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000318 }
319 };
320
321 /// \brief The current state when indenting a unwrapped line.
322 ///
323 /// As the indenting tries different combinations this is copied by value.
324 struct LineState {
325 /// \brief The number of used columns in the current line.
326 unsigned Column;
327
328 /// \brief The token that needs to be next formatted.
329 const AnnotatedToken *NextToken;
330
331 /// \brief The parenthesis level of the first token on the current line.
332 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000333
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000334 /// \brief The column of the first variable in a for-loop declaration.
335 ///
336 /// Used to align the second variable if necessary.
337 unsigned ForLoopVariablePos;
338
339 /// \brief \c true if this line contains a continued for-loop section.
340 bool LineContainsContinuedForLoopSection;
341
Daniel Jasper337816e2013-01-11 10:22:12 +0000342 /// \brief A stack keeping track of properties applying to parenthesis
343 /// levels.
344 std::vector<ParenState> Stack;
345
346 /// \brief Comparison operator to be able to used \c LineState in \c map.
347 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000348 if (Other.NextToken != NextToken)
349 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 if (Other.Column != Column)
351 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000352 if (Other.StartOfLineLevel != StartOfLineLevel)
353 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000354 if (Other.ForLoopVariablePos != ForLoopVariablePos)
355 return Other.ForLoopVariablePos < ForLoopVariablePos;
356 if (Other.LineContainsContinuedForLoopSection !=
357 LineContainsContinuedForLoopSection)
358 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000359 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000360 }
361 };
362
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000363 /// \brief Appends the next token to \p State and updates information
364 /// necessary for indentation.
365 ///
366 /// Puts the token on the current line if \p Newline is \c true and adds a
367 /// line break and necessary indentation otherwise.
368 ///
369 /// If \p DryRun is \c false, also creates and stores the required
370 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000371 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000372 const AnnotatedToken &Current = *State.NextToken;
373 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000374 assert(State.Stack.size());
375 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000376
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000377 if (Current.Type == TT_ImplicitStringLiteral) {
378 moveStateToNextToken(State);
379 return;
380 }
381
Daniel Jasperf7935112012-12-03 18:12:45 +0000382 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000383 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000384 if (Current.is(tok::r_brace)) {
385 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000386 } else if (Current.is(tok::string_literal) &&
387 Previous.is(tok::string_literal)) {
388 State.Column = State.Column - Previous.FormatTok.TokenLength;
389 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].FirstLessLess != 0) {
391 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000392 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000393 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
394 Current.is(tok::period) || Previous.is(tok::question) ||
395 Previous.Type == TT_ConditionalExpr)) {
396 // Indent and extra 4 spaces after if we know the current expression is
397 // continued. Don't do that on the top level, as we already indent 4
398 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000399 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000400 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000401 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000402 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000403 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000404 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000405 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000406 }
407
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000408 // A line starting with a closing brace is assumed to be correct for the
409 // same level as before the opening brace.
410 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000411
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000412 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000413 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000414
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000415 if (!DryRun) {
416 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000417 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
418 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000419 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000420 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000421 WhitespaceStartColumn, Style, SourceMgr,
422 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000423 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000424
Daniel Jasper337816e2013-01-11 10:22:12 +0000425 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000426 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000428 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000429 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
430 State.ForLoopVariablePos = State.Column -
431 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000432
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000433 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
434 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000435 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000436
Daniel Jasperf7935112012-12-03 18:12:45 +0000437 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000438 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000439
Daniel Jasperbcab4302013-01-09 10:40:23 +0000440 // FIXME: Do we need to do this for assignments nested in other
441 // expressions?
442 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000443 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000444 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000446 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000447 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000448 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000449
Daniel Jasper206df732013-01-07 13:08:40 +0000450 // Top-level spaces that are not part of assignments are exempt as that
451 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000452 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000453 if (Spaces > 0 &&
454 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000455 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000456 }
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000457 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000459 }
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000460 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000462
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000463 /// \brief Mark the next token as consumed in \p State and modify its stacks
464 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000466 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000468
Daniel Jasper337816e2013-01-11 10:22:12 +0000469 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
470 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000471
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000472 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000473 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000474 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
475 Current.is(tok::l_brace) ||
476 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000477 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000478 if (Current.is(tok::l_brace)) {
479 // FIXME: This does not work with nested static initializers.
480 // Implement a better handling for static initializers and similar
481 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000482 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000483 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000484 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000485 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000486 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000487 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000488 }
489
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000490 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000491 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000492 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
493 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
494 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000495 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000496 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000497
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000498 if (State.NextToken->Children.empty())
499 State.NextToken = NULL;
500 else
501 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000502
503 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000504 }
505
Nico Weber49cbc2c2013-01-07 15:15:29 +0000506 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000507 unsigned splitPenalty(const AnnotatedToken &Tok) {
508 const AnnotatedToken &Left = Tok;
509 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000510
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000511 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
512 return 50;
513 if (Left.is(tok::equal) && Right.is(tok::l_brace))
514 return 150;
515
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000516 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000517 if (RootToken.is(tok::kw_for) &&
518 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000519 return 20;
520
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000521 if (Left.is(tok::semi) || Left.is(tok::comma) ||
522 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000524
525 // In Objective-C method expressions, prefer breaking before "param:" over
526 // breaking after it.
527 if (isObjCSelectorName(Right))
528 return 0;
529 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
530 return 20;
531
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000532 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000533 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000534
Daniel Jasper399d24b2013-01-09 07:06:56 +0000535 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
536 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000537 prec::Level Level = getPrecedence(Left);
538
539 // Breaking after an assignment leads to a bad result as the two sides of
540 // the assignment are visually very close together.
541 if (Level == prec::Assignment)
542 return 50;
543
Daniel Jasperde5c2072012-12-24 00:13:23 +0000544 if (Level != prec::Unknown)
545 return Level;
546
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000547 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000548 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000549
Daniel Jasperf7935112012-12-03 18:12:45 +0000550 return 3;
551 }
552
Daniel Jasper2df93312013-01-09 10:16:05 +0000553 unsigned getColumnLimit() {
554 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
555 }
556
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 /// \brief Calculate the number of lines needed to format the remaining part
558 /// of the unwrapped line.
559 ///
560 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000562 /// added after the previous token.
563 ///
564 /// \param StopAt is used for optimization. If we can determine that we'll
565 /// definitely need at least \p StopAt additional lines, we already know of a
566 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000567 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000569 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 return 0;
571
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000573 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000574 if (NewLine && !State.NextToken->CanBreakBefore &&
575 !(State.NextToken->is(tok::r_brace) &&
576 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000578 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000579 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000580 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000581 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000582 State.LineContainsContinuedForLoopSection)
583 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000584 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
585 State.NextToken->Type != TT_LineComment &&
586 State.Stack.back().BreakAfterComma)
587 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000588
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000589 unsigned CurrentPenalty = 0;
590 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000591 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000592 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000593 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000595 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000596 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000597 }
598
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000600
Daniel Jasper2df93312013-01-09 10:16:05 +0000601 // Exceeding column limit is bad, assign penalty.
602 if (State.Column > getColumnLimit()) {
603 unsigned ExcessCharacters = State.Column - getColumnLimit();
604 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
605 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000606
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 if (StopAt <= CurrentPenalty)
608 return UINT_MAX;
609 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000611 if (I != Memory.end()) {
612 // If this state has already been examined, we can safely return the
613 // previous result if we
614 // - have not hit the optimatization (and thus returned UINT_MAX) OR
615 // - are now computing for a smaller or equal StopAt.
616 unsigned SavedResult = I->second.first;
617 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000618 if (SavedResult != UINT_MAX)
619 return SavedResult + CurrentPenalty;
620 else if (StopAt <= SavedStopAt)
621 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000622 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000623
624 unsigned NoBreak = calcPenalty(State, false, StopAt);
625 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
626 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000627
628 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
629 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000630 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000631
632 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000633 }
634
Daniel Jasperf7935112012-12-03 18:12:45 +0000635 FormatStyle Style;
636 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000637 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000638 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000639 const bool FitsOnALine;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000640 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000641 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000642
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000643 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000644 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000645 StateMap Memory;
646
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 OptimizationParameters Parameters;
648};
649
650/// \brief Determines extra information about the tokens comprising an
651/// \c UnwrappedLine.
652class TokenAnnotator {
653public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000654 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
655 AnnotatedLine &Line)
656 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000657
658 /// \brief A parser that gathers additional information about tokens.
659 ///
660 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
661 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
662 /// into template parameter lists.
663 class AnnotatingParser {
664 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000665 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000666 : CurrentToken(&RootToken), KeywordVirtualFound(false),
667 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000668
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000669 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 while (CurrentToken != NULL) {
671 if (CurrentToken->is(tok::greater)) {
672 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000673 next();
674 return true;
675 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000676 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
677 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000678 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000679 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
680 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000682 if (!consumeToken())
683 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 }
685 return false;
686 }
687
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000688 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000689 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
690 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000691 while (CurrentToken != NULL) {
692 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000693 next();
694 return true;
695 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000697 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000698 if (!consumeToken())
699 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 }
701 return false;
702 }
703
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000704 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000705 if (!CurrentToken)
706 return false;
707
708 // A '[' could be an index subscript (after an indentifier or after
709 // ')' or ']'), or it could be the start of an Objective-C method
710 // expression.
711 AnnotatedToken *LSquare = CurrentToken->Parent;
712 bool StartsObjCMethodExpr =
713 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
714 LSquare->Parent->is(tok::l_square) ||
715 LSquare->Parent->is(tok::l_paren) ||
716 LSquare->Parent->is(tok::kw_return) ||
717 LSquare->Parent->is(tok::kw_throw) ||
718 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
719 true, true) > prec::Unknown;
720
721 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
722 if (StartsObjCMethodExpr) {
723 ColonIsObjCMethodExpr = true;
724 LSquare->Type = TT_ObjCMethodExpr;
725 }
726
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000727 while (CurrentToken != NULL) {
728 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000729 if (StartsObjCMethodExpr) {
730 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
731 CurrentToken->Type = TT_ObjCMethodExpr;
732 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 next();
734 return true;
735 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000736 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000738 if (!consumeToken())
739 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 }
741 return false;
742 }
743
Daniel Jasper83a54d22013-01-10 09:26:47 +0000744 bool parseBrace() {
745 while (CurrentToken != NULL) {
746 if (CurrentToken->is(tok::r_brace)) {
747 next();
748 return true;
749 }
750 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
751 return false;
752 if (!consumeToken())
753 return false;
754 }
755 // Lines can currently end with '{'.
756 return true;
757 }
758
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000759 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000760 while (CurrentToken != NULL) {
761 if (CurrentToken->is(tok::colon)) {
762 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000763 next();
764 return true;
765 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000766 if (!consumeToken())
767 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 }
769 return false;
770 }
771
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000772 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000773 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
774 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000775 next();
776 if (!parseAngle())
777 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000778 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000779 parseLine();
780 return true;
781 }
782 return false;
783 }
784
Daniel Jasperc0880a92013-01-04 18:52:56 +0000785 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000786 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000787 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000788 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000789 case tok::plus:
790 case tok::minus:
791 // At the start of the line, +/- specific ObjectiveC method
792 // declarations.
793 if (Tok->Parent == NULL)
794 Tok->Type = TT_ObjCMethodSpecifier;
795 break;
Nico Webera7252d82013-01-12 06:18:40 +0000796 case tok::colon:
797 // Colons from ?: are handled in parseConditional().
798 if (ColonIsObjCMethodExpr)
799 Tok->Type = TT_ObjCMethodExpr;
800 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000801 case tok::l_paren: {
Daniel Jasper25837aa2013-01-14 14:14:23 +0000802 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
803 TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000804 if (!parseParens())
805 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000806 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
807 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000808 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000809 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
810 CurrentToken->Type = TT_ObjCSelectorStart;
811 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000812 }
Nico Weber9efe2912013-01-10 23:11:41 +0000813 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000814 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000815 if (!parseSquare())
816 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000817 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000818 case tok::l_brace:
819 if (!parseBrace())
820 return false;
821 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000822 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000823 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000824 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000825 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000826 Tok->Type = TT_BinaryOperator;
827 CurrentToken = Tok;
828 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000829 }
830 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000831 case tok::r_paren:
832 case tok::r_square:
833 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000834 case tok::r_brace:
835 // Lines can start with '}'.
836 if (Tok->Parent != NULL)
837 return false;
838 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000840 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 break;
842 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000843 if (CurrentToken->is(tok::l_paren)) {
844 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000845 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000846 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
847 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000848 next();
849 }
850 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000851 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
852 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000853 next();
854 }
855 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000856 break;
857 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000858 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000859 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000860 case tok::kw_template:
861 parseTemplateDeclaration();
862 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000863 default:
864 break;
865 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000866 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000867 }
868
Daniel Jasper050948a52012-12-21 17:58:39 +0000869 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000870 next();
871 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
872 next();
873 while (CurrentToken != NULL) {
874 CurrentToken->Type = TT_ImplicitStringLiteral;
875 next();
876 }
877 } else {
878 while (CurrentToken != NULL) {
879 next();
880 }
881 }
882 }
883
884 void parseWarningOrError() {
885 next();
886 // We still want to format the whitespace left of the first token of the
887 // warning or error.
888 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000889 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000890 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +0000891 next();
892 }
893 }
894
895 void parsePreprocessorDirective() {
896 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000897 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000898 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000899 // Hashes in the middle of a line can lead to any strange token
900 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000902 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 switch (
904 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000905 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000906 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000907 parseIncludeDirective();
908 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000909 case tok::pp_error:
910 case tok::pp_warning:
911 parseWarningOrError();
912 break;
Daniel Jasper050948a52012-12-21 17:58:39 +0000913 default:
914 break;
915 }
916 }
917
Daniel Jasperda16db32013-01-07 10:48:50 +0000918 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000919 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000920 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000921 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000922 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000923 while (CurrentToken != NULL) {
924 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000925 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000926 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000927 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000929 if (KeywordVirtualFound)
930 return LT_VirtualFunctionDecl;
931 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000932 }
933
934 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000935 if (CurrentToken != NULL && !CurrentToken->Children.empty())
936 CurrentToken = &CurrentToken->Children[0];
937 else
938 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000939 }
940
941 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000942 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000943 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000944 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000945 };
946
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000947 void createAnnotatedTokens(AnnotatedToken &Current) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000948 if (Current.FormatTok.Children.empty()) {
949 Line.Last = &Current;
950 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000951 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
952 Current.Children.back().Parent = &Current;
953 createAnnotatedTokens(Current.Children.back());
954 }
955 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000956
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000957 void calculateExtraInformation(AnnotatedToken &Current) {
958 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
959
Manuel Klimek52b15152013-01-09 15:25:02 +0000960 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 Current.MustBreakBefore = true;
962 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +0000963 if (Current.Type == TT_LineComment) {
964 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
965 } else if (Current.Type == TT_CtorInitializerColon ||
966 Current.Parent->Type == TT_LineComment ||
967 (Current.is(tok::string_literal) &&
968 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +0000969 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000970 } else {
971 Current.MustBreakBefore = false;
972 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000973 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000974 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000975 if (!Current.Children.empty())
976 calculateExtraInformation(Current.Children[0]);
977 }
978
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000979 void annotate() {
980 Line.Last = &Line.First;
981 createAnnotatedTokens(Line.First);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000982
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000983 AnnotatingParser Parser(Line.First);
984 Line.Type = Parser.parseLine();
985 if (Line.Type == LT_Invalid)
986 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000987
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000988 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000989
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000990 if (Line.First.Type == TT_ObjCMethodSpecifier)
991 Line.Type = LT_ObjCMethodDecl;
992 else if (Line.First.Type == TT_ObjCDecl)
993 Line.Type = LT_ObjCDecl;
994 else if (Line.First.Type == TT_ObjCProperty)
995 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000996
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000997 Line.First.SpaceRequiredBefore = true;
998 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
999 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001000
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001001 if (!Line.First.Children.empty())
1002 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001003 }
1004
1005private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001006 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1007 if (getPrecedence(Current) == prec::Assignment ||
1008 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1009 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001010
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001011 if (Current.Type == TT_Unknown) {
1012 if (Current.is(tok::star) || Current.is(tok::amp)) {
1013 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001014 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1015 Current.is(tok::caret)) {
1016 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001017 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1018 Current.Type = determineIncrementUsage(Current);
1019 } else if (Current.is(tok::exclaim)) {
1020 Current.Type = TT_UnaryOperator;
1021 } else if (isBinaryOperator(Current)) {
1022 Current.Type = TT_BinaryOperator;
1023 } else if (Current.is(tok::comment)) {
1024 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1025 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001026 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001027 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001028 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001029 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001030 } else if (Current.is(tok::r_paren) &&
1031 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001032 Current.Parent->Type == TT_TemplateCloser) &&
1033 (Current.Children.empty() ||
1034 (Current.Children[0].isNot(tok::equal) &&
1035 Current.Children[0].isNot(tok::semi) &&
1036 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001037 // FIXME: We need to get smarter and understand more cases of casts.
1038 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001039 } else if (Current.is(tok::at) && Current.Children.size()) {
1040 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1041 case tok::objc_interface:
1042 case tok::objc_implementation:
1043 case tok::objc_protocol:
1044 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001045 break;
1046 case tok::objc_property:
1047 Current.Type = TT_ObjCProperty;
1048 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001049 default:
1050 break;
1051 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 }
1053 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054
1055 if (!Current.Children.empty())
1056 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001057 }
1058
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001059 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001060 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001061 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 }
1063
Daniel Jasper71945272013-01-15 14:27:39 +00001064 /// \brief Returns the previous token ignoring comments.
1065 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1066 const AnnotatedToken *PrevToken = Tok.Parent;
1067 while (PrevToken != NULL && PrevToken->is(tok::comment))
1068 PrevToken = PrevToken->Parent;
1069 return PrevToken;
1070 }
1071
1072 /// \brief Returns the next token ignoring comments.
1073 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1074 if (Tok.Children.empty())
1075 return NULL;
1076 const AnnotatedToken *NextToken = &Tok.Children[0];
1077 while (NextToken->is(tok::comment)) {
1078 if (NextToken->Children.empty())
1079 return NULL;
1080 NextToken = &NextToken->Children[0];
1081 }
1082 return NextToken;
1083 }
1084
1085 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001086 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001087 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1088 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001089 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001090
1091 const AnnotatedToken *NextToken = getNextToken(Tok);
1092 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001093 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001094
Daniel Jasper71945272013-01-15 14:27:39 +00001095 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1096 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1097 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1098 PrevToken->Type == TT_BinaryOperator ||
1099 PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001100 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001101
Daniel Jasper71945272013-01-15 14:27:39 +00001102 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1103 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1104 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1105 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1106 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1107 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1108 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001109 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001110
Daniel Jasper71945272013-01-15 14:27:39 +00001111 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1112 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001113 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001114
Daniel Jasper426702d2012-12-05 07:51:39 +00001115 // It is very unlikely that we are going to find a pointer or reference type
1116 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001117 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001118 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001119
Daniel Jasperda16db32013-01-07 10:48:50 +00001120 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001121 }
1122
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001123 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001124 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1125 if (PrevToken == NULL)
1126 return TT_UnaryOperator;
1127
Daniel Jasper8dd40472012-12-21 09:41:31 +00001128 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001129 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1130 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1131 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1132 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1133 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001134 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001135
1136 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001137 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001138 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001139
1140 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001141 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001142 }
1143
1144 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001145 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001146 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1147 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001148 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001149 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1150 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001151 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001152
Daniel Jasperda16db32013-01-07 10:48:50 +00001153 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001154 }
1155
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001156 bool spaceRequiredBetween(const AnnotatedToken &Left,
1157 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001158 if (Right.is(tok::hashhash))
1159 return Left.is(tok::hash);
1160 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1161 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001162 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1163 return false;
Nico Webera6087752013-01-10 20:12:55 +00001164 if (Right.is(tok::less) &&
1165 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001166 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001167 return true;
1168 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1169 return false;
1170 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1171 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001172 if (Left.is(tok::at) &&
1173 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1174 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001175 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1176 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001177 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001178 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1179 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001180 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001181 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001182 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1183 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001184 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001185 return Right.FormatTok.Tok.isLiteral() ||
1186 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001187 if (Right.is(tok::star) && Left.is(tok::l_paren))
1188 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001189 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1190 return false;
1191 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001192 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001193 if (Left.is(tok::coloncolon) ||
1194 (Right.is(tok::coloncolon) &&
1195 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001196 return false;
1197 if (Left.is(tok::period) || Right.is(tok::period))
1198 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001199 if (Left.is(tok::colon))
1200 return Left.Type != TT_ObjCMethodExpr;
1201 if (Right.is(tok::colon))
1202 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001203 if (Left.is(tok::l_paren))
1204 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001205 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001206 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001207 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001208 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001209 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1210 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001211 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001212 if (Left.is(tok::at) &&
1213 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001214 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001215 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1216 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001217 return true;
1218 }
1219
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001220 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001221 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001222 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1223 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001224 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001225 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001226 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001227 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001228 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1229 if (Tok.Type == TT_ObjCSelectorStart)
1230 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001231 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001232 // Don't space between ')' and <id>
1233 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001234 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001235 // Don't space between ':' and '('
1236 return false;
1237 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001238 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001239 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1240 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001241
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001242 if (Tok.Parent->is(tok::comma))
1243 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001244 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001245 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001246 if (Tok.Type == TT_OverloadedOperator)
1247 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001248 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001249 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001250 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001251 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001252 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001253 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001254 if (Tok.Parent->Type == TT_UnaryOperator ||
1255 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001256 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001257 if (Tok.Type == TT_UnaryOperator)
1258 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001259 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1260 (Tok.Parent->isNot(tok::colon) ||
1261 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001262 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1263 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001264 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1265 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001266 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001267 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001268 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001269 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001270 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001271 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001272 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001273 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001274 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001275 }
1276
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001277 bool canBreakBefore(const AnnotatedToken &Right) {
1278 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001279 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001280 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1281 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001282 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001283 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1284 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001285 // Don't break this identifier as ':' or identifier
1286 // before it will break.
1287 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001288 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1289 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001290 // Don't break at ':' if identifier before it can beak.
1291 return false;
1292 }
Nico Webera7252d82013-01-12 06:18:40 +00001293 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1294 return false;
1295 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1296 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001297 if (isObjCSelectorName(Right))
1298 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001299 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001300 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001301 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001302 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001303 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001304 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001305 return false;
1306
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001307 if (Right.is(tok::comment))
Daniel Jasper942ee722013-01-13 16:10:20 +00001308 // We rely on MustBreakBefore being set correctly here as we should not
1309 // change the "binding" behavior of a comment.
1310 return false;
1311
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001312 // We only break before r_brace if there was a corresponding break before
1313 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1314 if (Right.is(tok::r_brace))
1315 return false;
1316
Daniel Jasper71945272013-01-15 14:27:39 +00001317 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001318 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001319 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1320 Left.is(tok::comma) || Right.is(tok::lessless) ||
1321 Right.is(tok::arrow) || Right.is(tok::period) ||
1322 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001323 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1324 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1325 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001326 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001327 }
1328
Daniel Jasperf7935112012-12-03 18:12:45 +00001329 FormatStyle Style;
1330 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001331 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001332 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001333};
1334
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001335class LexerBasedFormatTokenSource : public FormatTokenSource {
1336public:
1337 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001338 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001339 IdentTable(Lex.getLangOpts()) {
1340 Lex.SetKeepWhitespaceMode(true);
1341 }
1342
1343 virtual FormatToken getNextToken() {
1344 if (GreaterStashed) {
1345 FormatTok.NewlinesBefore = 0;
1346 FormatTok.WhiteSpaceStart =
1347 FormatTok.Tok.getLocation().getLocWithOffset(1);
1348 FormatTok.WhiteSpaceLength = 0;
1349 GreaterStashed = false;
1350 return FormatTok;
1351 }
1352
1353 FormatTok = FormatToken();
1354 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001355 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001356 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001357 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1358 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001359
1360 // Consume and record whitespace until we find a significant token.
1361 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001362 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001363 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1364 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001365 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1366
1367 if (FormatTok.Tok.is(tok::eof))
1368 return FormatTok;
1369 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001370 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001371 }
Manuel Klimekef920692013-01-07 07:56:50 +00001372
1373 // Now FormatTok is the next non-whitespace token.
1374 FormatTok.TokenLength = Text.size();
1375
Manuel Klimek1abf7892013-01-04 23:34:14 +00001376 // In case the token starts with escaped newlines, we want to
1377 // take them into account as whitespace - this pattern is quite frequent
1378 // in macro definitions.
1379 // FIXME: What do we want to do with other escaped spaces, and escaped
1380 // spaces or newlines in the middle of tokens?
1381 // FIXME: Add a more explicit test.
1382 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001383 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001384 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001385 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001386 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001387 }
1388
1389 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001390 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001391 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001392 FormatTok.Tok.setKind(Info.getTokenID());
1393 }
1394
1395 if (FormatTok.Tok.is(tok::greatergreater)) {
1396 FormatTok.Tok.setKind(tok::greater);
1397 GreaterStashed = true;
1398 }
1399
1400 return FormatTok;
1401 }
1402
1403private:
1404 FormatToken FormatTok;
1405 bool GreaterStashed;
1406 Lexer &Lex;
1407 SourceManager &SourceMgr;
1408 IdentifierTable IdentTable;
1409
1410 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001411 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001412 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1413 Tok.getLength());
1414 }
1415};
1416
Daniel Jasperf7935112012-12-03 18:12:45 +00001417class Formatter : public UnwrappedLineConsumer {
1418public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001419 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1420 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001421 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001422 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001423 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001424
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001425 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001426
Daniel Jasperf7935112012-12-03 18:12:45 +00001427 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001428 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001429 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001430 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001431 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001432 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1433 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1434 Annotator.annotate();
1435 }
1436 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1437 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001438 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001439 const AnnotatedLine &TheLine = *I;
1440 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1441 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1442 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001443 PreviousEndOfLineColumn);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001444 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, I, E);
1445 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1446 FitsOnALine, TheLine.First, Replaces,
1447 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001448 PreviousEndOfLineColumn = Formatter.format();
1449 } else {
1450 // If we did not reformat this unwrapped line, the column at the end of
1451 // the last token is unchanged - thus, we can calculate the end of the
1452 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001453 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001454 SourceMgr.getSpellingColumnNumber(
1455 TheLine.Last->FormatTok.Tok.getLocation()) +
1456 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1457 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001458 1;
1459 }
1460 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001461 return Replaces;
1462 }
1463
1464private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001465 /// \brief Tries to merge lines into one.
1466 ///
1467 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1468 /// if possible; note that \c I will be incremented when lines are merged.
1469 ///
1470 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001471 bool tryFitMultipleLinesInOne(unsigned Indent,
1472 std::vector<AnnotatedLine>::iterator &I,
1473 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001474 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1475
1476 // Check whether the UnwrappedLine can be put onto a single line. If
1477 // so, this is bound to be the optimal solution (by definition) and we
1478 // don't need to analyze the entire solution space.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001479 unsigned Length = 0;
1480 if (!fitsIntoLimit(I->First, Limit, &Length))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001481 return false;
Daniel Jasper3e9218e2013-01-14 16:02:06 +00001482 if (Limit == Length)
1483 return true; // Couldn't fit a space.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001484 Limit -= Length + 1; // One space.
1485 if (I + 1 == E)
1486 return true;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001487
Daniel Jasper25837aa2013-01-14 14:14:23 +00001488 if (I->Last->is(tok::l_brace)) {
1489 tryMergeSimpleBlock(I, E, Limit);
1490 } else if (I->First.is(tok::kw_if)) {
1491 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001492 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1493 I->First.FormatTok.IsFirst)) {
1494 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001495 }
1496 return true;
1497 }
1498
Daniel Jasper39825ea2013-01-14 15:40:57 +00001499 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1500 std::vector<AnnotatedLine>::iterator E,
1501 unsigned Limit) {
1502 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001503 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1504 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001505 if (I + 2 != E && (I + 2)->InPPDirective &&
1506 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1507 return;
1508 if (!fitsIntoLimit((I + 1)->First, Limit)) return;
1509 join(Line, *(++I));
1510 }
1511
Daniel Jasper25837aa2013-01-14 14:14:23 +00001512 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1513 std::vector<AnnotatedLine>::iterator E,
1514 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001515 if (!Style.AllowShortIfStatementsOnASingleLine)
1516 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001517 AnnotatedLine &Line = *I;
1518 if (!fitsIntoLimit((I + 1)->First, Limit))
1519 return;
1520 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1521 return;
1522 // Only inline simple if's (no nested if or else).
1523 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1524 return;
1525 join(Line, *(++I));
1526 }
1527
1528 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1529 std::vector<AnnotatedLine>::iterator E,
1530 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001531 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001532 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1533 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001534
1535 // First, check that the current line allows merging. This is the case if
1536 // we're not in a control flow statement and the last token is an opening
1537 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001538 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001539 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001540 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1541 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1542 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1543 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001544 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001545 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1546 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001547 if (!AllowedTokens)
1548 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001549
1550 // Second, check that the next line does not contain any braces - if it
1551 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 const AnnotatedToken *Tok = &(I + 1)->First;
1553 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001554 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001555 do {
1556 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001557 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001558 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1559 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001560
1561 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001562 Tok = &(I + 2)->First;
1563 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1564 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001565 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001566
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001567 // If the merged line fits, we use that instead and skip the next two lines.
1568 Line.Last->Children.push_back((I + 1)->First);
1569 while (!Line.Last->Children.empty()) {
1570 Line.Last->Children[0].Parent = Line.Last;
1571 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001572 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001573
1574 join(Line, *(I + 1));
1575 join(Line, *(I + 2));
1576 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001577 }
1578
1579 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1580 unsigned Limit) {
1581 unsigned LengthLine1 = 0;
1582 unsigned LengthLine2 = 0;
1583 if (!fitsIntoLimit((I + 1)->First, Limit, &LengthLine1) ||
1584 !fitsIntoLimit((I + 2)->First, Limit, &LengthLine2))
1585 return false;
1586 return LengthLine1 + LengthLine2 + 1 <= Limit; // One space.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001587 }
1588
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001589 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1590 A.Last->Children.push_back(B.First);
1591 while (!A.Last->Children.empty()) {
1592 A.Last->Children[0].Parent = A.Last;
1593 A.Last = &A.Last->Children[0];
1594 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001595 }
1596
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001597 bool touchesRanges(const AnnotatedLine &TheLine) {
1598 const FormatToken *First = &TheLine.First.FormatTok;
1599 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001600 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001601 First->Tok.getLocation(),
1602 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001603 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001604 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1605 Ranges[i].getBegin()) &&
1606 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1607 LineRange.getBegin()))
1608 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001609 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001610 return false;
1611 }
1612
1613 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001614 AnnotatedLines.push_back(
1615 AnnotatedLine(TheLine.RootToken, TheLine.Level, TheLine.InPPDirective));
Daniel Jasperf7935112012-12-03 18:12:45 +00001616 }
1617
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001618 /// \brief Add a new line and the required indent before the first Token
1619 /// of the \c UnwrappedLine if there was no structural parsing error.
1620 /// Returns the indent level of the \c UnwrappedLine.
1621 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1622 bool InPPDirective,
1623 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001624 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001625 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1626 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1627
1628 unsigned Newlines = std::min(Tok.NewlinesBefore,
1629 Style.MaxEmptyLinesToKeep + 1);
1630 if (Newlines == 0 && !Tok.IsFirst)
1631 Newlines = 1;
1632 unsigned Indent = Level * 2;
1633
1634 bool IsAccessModifier = false;
1635 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1636 RootToken.is(tok::kw_private))
1637 IsAccessModifier = true;
1638 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1639 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1640 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1641 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1642 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1643 IsAccessModifier = true;
1644
1645 if (IsAccessModifier &&
1646 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1647 Indent += Style.AccessModifierOffset;
1648 if (!InPPDirective || Tok.HasUnescapedNewline) {
1649 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1650 } else {
1651 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1652 SourceMgr, Replaces);
1653 }
1654 return Indent;
1655 }
1656
Alexander Kornienko116ba682013-01-14 11:34:14 +00001657 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001658 FormatStyle Style;
1659 Lexer &Lex;
1660 SourceManager &SourceMgr;
1661 tooling::Replacements Replaces;
1662 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001663 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001664 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001665};
1666
1667tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1668 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001669 std::vector<CharSourceRange> Ranges,
1670 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001671 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001672 OwningPtr<DiagnosticConsumer> DiagPrinter;
1673 if (DiagClient == 0) {
1674 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1675 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1676 DiagClient = DiagPrinter.get();
1677 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001678 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001679 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001680 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001681 Diagnostics.setSourceManager(&SourceMgr);
1682 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001683 return formatter.format();
1684}
1685
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001686LangOptions getFormattingLangOpts() {
1687 LangOptions LangOpts;
1688 LangOpts.CPlusPlus = 1;
1689 LangOpts.CPlusPlus11 = 1;
1690 LangOpts.Bool = 1;
1691 LangOpts.ObjC1 = 1;
1692 LangOpts.ObjC2 = 1;
1693 return LangOpts;
1694}
1695
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001696} // namespace format
1697} // namespace clang