blob: ec8b02ffcadf8a5e2451c5248605fab8e3976384 [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,
Daniel Jasperda16db32013-01-07 10:48:50 +000037 TT_DirectorySeparator,
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
72 bool is(tok::TokenKind Kind) const {
73 return FormatTok.Tok.is(Kind);
74 }
75 bool isNot(tok::TokenKind Kind) const {
76 return FormatTok.Tok.isNot(Kind);
77 }
78 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
79 return FormatTok.Tok.isObjCAtKeyword(Kind);
80 }
81
82 FormatToken FormatTok;
83
Daniel Jasperf7935112012-12-03 18:12:45 +000084 TokenType Type;
85
Daniel Jasperf7935112012-12-03 18:12:45 +000086 bool SpaceRequiredBefore;
87 bool CanBreakBefore;
88 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000089
90 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000091
92 std::vector<AnnotatedToken> Children;
93 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000094};
95
Daniel Jasper7c85fde2013-01-08 14:56:18 +000096static prec::Level getPrecedence(const AnnotatedToken &Tok) {
97 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000098}
99
Daniel Jasperf7935112012-12-03 18:12:45 +0000100FormatStyle getLLVMStyle() {
101 FormatStyle LLVMStyle;
102 LLVMStyle.ColumnLimit = 80;
103 LLVMStyle.MaxEmptyLinesToKeep = 1;
104 LLVMStyle.PointerAndReferenceBindToType = false;
105 LLVMStyle.AccessModifierOffset = -2;
106 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000107 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000108 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000109 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000110 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000111 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000112 return LLVMStyle;
113}
114
115FormatStyle getGoogleStyle() {
116 FormatStyle GoogleStyle;
117 GoogleStyle.ColumnLimit = 80;
118 GoogleStyle.MaxEmptyLinesToKeep = 1;
119 GoogleStyle.PointerAndReferenceBindToType = true;
120 GoogleStyle.AccessModifierOffset = -1;
121 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000122 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000123 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000124 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000125 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000126 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000127 return GoogleStyle;
128}
129
130struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000131 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000132 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000133 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000134};
135
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000136/// \brief Replaces the whitespace in front of \p Tok. Only call once for
137/// each \c FormatToken.
138static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
139 unsigned Spaces, const FormatStyle &Style,
140 SourceManager &SourceMgr,
141 tooling::Replacements &Replaces) {
142 Replaces.insert(tooling::Replacement(
143 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
144 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
145}
146
147/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
148/// backslashes to escape newlines inside a preprocessor directive.
149///
150/// This function and \c replaceWhitespace have the same behavior if
151/// \c Newlines == 0.
152static void replacePPWhitespace(
153 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
154 unsigned WhitespaceStartColumn, const FormatStyle &Style,
155 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
156 std::string NewLineText;
157 if (NewLines > 0) {
158 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
159 WhitespaceStartColumn);
160 for (unsigned i = 0; i < NewLines; ++i) {
161 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
162 NewLineText += "\\\n";
163 Offset = 0;
164 }
165 }
166 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
167 Tok.FormatTok.WhiteSpaceLength,
168 NewLineText + std::string(Spaces, ' ')));
169}
170
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000171/// \brief Checks whether the (remaining) \c UnwrappedLine starting with
172/// \p RootToken fits into \p Limit columns.
173bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit) {
174 unsigned Columns = RootToken.FormatTok.TokenLength;
175 bool FitsOnALine = true;
176 const AnnotatedToken *Tok = &RootToken;
177 while (!Tok->Children.empty()) {
178 Tok = &Tok->Children[0];
179 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
180 // A special case for the colon of a constructor initializer as this only
181 // needs to be put on a new line if the line needs to be split.
182 if (Columns > Limit ||
183 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
184 FitsOnALine = false;
185 break;
186 }
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000187 }
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000188 return FitsOnALine;
189}
190
Daniel Jasperf7935112012-12-03 18:12:45 +0000191class UnwrappedLineFormatter {
192public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000193 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
194 const UnwrappedLine &Line, unsigned FirstIndent,
195 bool FitsOnALine, LineType CurrentLineType,
196 const AnnotatedToken &RootToken,
197 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000198 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000199 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000200 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000201 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000202 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000203 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000204 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000205 }
206
Manuel Klimek1abf7892013-01-04 23:34:14 +0000207 /// \brief Formats an \c UnwrappedLine.
208 ///
209 /// \returns The column after the last token in the last line of the
210 /// \c UnwrappedLine.
211 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000212 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000213 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000214 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000215 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000216 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000217 State.ForLoopVariablePos = 0;
218 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000219 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000220
221 // The first token has already been indented and thus consumed.
222 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000223
224 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000225 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000226 if (FitsOnALine) {
227 addTokenToState(false, false, State);
228 } else {
229 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
230 unsigned Break = calcPenalty(State, true, NoBreak);
231 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000232 if (State.NextToken != NULL &&
233 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
234 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
235 !fitsIntoLimit(*State.NextToken,
236 getColumnLimit() - State.Column - 1))
237 State.Stack.back().BreakAfterComma = true;
238 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000239 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000240 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000241 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 }
243
244private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000245 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000246 ParenState(unsigned Indent, unsigned LastSpace)
247 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
248 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000249
Daniel Jasperf7935112012-12-03 18:12:45 +0000250 /// \brief The position to which a specific parenthesis level needs to be
251 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000252 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000253
Daniel Jaspere9de2602012-12-06 09:56:08 +0000254 /// \brief The position of the last space on each level.
255 ///
256 /// Used e.g. to break like:
257 /// functionCall(Parameter, otherCall(
258 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000259 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000260
Daniel Jaspere9de2602012-12-06 09:56:08 +0000261 /// \brief The position the first "<<" operator encountered on each level.
262 ///
263 /// Used to align "<<" operators. 0 if no such operator has been encountered
264 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000265 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000266
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000267 /// \brief Whether a newline needs to be inserted before the block's closing
268 /// brace.
269 ///
270 /// We only want to insert a newline before the closing brace if there also
271 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000272 bool BreakBeforeClosingBrace;
273
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000274 bool BreakAfterComma;
275
Daniel Jasper337816e2013-01-11 10:22:12 +0000276 bool operator<(const ParenState &Other) const {
277 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000278 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000279 if (LastSpace != Other.LastSpace)
280 return LastSpace < Other.LastSpace;
281 if (FirstLessLess != Other.FirstLessLess)
282 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000283 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
284 return BreakBeforeClosingBrace;
285 return BreakAfterComma;
Daniel Jasper337816e2013-01-11 10:22:12 +0000286 }
287 };
288
289 /// \brief The current state when indenting a unwrapped line.
290 ///
291 /// As the indenting tries different combinations this is copied by value.
292 struct LineState {
293 /// \brief The number of used columns in the current line.
294 unsigned Column;
295
296 /// \brief The token that needs to be next formatted.
297 const AnnotatedToken *NextToken;
298
299 /// \brief The parenthesis level of the first token on the current line.
300 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000301
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000302 /// \brief The column of the first variable in a for-loop declaration.
303 ///
304 /// Used to align the second variable if necessary.
305 unsigned ForLoopVariablePos;
306
307 /// \brief \c true if this line contains a continued for-loop section.
308 bool LineContainsContinuedForLoopSection;
309
Daniel Jasper337816e2013-01-11 10:22:12 +0000310 /// \brief A stack keeping track of properties applying to parenthesis
311 /// levels.
312 std::vector<ParenState> Stack;
313
314 /// \brief Comparison operator to be able to used \c LineState in \c map.
315 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000316 if (Other.NextToken != NextToken)
317 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000318 if (Other.Column != Column)
319 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000320 if (Other.StartOfLineLevel != StartOfLineLevel)
321 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000322 if (Other.ForLoopVariablePos != ForLoopVariablePos)
323 return Other.ForLoopVariablePos < ForLoopVariablePos;
324 if (Other.LineContainsContinuedForLoopSection !=
325 LineContainsContinuedForLoopSection)
326 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000327 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 }
329 };
330
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000331 /// \brief Appends the next token to \p State and updates information
332 /// necessary for indentation.
333 ///
334 /// Puts the token on the current line if \p Newline is \c true and adds a
335 /// line break and necessary indentation otherwise.
336 ///
337 /// If \p DryRun is \c false, also creates and stores the required
338 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000339 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000340 const AnnotatedToken &Current = *State.NextToken;
341 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000342 assert(State.Stack.size());
343 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000344
345 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000346 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000347 if (Current.is(tok::r_brace)) {
348 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000349 } else if (Current.is(tok::string_literal) &&
350 Previous.is(tok::string_literal)) {
351 State.Column = State.Column - Previous.FormatTok.TokenLength;
352 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000353 State.Stack[ParenLevel].FirstLessLess != 0) {
354 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000355 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000356 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
357 Current.is(tok::period) || Previous.is(tok::question) ||
358 Previous.Type == TT_ConditionalExpr)) {
359 // Indent and extra 4 spaces after if we know the current expression is
360 // continued. Don't do that on the top level, as we already indent 4
361 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000363 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000364 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000365 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000366 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000367 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000368 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000369 }
370
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000371 // A line starting with a closing brace is assumed to be correct for the
372 // same level as before the opening brace.
373 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000374
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000375 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000376 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000377
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000378 if (!DryRun) {
379 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000380 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
381 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000382 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000383 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000384 WhitespaceStartColumn, Style, SourceMgr,
385 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000386 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000387
Daniel Jasper337816e2013-01-11 10:22:12 +0000388 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000389 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000392 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
393 State.ForLoopVariablePos = State.Column -
394 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000395
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000396 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
397 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000398 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000399
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000401 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000402
Daniel Jasperbcab4302013-01-09 10:40:23 +0000403 // FIXME: Do we need to do this for assignments nested in other
404 // expressions?
405 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000406 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000407 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000408 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000409 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000410 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000411 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000412
Daniel Jasper206df732013-01-07 13:08:40 +0000413 // Top-level spaces that are not part of assignments are exempt as that
414 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000415 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000416 if (Spaces > 0 &&
417 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000418 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000419 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000420 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000421 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000422 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000423 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000424 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000426 /// \brief Mark the next token as consumed in \p State and modify its stacks
427 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000428 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000429 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000430 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000431
Daniel Jasper337816e2013-01-11 10:22:12 +0000432 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
433 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000434
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000435 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000436 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000437 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
438 Current.is(tok::l_brace) ||
439 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000440 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000441 if (Current.is(tok::l_brace)) {
442 // FIXME: This does not work with nested static initializers.
443 // Implement a better handling for static initializers and similar
444 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000446 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000448 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000450 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000451 }
452
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000453 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000454 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000455 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
456 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
457 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000460
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000461 if (State.NextToken->Children.empty())
462 State.NextToken = NULL;
463 else
464 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000465
466 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000467 }
468
Nico Weber49cbc2c2013-01-07 15:15:29 +0000469 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000470 unsigned splitPenalty(const AnnotatedToken &Tok) {
471 const AnnotatedToken &Left = Tok;
472 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000473
474 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000475 if (RootToken.is(tok::kw_for) &&
476 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000477 return 20;
478
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000479 if (Left.is(tok::semi) || Left.is(tok::comma) ||
480 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000481 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000482 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000483 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000484
Daniel Jasper399d24b2013-01-09 07:06:56 +0000485 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
486 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000487 prec::Level Level = getPrecedence(Left);
488
489 // Breaking after an assignment leads to a bad result as the two sides of
490 // the assignment are visually very close together.
491 if (Level == prec::Assignment)
492 return 50;
493
Daniel Jasperde5c2072012-12-24 00:13:23 +0000494 if (Level != prec::Unknown)
495 return Level;
496
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000497 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000498 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000499
Daniel Jasperf7935112012-12-03 18:12:45 +0000500 return 3;
501 }
502
Daniel Jasper2df93312013-01-09 10:16:05 +0000503 unsigned getColumnLimit() {
504 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
505 }
506
Daniel Jasperf7935112012-12-03 18:12:45 +0000507 /// \brief Calculate the number of lines needed to format the remaining part
508 /// of the unwrapped line.
509 ///
510 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000511 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000512 /// added after the previous token.
513 ///
514 /// \param StopAt is used for optimization. If we can determine that we'll
515 /// definitely need at least \p StopAt additional lines, we already know of a
516 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000517 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000518 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000519 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000520 return 0;
521
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000522 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000524 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000526 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000527 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000528 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000529 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000530 State.LineContainsContinuedForLoopSection)
531 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000532 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
533 State.NextToken->Type != TT_LineComment &&
534 State.Stack.back().BreakAfterComma)
535 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000536
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000537 unsigned CurrentPenalty = 0;
538 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000540 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000541 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000543 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000545 }
546
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000547 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000548
Daniel Jasper2df93312013-01-09 10:16:05 +0000549 // Exceeding column limit is bad, assign penalty.
550 if (State.Column > getColumnLimit()) {
551 unsigned ExcessCharacters = State.Column - getColumnLimit();
552 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
553 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000554
Daniel Jasperf7935112012-12-03 18:12:45 +0000555 if (StopAt <= CurrentPenalty)
556 return UINT_MAX;
557 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000559 if (I != Memory.end()) {
560 // If this state has already been examined, we can safely return the
561 // previous result if we
562 // - have not hit the optimatization (and thus returned UINT_MAX) OR
563 // - are now computing for a smaller or equal StopAt.
564 unsigned SavedResult = I->second.first;
565 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000566 if (SavedResult != UINT_MAX)
567 return SavedResult + CurrentPenalty;
568 else if (StopAt <= SavedStopAt)
569 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000570 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000571
572 unsigned NoBreak = calcPenalty(State, false, StopAt);
573 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
574 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000575
576 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
577 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000578 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000579
580 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000581 }
582
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 FormatStyle Style;
584 SourceManager &SourceMgr;
585 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000586 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000587 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000588 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000589 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000592 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000593 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000594 StateMap Memory;
595
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 OptimizationParameters Parameters;
597};
598
599/// \brief Determines extra information about the tokens comprising an
600/// \c UnwrappedLine.
601class TokenAnnotator {
602public:
603 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000604 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000605 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000606 RootToken(Line.RootToken) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000607
608 /// \brief A parser that gathers additional information about tokens.
609 ///
610 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
611 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
612 /// into template parameter lists.
613 class AnnotatingParser {
614 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000615 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000616 : CurrentToken(&RootToken), KeywordVirtualFound(false),
617 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000618
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000619 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000620 while (CurrentToken != NULL) {
621 if (CurrentToken->is(tok::greater)) {
622 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 next();
624 return true;
625 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000626 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
627 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000629 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
630 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000631 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000632 if (!consumeToken())
633 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000634 }
635 return false;
636 }
637
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000638 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000639 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
640 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000641 while (CurrentToken != NULL) {
642 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000643 next();
644 return true;
645 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000646 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000648 if (!consumeToken())
649 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000650 }
651 return false;
652 }
653
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000655 if (!CurrentToken)
656 return false;
657
658 // A '[' could be an index subscript (after an indentifier or after
659 // ')' or ']'), or it could be the start of an Objective-C method
660 // expression.
661 AnnotatedToken *LSquare = CurrentToken->Parent;
662 bool StartsObjCMethodExpr =
663 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
664 LSquare->Parent->is(tok::l_square) ||
665 LSquare->Parent->is(tok::l_paren) ||
666 LSquare->Parent->is(tok::kw_return) ||
667 LSquare->Parent->is(tok::kw_throw) ||
668 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
669 true, true) > prec::Unknown;
670
671 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
672 if (StartsObjCMethodExpr) {
673 ColonIsObjCMethodExpr = true;
674 LSquare->Type = TT_ObjCMethodExpr;
675 }
676
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000677 while (CurrentToken != NULL) {
678 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000679 if (StartsObjCMethodExpr) {
680 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
681 CurrentToken->Type = TT_ObjCMethodExpr;
682 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000683 next();
684 return true;
685 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000686 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000687 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000688 if (!consumeToken())
689 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000690 }
691 return false;
692 }
693
Daniel Jasper83a54d22013-01-10 09:26:47 +0000694 bool parseBrace() {
695 while (CurrentToken != NULL) {
696 if (CurrentToken->is(tok::r_brace)) {
697 next();
698 return true;
699 }
700 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
701 return false;
702 if (!consumeToken())
703 return false;
704 }
705 // Lines can currently end with '{'.
706 return true;
707 }
708
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000709 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000710 while (CurrentToken != NULL) {
711 if (CurrentToken->is(tok::colon)) {
712 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000713 next();
714 return true;
715 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000716 if (!consumeToken())
717 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000718 }
719 return false;
720 }
721
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000722 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000723 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
724 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000725 next();
726 if (!parseAngle())
727 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000728 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000729 parseLine();
730 return true;
731 }
732 return false;
733 }
734
Daniel Jasperc0880a92013-01-04 18:52:56 +0000735 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000736 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000738 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000739 case tok::plus:
740 case tok::minus:
741 // At the start of the line, +/- specific ObjectiveC method
742 // declarations.
743 if (Tok->Parent == NULL)
744 Tok->Type = TT_ObjCMethodSpecifier;
745 break;
Nico Webera7252d82013-01-12 06:18:40 +0000746 case tok::colon:
747 // Colons from ?: are handled in parseConditional().
748 if (ColonIsObjCMethodExpr)
749 Tok->Type = TT_ObjCMethodExpr;
750 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000751 case tok::l_paren: {
752 bool ParensWereObjCReturnType =
753 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000754 if (!parseParens())
755 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000756 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
757 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000758 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000759 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
760 CurrentToken->Type = TT_ObjCSelectorStart;
761 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000762 }
Nico Weber9efe2912013-01-10 23:11:41 +0000763 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000764 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000765 if (!parseSquare())
766 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000767 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000768 case tok::l_brace:
769 if (!parseBrace())
770 return false;
771 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000772 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000773 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000774 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 Tok->Type = TT_BinaryOperator;
777 CurrentToken = Tok;
778 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000779 }
780 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000781 case tok::r_paren:
782 case tok::r_square:
783 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000784 case tok::r_brace:
785 // Lines can start with '}'.
786 if (Tok->Parent != NULL)
787 return false;
788 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000789 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000790 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000791 break;
792 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000793 if (CurrentToken->is(tok::l_paren)) {
794 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000795 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000796 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
797 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000798 next();
799 }
800 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000801 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
802 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000803 next();
804 }
805 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000806 break;
807 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000808 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000809 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000810 case tok::kw_template:
811 parseTemplateDeclaration();
812 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 default:
814 break;
815 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000816 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000817 }
818
Daniel Jasper050948a52012-12-21 17:58:39 +0000819 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000820 while (CurrentToken != NULL) {
821 if (CurrentToken->is(tok::slash))
822 CurrentToken->Type = TT_DirectorySeparator;
823 else if (CurrentToken->is(tok::less))
824 CurrentToken->Type = TT_TemplateOpener;
825 else if (CurrentToken->is(tok::greater))
826 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000827 next();
828 }
829 }
830
831 void parsePreprocessorDirective() {
832 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000833 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000834 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000835 // Hashes in the middle of a line can lead to any strange token
836 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000837 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000838 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 switch (
840 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000841 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000842 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000843 parseIncludeDirective();
844 break;
845 default:
846 break;
847 }
848 }
849
Daniel Jasperda16db32013-01-07 10:48:50 +0000850 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000851 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000852 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000853 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000854 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000855 while (CurrentToken != NULL) {
856 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000857 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000858 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000859 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000861 if (KeywordVirtualFound)
862 return LT_VirtualFunctionDecl;
863 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000864 }
865
866 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000867 if (CurrentToken != NULL && !CurrentToken->Children.empty())
868 CurrentToken = &CurrentToken->Children[0];
869 else
870 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000871 }
872
873 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000875 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000876 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000877 };
878
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000879 void createAnnotatedTokens(AnnotatedToken &Current) {
880 if (!Current.FormatTok.Children.empty()) {
881 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
882 Current.Children.back().Parent = &Current;
883 createAnnotatedTokens(Current.Children.back());
884 }
885 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000886
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000887 void calculateExtraInformation(AnnotatedToken &Current) {
888 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
889
Manuel Klimek52b15152013-01-09 15:25:02 +0000890 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000891 Current.MustBreakBefore = true;
892 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000893 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
894 TT_LineComment || (Current.is(tok::string_literal) &&
895 Current.Parent->is(tok::string_literal))) {
896 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000897 } else {
898 Current.MustBreakBefore = false;
899 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902 if (!Current.Children.empty())
903 calculateExtraInformation(Current.Children[0]);
904 }
905
906 bool annotate() {
907 createAnnotatedTokens(RootToken);
908
909 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000910 CurrentLineType = Parser.parseLine();
911 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000912 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000913
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000914 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000915
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000916 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000917 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000918 else if (RootToken.Type == TT_ObjCDecl)
919 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000920 else if (RootToken.Type == TT_ObjCProperty)
921 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000922
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000923 if (!RootToken.Children.empty())
924 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000925 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000926 }
927
Daniel Jasperda16db32013-01-07 10:48:50 +0000928 LineType getLineType() {
929 return CurrentLineType;
930 }
931
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 const AnnotatedToken &getRootToken() {
933 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000934 }
935
936private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000937 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
938 if (getPrecedence(Current) == prec::Assignment ||
939 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
940 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000941
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000942 if (Current.Type == TT_Unknown) {
943 if (Current.is(tok::star) || Current.is(tok::amp)) {
944 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000945 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
946 Current.is(tok::caret)) {
947 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
949 Current.Type = determineIncrementUsage(Current);
950 } else if (Current.is(tok::exclaim)) {
951 Current.Type = TT_UnaryOperator;
952 } else if (isBinaryOperator(Current)) {
953 Current.Type = TT_BinaryOperator;
954 } else if (Current.is(tok::comment)) {
955 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
956 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000957 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000958 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000959 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000960 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000961 } else if (Current.is(tok::r_paren) &&
962 (Current.Parent->Type == TT_PointerOrReference ||
963 Current.Parent->Type == TT_TemplateCloser)) {
964 // FIXME: We need to get smarter and understand more cases of casts.
965 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000966 } else if (Current.is(tok::at) && Current.Children.size()) {
967 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
968 case tok::objc_interface:
969 case tok::objc_implementation:
970 case tok::objc_protocol:
971 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000972 break;
973 case tok::objc_property:
974 Current.Type = TT_ObjCProperty;
975 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000976 default:
977 break;
978 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000979 }
980 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000981
982 if (!Current.Children.empty())
983 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 }
985
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000986 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000987 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000988 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000989 }
990
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000991 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
992 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000993 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000994 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000995 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000996 const FormatToken &PrevToken = Tok.Parent->FormatTok;
997 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000998
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000999 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
1000 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +00001001 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
1002 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001003 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001004
Nico Weber5dafd4a2013-01-12 05:47:16 +00001005 if (PrevToken.Tok.isLiteral() || PrevToken.Tok.is(tok::r_paren) ||
1006 PrevToken.Tok.is(tok::r_square) || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001007 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
1008 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
1009 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
Nico Webereee7b812013-01-12 05:50:48 +00001010 NextToken.Tok.is(tok::l_paren) || NextToken.Tok.is(tok::l_square) ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001011 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001012 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001013
Daniel Jasper542de162013-01-02 15:46:59 +00001014 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
1015 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001016 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001017
Daniel Jasper426702d2012-12-05 07:51:39 +00001018 // It is very unlikely that we are going to find a pointer or reference type
1019 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001020 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001021 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001022
Daniel Jasperda16db32013-01-07 10:48:50 +00001023 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001024 }
1025
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001026 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001027 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001028 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
1029 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
1030 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +00001031 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
Nico Weber63a54eb2013-01-12 05:41:23 +00001032 Tok.Parent->is(tok::at) || Tok.Parent->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001033 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001034
1035 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001037 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001038
1039 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001040 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001041 }
1042
1043 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001044 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1045 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001046 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001047
Daniel Jasperda16db32013-01-07 10:48:50 +00001048 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 }
1050
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001051 bool spaceRequiredBetween(const AnnotatedToken &Left,
1052 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001053 if (Right.is(tok::hashhash))
1054 return Left.is(tok::hash);
1055 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1056 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001057 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1058 return false;
Nico Webera6087752013-01-10 20:12:55 +00001059 if (Right.is(tok::less) &&
1060 (Left.is(tok::kw_template) ||
1061 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 return true;
1063 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1064 return false;
1065 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1066 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001067 if (Left.is(tok::at) &&
1068 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1069 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001070 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1071 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001072 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001073 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1074 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001075 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001076 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001077 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1078 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001080 return Right.FormatTok.Tok.isLiteral() ||
1081 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001082 if (Right.is(tok::star) && Left.is(tok::l_paren))
1083 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001084 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1085 return false;
1086 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001087 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001088 if (Left.is(tok::coloncolon) ||
1089 (Right.is(tok::coloncolon) &&
1090 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001091 return false;
1092 if (Left.is(tok::period) || Right.is(tok::period))
1093 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001094 if (Left.is(tok::colon))
1095 return Left.Type != TT_ObjCMethodExpr;
1096 if (Right.is(tok::colon))
1097 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001098 if (Left.is(tok::l_paren))
1099 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001101 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1102 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001103 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001104 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1105 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001106 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001107 if (Left.is(tok::at) &&
1108 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001109 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001110 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1111 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 return true;
1113 }
1114
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001115 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001116 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1118 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001119 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001120 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001121 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001123 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1124 if (Tok.Type == TT_ObjCSelectorStart)
1125 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001127 // Don't space between ')' and <id>
1128 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001129 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001130 // Don't space between ':' and '('
1131 return false;
1132 }
Nico Webera2a84952013-01-10 21:30:42 +00001133 if (CurrentLineType == LT_ObjCProperty &&
1134 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1135 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001136
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001137 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001138 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001139 if (Tok.Type == TT_OverloadedOperator)
1140 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001141 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001143 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001144 if (Tok.is(tok::colon))
Nico Webera7252d82013-01-12 06:18:40 +00001145 return RootToken.isNot(tok::kw_case) && !Tok.Children.empty() &&
1146 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001147 if (Tok.Parent->Type == TT_UnaryOperator ||
1148 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001149 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001150 if (Tok.Type == TT_UnaryOperator)
1151 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001152 Tok.Parent->isNot(tok::l_square) &&
1153 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001154 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1155 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001156 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1157 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001158 if (Tok.Type == TT_DirectorySeparator ||
1159 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001160 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001161 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001162 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001163 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001164 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001165 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001166 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001167 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001168 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001169 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001170 }
1171
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001172 bool canBreakBefore(const AnnotatedToken &Right) {
1173 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001174 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001175 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1176 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001177 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001178 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1179 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001180 // Don't break this identifier as ':' or identifier
1181 // before it will break.
1182 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001183 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1184 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001185 // Don't break at ':' if identifier before it can beak.
1186 return false;
1187 }
Nico Webera7252d82013-01-12 06:18:40 +00001188 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1189 return false;
1190 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1191 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001192 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001193 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001194 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001195 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001196 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001197 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001198 return false;
1199
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001200 if (Right.is(tok::comment))
1201 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001202 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001203 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001204 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001205 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1206 Left.is(tok::comma) || Right.is(tok::lessless) ||
1207 Right.is(tok::arrow) || Right.is(tok::period) ||
1208 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001209 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001210 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001211 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1212 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001213 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001214 }
1215
Daniel Jasperf7935112012-12-03 18:12:45 +00001216 FormatStyle Style;
1217 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001218 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001219 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001220 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001221};
1222
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001223class LexerBasedFormatTokenSource : public FormatTokenSource {
1224public:
1225 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001226 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001227 IdentTable(Lex.getLangOpts()) {
1228 Lex.SetKeepWhitespaceMode(true);
1229 }
1230
1231 virtual FormatToken getNextToken() {
1232 if (GreaterStashed) {
1233 FormatTok.NewlinesBefore = 0;
1234 FormatTok.WhiteSpaceStart =
1235 FormatTok.Tok.getLocation().getLocWithOffset(1);
1236 FormatTok.WhiteSpaceLength = 0;
1237 GreaterStashed = false;
1238 return FormatTok;
1239 }
1240
1241 FormatTok = FormatToken();
1242 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001243 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001244 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001245 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1246 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001247
1248 // Consume and record whitespace until we find a significant token.
1249 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001250 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001251 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1252 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001253 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1254
1255 if (FormatTok.Tok.is(tok::eof))
1256 return FormatTok;
1257 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001258 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001259 }
Manuel Klimekef920692013-01-07 07:56:50 +00001260
1261 // Now FormatTok is the next non-whitespace token.
1262 FormatTok.TokenLength = Text.size();
1263
Manuel Klimek1abf7892013-01-04 23:34:14 +00001264 // In case the token starts with escaped newlines, we want to
1265 // take them into account as whitespace - this pattern is quite frequent
1266 // in macro definitions.
1267 // FIXME: What do we want to do with other escaped spaces, and escaped
1268 // spaces or newlines in the middle of tokens?
1269 // FIXME: Add a more explicit test.
1270 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001271 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001272 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001273 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001274 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275 }
1276
1277 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001278 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001279 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001280 FormatTok.Tok.setKind(Info.getTokenID());
1281 }
1282
1283 if (FormatTok.Tok.is(tok::greatergreater)) {
1284 FormatTok.Tok.setKind(tok::greater);
1285 GreaterStashed = true;
1286 }
1287
1288 return FormatTok;
1289 }
1290
1291private:
1292 FormatToken FormatTok;
1293 bool GreaterStashed;
1294 Lexer &Lex;
1295 SourceManager &SourceMgr;
1296 IdentifierTable IdentTable;
1297
1298 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001299 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001300 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1301 Tok.getLength());
1302 }
1303};
1304
Daniel Jasperf7935112012-12-03 18:12:45 +00001305class Formatter : public UnwrappedLineConsumer {
1306public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001307 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1308 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001309 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001310 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001311 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001312
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001313 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001314
Daniel Jasperf7935112012-12-03 18:12:45 +00001315 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001316 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001317 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001318 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001319 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001320 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1321 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001322 I != E; ++I) {
1323 const UnwrappedLine &TheLine = *I;
1324 if (touchesRanges(TheLine)) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001325 llvm::OwningPtr<TokenAnnotator> AnnotatedLine(
1326 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1327 if (!AnnotatedLine->annotate())
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001328 break;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001329 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001330 TheLine.Level, TheLine.InPPDirective,
1331 PreviousEndOfLineColumn);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001332
1333 UnwrappedLine Line(TheLine);
1334 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1335 I, E);
1336 UnwrappedLineFormatter Formatter(
1337 Style, SourceMgr, Line, Indent, FitsOnALine,
1338 AnnotatedLine->getLineType(), AnnotatedLine->getRootToken(),
1339 Replaces, StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001340 PreviousEndOfLineColumn = Formatter.format();
1341 } else {
1342 // If we did not reformat this unwrapped line, the column at the end of
1343 // the last token is unchanged - thus, we can calculate the end of the
1344 // last token, and return the result.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001345 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001346 PreviousEndOfLineColumn =
1347 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1348 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1349 Lex.getLangOpts()) -
1350 1;
1351 }
1352 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001353 return Replaces;
1354 }
1355
1356private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001357 /// \brief Tries to merge lines into one.
1358 ///
1359 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1360 /// if possible; note that \c I will be incremented when lines are merged.
1361 ///
1362 /// Returns whether the resulting \c Line can fit in a single line.
1363 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
1364 llvm::OwningPtr<TokenAnnotator> &AnnotatedLine,
1365 std::vector<UnwrappedLine>::iterator &I,
1366 std::vector<UnwrappedLine>::iterator E) {
1367 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1368
1369 // Check whether the UnwrappedLine can be put onto a single line. If
1370 // so, this is bound to be the optimal solution (by definition) and we
1371 // don't need to analyze the entire solution space.
1372 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1373 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1374 return FitsOnALine;
1375
1376 // Try to merge the next two lines if possible.
1377 UnwrappedLine Combined(Line);
1378
1379 // First, check that the current line allows merging. This is the case if
1380 // we're not in a control flow statement and the last token is an opening
1381 // brace.
1382 FormatToken *Last = &Combined.RootToken;
1383 bool AllowedTokens =
Manuel Klimek2acb7b72013-01-11 19:17:44 +00001384 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1385 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1386 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1387 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001388 // This gets rid of all ObjC @ keywords and methods.
1389 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus) &&
1390 Last->Tok.isNot(tok::plus);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001391 while (!Last->Children.empty())
1392 Last = &Last->Children.back();
1393 if (!Last->Tok.is(tok::l_brace))
1394 return FitsOnALine;
1395
1396 // Second, check that the next line does not contain any braces - if it
1397 // does, readability declines when putting it into a single line.
1398 const FormatToken *Next = &(I + 1)->RootToken;
1399 while (Next) {
1400 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1401 !Next->Tok.is(tok::r_brace);
1402 Last->Children.push_back(*Next);
1403 Last = &Last->Children[0];
1404 Last->Children.clear();
1405 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1406 }
1407
1408 // Last, check that the third line contains a single closing brace.
1409 Next = &(I + 2)->RootToken;
1410 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1411 if (!Next->Children.empty() || !AllowedTokens)
1412 return FitsOnALine;
1413 Last->Children.push_back(*Next);
1414
1415 llvm::OwningPtr<TokenAnnotator> CombinedAnnotator(
1416 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1417 if (CombinedAnnotator->annotate() &&
1418 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1419 // If the merged line fits, we use that instead and skip the next two
1420 // lines.
1421 AnnotatedLine.reset(CombinedAnnotator.take());
1422 Line = Combined;
1423 I += 2;
1424 }
1425 return FitsOnALine;
1426 }
1427
1428 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001429 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001430 while (!Last->Children.empty())
1431 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001432 return Last;
1433 }
1434
1435 bool touchesRanges(const UnwrappedLine &TheLine) {
1436 const FormatToken *First = &TheLine.RootToken;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001437 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001438 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001439 First->Tok.getLocation(),
1440 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001441 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001442 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1443 Ranges[i].getBegin()) &&
1444 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1445 LineRange.getBegin()))
1446 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001447 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001448 return false;
1449 }
1450
1451 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1452 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001453 }
1454
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001455 /// \brief Add a new line and the required indent before the first Token
1456 /// of the \c UnwrappedLine if there was no structural parsing error.
1457 /// Returns the indent level of the \c UnwrappedLine.
1458 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1459 bool InPPDirective,
1460 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001461 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001462 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1463 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1464
1465 unsigned Newlines = std::min(Tok.NewlinesBefore,
1466 Style.MaxEmptyLinesToKeep + 1);
1467 if (Newlines == 0 && !Tok.IsFirst)
1468 Newlines = 1;
1469 unsigned Indent = Level * 2;
1470
1471 bool IsAccessModifier = false;
1472 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1473 RootToken.is(tok::kw_private))
1474 IsAccessModifier = true;
1475 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1476 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1477 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1478 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1479 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1480 IsAccessModifier = true;
1481
1482 if (IsAccessModifier &&
1483 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1484 Indent += Style.AccessModifierOffset;
1485 if (!InPPDirective || Tok.HasUnescapedNewline) {
1486 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1487 } else {
1488 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1489 SourceMgr, Replaces);
1490 }
1491 return Indent;
1492 }
1493
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001494 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001495 FormatStyle Style;
1496 Lexer &Lex;
1497 SourceManager &SourceMgr;
1498 tooling::Replacements Replaces;
1499 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001500 std::vector<UnwrappedLine> UnwrappedLines;
1501 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001502};
1503
1504tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1505 SourceManager &SourceMgr,
1506 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001507 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1508 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1509 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1510 DiagnosticsEngine Diagnostics(
1511 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1512 &DiagnosticPrinter, false);
1513 Diagnostics.setSourceManager(&SourceMgr);
1514 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001515 return formatter.format();
1516}
1517
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001518LangOptions getFormattingLangOpts() {
1519 LangOptions LangOpts;
1520 LangOpts.CPlusPlus = 1;
1521 LangOpts.CPlusPlus11 = 1;
1522 LangOpts.Bool = 1;
1523 LangOpts.ObjC1 = 1;
1524 LangOpts.ObjC2 = 1;
1525 return LangOpts;
1526}
1527
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001528} // namespace format
1529} // namespace clang