blob: 0c486e0be3dd77a19a3e68a9cff6142cc37eb44a [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;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000389 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000390 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000391 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000393 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
394 State.ForLoopVariablePos = State.Column -
395 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000396
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000397 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
398 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000399 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000400
Daniel Jasperf7935112012-12-03 18:12:45 +0000401 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000402 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000403
Daniel Jasperbcab4302013-01-09 10:40:23 +0000404 // FIXME: Do we need to do this for assignments nested in other
405 // expressions?
406 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000407 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000408 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000409 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000410 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000411 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000412 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000413
Daniel Jasper206df732013-01-07 13:08:40 +0000414 // Top-level spaces that are not part of assignments are exempt as that
415 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000416 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000417 if (Spaces > 0 &&
418 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000419 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000420 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000421 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000422 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000423 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000424 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000425 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000426
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000427 /// \brief Mark the next token as consumed in \p State and modify its stacks
428 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000429 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000430 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000432
Daniel Jasper337816e2013-01-11 10:22:12 +0000433 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
434 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000435
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000436 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000437 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000438 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
439 Current.is(tok::l_brace) ||
440 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000441 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000442 if (Current.is(tok::l_brace)) {
443 // FIXME: This does not work with nested static initializers.
444 // Implement a better handling for static initializers and similar
445 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000447 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000448 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000449 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000450 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000451 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000452 }
453
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000454 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000455 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000456 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
457 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
458 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000459 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000460 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000461
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000462 if (State.NextToken->Children.empty())
463 State.NextToken = NULL;
464 else
465 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000466
467 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000468 }
469
Nico Weber49cbc2c2013-01-07 15:15:29 +0000470 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000471 unsigned splitPenalty(const AnnotatedToken &Tok) {
472 const AnnotatedToken &Left = Tok;
473 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000474
475 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000476 if (RootToken.is(tok::kw_for) &&
477 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000478 return 20;
479
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000480 if (Left.is(tok::semi) || Left.is(tok::comma) ||
481 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000483 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000484 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000485
Daniel Jasper399d24b2013-01-09 07:06:56 +0000486 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
487 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000488 prec::Level Level = getPrecedence(Left);
489
490 // Breaking after an assignment leads to a bad result as the two sides of
491 // the assignment are visually very close together.
492 if (Level == prec::Assignment)
493 return 50;
494
Daniel Jasperde5c2072012-12-24 00:13:23 +0000495 if (Level != prec::Unknown)
496 return Level;
497
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000498 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000499 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000500
Daniel Jasperf7935112012-12-03 18:12:45 +0000501 return 3;
502 }
503
Daniel Jasper2df93312013-01-09 10:16:05 +0000504 unsigned getColumnLimit() {
505 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
506 }
507
Daniel Jasperf7935112012-12-03 18:12:45 +0000508 /// \brief Calculate the number of lines needed to format the remaining part
509 /// of the unwrapped line.
510 ///
511 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000512 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 /// added after the previous token.
514 ///
515 /// \param StopAt is used for optimization. If we can determine that we'll
516 /// definitely need at least \p StopAt additional lines, we already know of a
517 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000518 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000519 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000520 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 return 0;
522
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000523 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000524 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000525 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000526 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000527 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000529 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000530 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000531 State.LineContainsContinuedForLoopSection)
532 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000533 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
534 State.NextToken->Type != TT_LineComment &&
535 State.Stack.back().BreakAfterComma)
536 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000537
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000538 unsigned CurrentPenalty = 0;
539 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000541 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000542 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000544 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000546 }
547
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000548 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000549
Daniel Jasper2df93312013-01-09 10:16:05 +0000550 // Exceeding column limit is bad, assign penalty.
551 if (State.Column > getColumnLimit()) {
552 unsigned ExcessCharacters = State.Column - getColumnLimit();
553 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
554 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000555
Daniel Jasperf7935112012-12-03 18:12:45 +0000556 if (StopAt <= CurrentPenalty)
557 return UINT_MAX;
558 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000560 if (I != Memory.end()) {
561 // If this state has already been examined, we can safely return the
562 // previous result if we
563 // - have not hit the optimatization (and thus returned UINT_MAX) OR
564 // - are now computing for a smaller or equal StopAt.
565 unsigned SavedResult = I->second.first;
566 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000567 if (SavedResult != UINT_MAX)
568 return SavedResult + CurrentPenalty;
569 else if (StopAt <= SavedStopAt)
570 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000571 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000572
573 unsigned NoBreak = calcPenalty(State, false, StopAt);
574 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
575 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000576
577 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
578 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000579 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000580
581 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 }
583
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 FormatStyle Style;
585 SourceManager &SourceMgr;
586 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000587 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000588 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000589 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000592
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000593 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000595 StateMap Memory;
596
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 OptimizationParameters Parameters;
598};
599
600/// \brief Determines extra information about the tokens comprising an
601/// \c UnwrappedLine.
602class TokenAnnotator {
603public:
604 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000605 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000606 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000607 RootToken(Line.RootToken) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000608
609 /// \brief A parser that gathers additional information about tokens.
610 ///
611 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
612 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
613 /// into template parameter lists.
614 class AnnotatingParser {
615 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000616 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000617 : CurrentToken(&RootToken), KeywordVirtualFound(false),
618 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000619
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000620 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000621 while (CurrentToken != NULL) {
622 if (CurrentToken->is(tok::greater)) {
623 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000624 next();
625 return true;
626 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000627 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
628 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000630 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
631 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000632 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000633 if (!consumeToken())
634 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000635 }
636 return false;
637 }
638
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000639 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000640 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
641 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000642 while (CurrentToken != NULL) {
643 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000644 next();
645 return true;
646 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000647 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000648 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000649 if (!consumeToken())
650 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000651 }
652 return false;
653 }
654
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000655 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000656 if (!CurrentToken)
657 return false;
658
659 // A '[' could be an index subscript (after an indentifier or after
660 // ')' or ']'), or it could be the start of an Objective-C method
661 // expression.
662 AnnotatedToken *LSquare = CurrentToken->Parent;
663 bool StartsObjCMethodExpr =
664 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
665 LSquare->Parent->is(tok::l_square) ||
666 LSquare->Parent->is(tok::l_paren) ||
667 LSquare->Parent->is(tok::kw_return) ||
668 LSquare->Parent->is(tok::kw_throw) ||
669 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
670 true, true) > prec::Unknown;
671
672 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
673 if (StartsObjCMethodExpr) {
674 ColonIsObjCMethodExpr = true;
675 LSquare->Type = TT_ObjCMethodExpr;
676 }
677
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000678 while (CurrentToken != NULL) {
679 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000680 if (StartsObjCMethodExpr) {
681 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
682 CurrentToken->Type = TT_ObjCMethodExpr;
683 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 next();
685 return true;
686 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000687 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000688 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000689 if (!consumeToken())
690 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000691 }
692 return false;
693 }
694
Daniel Jasper83a54d22013-01-10 09:26:47 +0000695 bool parseBrace() {
696 while (CurrentToken != NULL) {
697 if (CurrentToken->is(tok::r_brace)) {
698 next();
699 return true;
700 }
701 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
702 return false;
703 if (!consumeToken())
704 return false;
705 }
706 // Lines can currently end with '{'.
707 return true;
708 }
709
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000710 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000711 while (CurrentToken != NULL) {
712 if (CurrentToken->is(tok::colon)) {
713 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 next();
715 return true;
716 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000717 if (!consumeToken())
718 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000719 }
720 return false;
721 }
722
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000723 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000724 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
725 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000726 next();
727 if (!parseAngle())
728 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000729 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000730 parseLine();
731 return true;
732 }
733 return false;
734 }
735
Daniel Jasperc0880a92013-01-04 18:52:56 +0000736 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000737 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000739 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000740 case tok::plus:
741 case tok::minus:
742 // At the start of the line, +/- specific ObjectiveC method
743 // declarations.
744 if (Tok->Parent == NULL)
745 Tok->Type = TT_ObjCMethodSpecifier;
746 break;
Nico Webera7252d82013-01-12 06:18:40 +0000747 case tok::colon:
748 // Colons from ?: are handled in parseConditional().
749 if (ColonIsObjCMethodExpr)
750 Tok->Type = TT_ObjCMethodExpr;
751 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000752 case tok::l_paren: {
753 bool ParensWereObjCReturnType =
754 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000755 if (!parseParens())
756 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000757 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
758 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000759 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000760 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
761 CurrentToken->Type = TT_ObjCSelectorStart;
762 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000763 }
Nico Weber9efe2912013-01-10 23:11:41 +0000764 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000766 if (!parseSquare())
767 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000769 case tok::l_brace:
770 if (!parseBrace())
771 return false;
772 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000773 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000774 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000775 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000776 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000777 Tok->Type = TT_BinaryOperator;
778 CurrentToken = Tok;
779 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 }
781 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000782 case tok::r_paren:
783 case tok::r_square:
784 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000785 case tok::r_brace:
786 // Lines can start with '}'.
787 if (Tok->Parent != NULL)
788 return false;
789 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000790 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000791 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000792 break;
793 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000794 if (CurrentToken->is(tok::l_paren)) {
795 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000796 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000797 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
798 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000799 next();
800 }
801 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000802 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
803 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000804 next();
805 }
806 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000807 break;
808 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000809 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000811 case tok::kw_template:
812 parseTemplateDeclaration();
813 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000814 default:
815 break;
816 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000817 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 }
819
Daniel Jasper050948a52012-12-21 17:58:39 +0000820 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000821 while (CurrentToken != NULL) {
822 if (CurrentToken->is(tok::slash))
823 CurrentToken->Type = TT_DirectorySeparator;
824 else if (CurrentToken->is(tok::less))
825 CurrentToken->Type = TT_TemplateOpener;
826 else if (CurrentToken->is(tok::greater))
827 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000828 next();
829 }
830 }
831
832 void parsePreprocessorDirective() {
833 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000834 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000835 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000836 // Hashes in the middle of a line can lead to any strange token
837 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000838 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000839 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000840 switch (
841 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000842 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000843 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000844 parseIncludeDirective();
845 break;
846 default:
847 break;
848 }
849 }
850
Daniel Jasperda16db32013-01-07 10:48:50 +0000851 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000852 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000853 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000854 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000855 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000856 while (CurrentToken != NULL) {
857 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000858 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000859 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000860 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000861 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000862 if (KeywordVirtualFound)
863 return LT_VirtualFunctionDecl;
864 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000865 }
866
867 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 if (CurrentToken != NULL && !CurrentToken->Children.empty())
869 CurrentToken = &CurrentToken->Children[0];
870 else
871 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000872 }
873
874 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000875 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000876 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000877 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000878 };
879
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000880 void createAnnotatedTokens(AnnotatedToken &Current) {
881 if (!Current.FormatTok.Children.empty()) {
882 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
883 Current.Children.back().Parent = &Current;
884 createAnnotatedTokens(Current.Children.back());
885 }
886 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000887
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000888 void calculateExtraInformation(AnnotatedToken &Current) {
889 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
890
Manuel Klimek52b15152013-01-09 15:25:02 +0000891 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000892 Current.MustBreakBefore = true;
893 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000894 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
895 TT_LineComment || (Current.is(tok::string_literal) &&
896 Current.Parent->is(tok::string_literal))) {
897 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000898 } else {
899 Current.MustBreakBefore = false;
900 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000901 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 if (!Current.Children.empty())
904 calculateExtraInformation(Current.Children[0]);
905 }
906
907 bool annotate() {
908 createAnnotatedTokens(RootToken);
909
910 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000911 CurrentLineType = Parser.parseLine();
912 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000913 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000914
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000916
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000918 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000919 else if (RootToken.Type == TT_ObjCDecl)
920 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000921 else if (RootToken.Type == TT_ObjCProperty)
922 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000923
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000924 if (!RootToken.Children.empty())
925 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000926 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000927 }
928
Daniel Jasperda16db32013-01-07 10:48:50 +0000929 LineType getLineType() {
930 return CurrentLineType;
931 }
932
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000933 const AnnotatedToken &getRootToken() {
934 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000935 }
936
937private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000938 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
939 if (getPrecedence(Current) == prec::Assignment ||
940 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
941 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000942
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000943 if (Current.Type == TT_Unknown) {
944 if (Current.is(tok::star) || Current.is(tok::amp)) {
945 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000946 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
947 Current.is(tok::caret)) {
948 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000949 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
950 Current.Type = determineIncrementUsage(Current);
951 } else if (Current.is(tok::exclaim)) {
952 Current.Type = TT_UnaryOperator;
953 } else if (isBinaryOperator(Current)) {
954 Current.Type = TT_BinaryOperator;
955 } else if (Current.is(tok::comment)) {
956 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
957 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000958 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000959 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000960 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000962 } else if (Current.is(tok::r_paren) &&
963 (Current.Parent->Type == TT_PointerOrReference ||
964 Current.Parent->Type == TT_TemplateCloser)) {
965 // FIXME: We need to get smarter and understand more cases of casts.
966 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000967 } else if (Current.is(tok::at) && Current.Children.size()) {
968 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
969 case tok::objc_interface:
970 case tok::objc_implementation:
971 case tok::objc_protocol:
972 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000973 break;
974 case tok::objc_property:
975 Current.Type = TT_ObjCProperty;
976 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000977 default:
978 break;
979 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000980 }
981 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000982
983 if (!Current.Children.empty())
984 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000985 }
986
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000987 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000988 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000989 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000990 }
991
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000992 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
993 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000994 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000995 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000996 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000997 const FormatToken &PrevToken = Tok.Parent->FormatTok;
998 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000999
Daniel Jasper3c2557d2013-01-04 20:46:38 +00001000 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
1001 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +00001002 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
1003 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001004 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001005
Nico Weber5dafd4a2013-01-12 05:47:16 +00001006 if (PrevToken.Tok.isLiteral() || PrevToken.Tok.is(tok::r_paren) ||
1007 PrevToken.Tok.is(tok::r_square) || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001008 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
1009 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
1010 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
Nico Webereee7b812013-01-12 05:50:48 +00001011 NextToken.Tok.is(tok::l_paren) || NextToken.Tok.is(tok::l_square) ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001012 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001013 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001014
Daniel Jasper542de162013-01-02 15:46:59 +00001015 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
1016 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001017 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001018
Daniel Jasper426702d2012-12-05 07:51:39 +00001019 // It is very unlikely that we are going to find a pointer or reference type
1020 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001021 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001022 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001023
Daniel Jasperda16db32013-01-07 10:48:50 +00001024 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001025 }
1026
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001027 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001028 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001029 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
1030 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
1031 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +00001032 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
Nico Weber63a54eb2013-01-12 05:41:23 +00001033 Tok.Parent->is(tok::at) || Tok.Parent->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001034 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001035
1036 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001037 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001038 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001039
1040 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001041 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001042 }
1043
1044 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001045 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1046 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001047 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001048
Daniel Jasperda16db32013-01-07 10:48:50 +00001049 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001050 }
1051
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001052 bool spaceRequiredBetween(const AnnotatedToken &Left,
1053 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001054 if (Right.is(tok::hashhash))
1055 return Left.is(tok::hash);
1056 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1057 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001058 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1059 return false;
Nico Webera6087752013-01-10 20:12:55 +00001060 if (Right.is(tok::less) &&
1061 (Left.is(tok::kw_template) ||
1062 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001063 return true;
1064 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1065 return false;
1066 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1067 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001068 if (Left.is(tok::at) &&
1069 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1070 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001071 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1072 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001073 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001074 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1075 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001076 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001078 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1079 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001080 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001081 return Right.FormatTok.Tok.isLiteral() ||
1082 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 if (Right.is(tok::star) && Left.is(tok::l_paren))
1084 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001085 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1086 return false;
1087 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001088 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001089 if (Left.is(tok::coloncolon) ||
1090 (Right.is(tok::coloncolon) &&
1091 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001092 return false;
1093 if (Left.is(tok::period) || Right.is(tok::period))
1094 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001095 if (Left.is(tok::colon))
1096 return Left.Type != TT_ObjCMethodExpr;
1097 if (Right.is(tok::colon))
1098 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001099 if (Left.is(tok::l_paren))
1100 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001101 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001102 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1103 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001104 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001105 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1106 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001107 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001108 if (Left.is(tok::at) &&
1109 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001110 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001111 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1112 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001113 return true;
1114 }
1115
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001116 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001117 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001118 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1119 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001120 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001122 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001123 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001124 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1125 if (Tok.Type == TT_ObjCSelectorStart)
1126 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001127 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001128 // Don't space between ')' and <id>
1129 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001130 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001131 // Don't space between ':' and '('
1132 return false;
1133 }
Nico Webera2a84952013-01-10 21:30:42 +00001134 if (CurrentLineType == LT_ObjCProperty &&
1135 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1136 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001137
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001138 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001139 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001140 if (Tok.Type == TT_OverloadedOperator)
1141 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001142 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001143 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001144 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001145 if (Tok.is(tok::colon))
Nico Webera7252d82013-01-12 06:18:40 +00001146 return RootToken.isNot(tok::kw_case) && !Tok.Children.empty() &&
1147 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001148 if (Tok.Parent->Type == TT_UnaryOperator ||
1149 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001150 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 if (Tok.Type == TT_UnaryOperator)
1152 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001153 Tok.Parent->isNot(tok::l_square) &&
1154 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001155 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1156 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001157 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1158 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001159 if (Tok.Type == TT_DirectorySeparator ||
1160 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001161 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001162 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001163 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001164 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001165 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001166 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001167 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001168 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001169 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001170 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001171 }
1172
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001173 bool canBreakBefore(const AnnotatedToken &Right) {
1174 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001175 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001176 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1177 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001178 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001179 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1180 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001181 // Don't break this identifier as ':' or identifier
1182 // before it will break.
1183 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001184 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1185 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001186 // Don't break at ':' if identifier before it can beak.
1187 return false;
1188 }
Nico Webera7252d82013-01-12 06:18:40 +00001189 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1190 return false;
1191 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1192 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001193 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001194 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001195 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001196 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001197 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001198 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001199 return false;
1200
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001201 if (Right.is(tok::comment))
1202 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001203 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001204 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001205 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001206 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1207 Left.is(tok::comma) || Right.is(tok::lessless) ||
1208 Right.is(tok::arrow) || Right.is(tok::period) ||
1209 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001210 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001211 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001212 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1213 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001214 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001215 }
1216
Daniel Jasperf7935112012-12-03 18:12:45 +00001217 FormatStyle Style;
1218 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001219 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001220 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001222};
1223
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001224class LexerBasedFormatTokenSource : public FormatTokenSource {
1225public:
1226 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001227 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228 IdentTable(Lex.getLangOpts()) {
1229 Lex.SetKeepWhitespaceMode(true);
1230 }
1231
1232 virtual FormatToken getNextToken() {
1233 if (GreaterStashed) {
1234 FormatTok.NewlinesBefore = 0;
1235 FormatTok.WhiteSpaceStart =
1236 FormatTok.Tok.getLocation().getLocWithOffset(1);
1237 FormatTok.WhiteSpaceLength = 0;
1238 GreaterStashed = false;
1239 return FormatTok;
1240 }
1241
1242 FormatTok = FormatToken();
1243 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001244 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001245 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001246 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1247 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001248
1249 // Consume and record whitespace until we find a significant token.
1250 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001251 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001252 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1253 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001254 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1255
1256 if (FormatTok.Tok.is(tok::eof))
1257 return FormatTok;
1258 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001259 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001260 }
Manuel Klimekef920692013-01-07 07:56:50 +00001261
1262 // Now FormatTok is the next non-whitespace token.
1263 FormatTok.TokenLength = Text.size();
1264
Manuel Klimek1abf7892013-01-04 23:34:14 +00001265 // In case the token starts with escaped newlines, we want to
1266 // take them into account as whitespace - this pattern is quite frequent
1267 // in macro definitions.
1268 // FIXME: What do we want to do with other escaped spaces, and escaped
1269 // spaces or newlines in the middle of tokens?
1270 // FIXME: Add a more explicit test.
1271 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001272 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001273 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001274 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001275 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001276 }
1277
1278 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001279 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001280 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281 FormatTok.Tok.setKind(Info.getTokenID());
1282 }
1283
1284 if (FormatTok.Tok.is(tok::greatergreater)) {
1285 FormatTok.Tok.setKind(tok::greater);
1286 GreaterStashed = true;
1287 }
1288
1289 return FormatTok;
1290 }
1291
1292private:
1293 FormatToken FormatTok;
1294 bool GreaterStashed;
1295 Lexer &Lex;
1296 SourceManager &SourceMgr;
1297 IdentifierTable IdentTable;
1298
1299 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001300 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001301 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1302 Tok.getLength());
1303 }
1304};
1305
Daniel Jasperf7935112012-12-03 18:12:45 +00001306class Formatter : public UnwrappedLineConsumer {
1307public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001308 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1309 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001310 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001311 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001312 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001313
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001314 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001315
Daniel Jasperf7935112012-12-03 18:12:45 +00001316 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001317 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001318 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001319 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001320 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001321 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1322 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001323 I != E; ++I) {
1324 const UnwrappedLine &TheLine = *I;
1325 if (touchesRanges(TheLine)) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001326 llvm::OwningPtr<TokenAnnotator> AnnotatedLine(
1327 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1328 if (!AnnotatedLine->annotate())
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001329 break;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001330 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001331 TheLine.Level, TheLine.InPPDirective,
1332 PreviousEndOfLineColumn);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001333
1334 UnwrappedLine Line(TheLine);
1335 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1336 I, E);
1337 UnwrappedLineFormatter Formatter(
1338 Style, SourceMgr, Line, Indent, FitsOnALine,
1339 AnnotatedLine->getLineType(), AnnotatedLine->getRootToken(),
1340 Replaces, StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001341 PreviousEndOfLineColumn = Formatter.format();
1342 } else {
1343 // If we did not reformat this unwrapped line, the column at the end of
1344 // the last token is unchanged - thus, we can calculate the end of the
1345 // last token, and return the result.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001346 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001347 PreviousEndOfLineColumn =
1348 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1349 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1350 Lex.getLangOpts()) -
1351 1;
1352 }
1353 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001354 return Replaces;
1355 }
1356
1357private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001358 /// \brief Tries to merge lines into one.
1359 ///
1360 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1361 /// if possible; note that \c I will be incremented when lines are merged.
1362 ///
1363 /// Returns whether the resulting \c Line can fit in a single line.
1364 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
1365 llvm::OwningPtr<TokenAnnotator> &AnnotatedLine,
1366 std::vector<UnwrappedLine>::iterator &I,
1367 std::vector<UnwrappedLine>::iterator E) {
1368 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1369
1370 // Check whether the UnwrappedLine can be put onto a single line. If
1371 // so, this is bound to be the optimal solution (by definition) and we
1372 // don't need to analyze the entire solution space.
1373 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1374 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1375 return FitsOnALine;
1376
1377 // Try to merge the next two lines if possible.
1378 UnwrappedLine Combined(Line);
1379
1380 // First, check that the current line allows merging. This is the case if
1381 // we're not in a control flow statement and the last token is an opening
1382 // brace.
1383 FormatToken *Last = &Combined.RootToken;
1384 bool AllowedTokens =
Manuel Klimek2acb7b72013-01-11 19:17:44 +00001385 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1386 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1387 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1388 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001389 // This gets rid of all ObjC @ keywords and methods.
1390 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus) &&
1391 Last->Tok.isNot(tok::plus);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001392 while (!Last->Children.empty())
1393 Last = &Last->Children.back();
1394 if (!Last->Tok.is(tok::l_brace))
1395 return FitsOnALine;
1396
1397 // Second, check that the next line does not contain any braces - if it
1398 // does, readability declines when putting it into a single line.
1399 const FormatToken *Next = &(I + 1)->RootToken;
1400 while (Next) {
1401 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1402 !Next->Tok.is(tok::r_brace);
1403 Last->Children.push_back(*Next);
1404 Last = &Last->Children[0];
1405 Last->Children.clear();
1406 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1407 }
1408
1409 // Last, check that the third line contains a single closing brace.
1410 Next = &(I + 2)->RootToken;
1411 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1412 if (!Next->Children.empty() || !AllowedTokens)
1413 return FitsOnALine;
1414 Last->Children.push_back(*Next);
1415
1416 llvm::OwningPtr<TokenAnnotator> CombinedAnnotator(
1417 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1418 if (CombinedAnnotator->annotate() &&
1419 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1420 // If the merged line fits, we use that instead and skip the next two
1421 // lines.
1422 AnnotatedLine.reset(CombinedAnnotator.take());
1423 Line = Combined;
1424 I += 2;
1425 }
1426 return FitsOnALine;
1427 }
1428
1429 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001430 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001431 while (!Last->Children.empty())
1432 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001433 return Last;
1434 }
1435
1436 bool touchesRanges(const UnwrappedLine &TheLine) {
1437 const FormatToken *First = &TheLine.RootToken;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001438 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001439 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001440 First->Tok.getLocation(),
1441 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001442 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001443 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1444 Ranges[i].getBegin()) &&
1445 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1446 LineRange.getBegin()))
1447 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001448 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001449 return false;
1450 }
1451
1452 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1453 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001454 }
1455
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001456 /// \brief Add a new line and the required indent before the first Token
1457 /// of the \c UnwrappedLine if there was no structural parsing error.
1458 /// Returns the indent level of the \c UnwrappedLine.
1459 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1460 bool InPPDirective,
1461 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001462 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001463 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1464 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1465
1466 unsigned Newlines = std::min(Tok.NewlinesBefore,
1467 Style.MaxEmptyLinesToKeep + 1);
1468 if (Newlines == 0 && !Tok.IsFirst)
1469 Newlines = 1;
1470 unsigned Indent = Level * 2;
1471
1472 bool IsAccessModifier = false;
1473 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1474 RootToken.is(tok::kw_private))
1475 IsAccessModifier = true;
1476 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1477 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1478 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1479 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1480 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1481 IsAccessModifier = true;
1482
1483 if (IsAccessModifier &&
1484 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1485 Indent += Style.AccessModifierOffset;
1486 if (!InPPDirective || Tok.HasUnescapedNewline) {
1487 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1488 } else {
1489 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1490 SourceMgr, Replaces);
1491 }
1492 return Indent;
1493 }
1494
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001495 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001496 FormatStyle Style;
1497 Lexer &Lex;
1498 SourceManager &SourceMgr;
1499 tooling::Replacements Replaces;
1500 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001501 std::vector<UnwrappedLine> UnwrappedLines;
1502 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001503};
1504
1505tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1506 SourceManager &SourceMgr,
1507 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001508 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1509 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1510 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1511 DiagnosticsEngine Diagnostics(
1512 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1513 &DiagnosticPrinter, false);
1514 Diagnostics.setSourceManager(&SourceMgr);
1515 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001516 return formatter.format();
1517}
1518
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001519LangOptions getFormattingLangOpts() {
1520 LangOptions LangOpts;
1521 LangOpts.CPlusPlus = 1;
1522 LangOpts.CPlusPlus11 = 1;
1523 LangOpts.Bool = 1;
1524 LangOpts.ObjC1 = 1;
1525 LangOpts.ObjC2 = 1;
1526 return LangOpts;
1527}
1528
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001529} // namespace format
1530} // namespace clang