blob: 87b996a7823b2b932c925ae255e18ec2a712ccf9 [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 Weber9efe2912013-01-10 23:11:41 +000042 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000043 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_OverloadedOperator,
45 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000046 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_TemplateCloser,
48 TT_TemplateOpener,
49 TT_TrailingUnaryOperator,
50 TT_UnaryOperator,
51 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000052};
53
54enum LineType {
55 LT_Invalid,
56 LT_Other,
57 LT_PreprocessorDirective,
58 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000059 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000060 LT_ObjCMethodDecl,
61 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000062};
63
Daniel Jasper7c85fde2013-01-08 14:56:18 +000064class AnnotatedToken {
65public:
66 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000067 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
68 CanBreakBefore(false), MustBreakBefore(false),
69 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000070
71 bool is(tok::TokenKind Kind) const {
72 return FormatTok.Tok.is(Kind);
73 }
74 bool isNot(tok::TokenKind Kind) const {
75 return FormatTok.Tok.isNot(Kind);
76 }
77 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
78 return FormatTok.Tok.isObjCAtKeyword(Kind);
79 }
80
81 FormatToken FormatTok;
82
Daniel Jasperf7935112012-12-03 18:12:45 +000083 TokenType Type;
84
Daniel Jasperf7935112012-12-03 18:12:45 +000085 bool SpaceRequiredBefore;
86 bool CanBreakBefore;
87 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000088
89 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000090
91 std::vector<AnnotatedToken> Children;
92 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000093};
94
Daniel Jasper7c85fde2013-01-08 14:56:18 +000095static prec::Level getPrecedence(const AnnotatedToken &Tok) {
96 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000097}
98
Daniel Jasperf7935112012-12-03 18:12:45 +000099using llvm::MutableArrayRef;
100
101FormatStyle getLLVMStyle() {
102 FormatStyle LLVMStyle;
103 LLVMStyle.ColumnLimit = 80;
104 LLVMStyle.MaxEmptyLinesToKeep = 1;
105 LLVMStyle.PointerAndReferenceBindToType = false;
106 LLVMStyle.AccessModifierOffset = -2;
107 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000108 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000109 LLVMStyle.SpacesBeforeTrailingComments = 1;
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;
Nico Webera6087752013-01-10 20:12:55 +0000124 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000125 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000126 return GoogleStyle;
127}
128
129struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000130 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000131 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000132 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000133};
134
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000135/// \brief Replaces the whitespace in front of \p Tok. Only call once for
136/// each \c FormatToken.
137static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
138 unsigned Spaces, const FormatStyle &Style,
139 SourceManager &SourceMgr,
140 tooling::Replacements &Replaces) {
141 Replaces.insert(tooling::Replacement(
142 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
143 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
144}
145
146/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
147/// backslashes to escape newlines inside a preprocessor directive.
148///
149/// This function and \c replaceWhitespace have the same behavior if
150/// \c Newlines == 0.
151static void replacePPWhitespace(
152 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
153 unsigned WhitespaceStartColumn, const FormatStyle &Style,
154 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
155 std::string NewLineText;
156 if (NewLines > 0) {
157 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
158 WhitespaceStartColumn);
159 for (unsigned i = 0; i < NewLines; ++i) {
160 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
161 NewLineText += "\\\n";
162 Offset = 0;
163 }
164 }
165 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
166 Tok.FormatTok.WhiteSpaceLength,
167 NewLineText + std::string(Spaces, ' ')));
168}
169
Daniel Jasperf7935112012-12-03 18:12:45 +0000170class UnwrappedLineFormatter {
171public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000172 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
173 const UnwrappedLine &Line, unsigned FirstIndent,
174 bool FitsOnALine, LineType CurrentLineType,
175 const AnnotatedToken &RootToken,
176 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000177 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000178 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000179 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000180 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000181 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000182 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000183 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000184 }
185
Manuel Klimek1abf7892013-01-04 23:34:14 +0000186 /// \brief Formats an \c UnwrappedLine.
187 ///
188 /// \returns The column after the last token in the last line of the
189 /// \c UnwrappedLine.
190 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000191 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000192 IndentState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000193 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000194 State.NextToken = &RootToken;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000195 State.Indent.push_back(FirstIndent + 4);
196 State.LastSpace.push_back(FirstIndent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000197 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000198 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000199 State.ForLoopVariablePos = 0;
200 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000201 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000202
203 // The first token has already been indented and thus consumed.
204 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000205
206 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000207 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000208 if (FitsOnALine) {
209 addTokenToState(false, false, State);
210 } else {
211 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
212 unsigned Break = calcPenalty(State, true, NoBreak);
213 addTokenToState(Break < NoBreak, false, State);
214 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000215 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000216 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000217 }
218
219private:
220 /// \brief The current state when indenting a unwrapped line.
221 ///
222 /// As the indenting tries different combinations this is copied by value.
223 struct IndentState {
224 /// \brief The number of used columns in the current line.
225 unsigned Column;
226
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000227 const AnnotatedToken *NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000228
Daniel Jasper6d822722012-12-24 16:43:00 +0000229 /// \brief The parenthesis level of the first token on the current line.
230 unsigned StartOfLineLevel;
231
Daniel Jasperf7935112012-12-03 18:12:45 +0000232 /// \brief The position to which a specific parenthesis level needs to be
233 /// indented.
234 std::vector<unsigned> Indent;
235
Daniel Jaspere9de2602012-12-06 09:56:08 +0000236 /// \brief The position of the last space on each level.
237 ///
238 /// Used e.g. to break like:
239 /// functionCall(Parameter, otherCall(
240 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000241 std::vector<unsigned> LastSpace;
242
Daniel Jaspere9de2602012-12-06 09:56:08 +0000243 /// \brief The position the first "<<" operator encountered on each level.
244 ///
245 /// Used to align "<<" operators. 0 if no such operator has been encountered
246 /// on a level.
247 std::vector<unsigned> FirstLessLess;
248
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000249 /// \brief Whether a newline needs to be inserted before the block's closing
250 /// brace.
251 ///
252 /// We only want to insert a newline before the closing brace if there also
253 /// was a newline after the beginning left brace.
254 std::vector<bool> BreakBeforeClosingBrace;
255
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000256 /// \brief The column of the first variable in a for-loop declaration.
257 ///
258 /// Used to align the second variable if necessary.
259 unsigned ForLoopVariablePos;
260
261 /// \brief \c true if this line contains a continued for-loop section.
262 bool LineContainsContinuedForLoopSection;
263
Daniel Jasperf7935112012-12-03 18:12:45 +0000264 /// \brief Comparison operator to be able to used \c IndentState in \c map.
265 bool operator<(const IndentState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000266 if (Other.NextToken != NextToken)
267 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000268 if (Other.Column != Column)
269 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000270 if (Other.StartOfLineLevel != StartOfLineLevel)
271 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000272 if (Other.Indent.size() != Indent.size())
273 return Other.Indent.size() > Indent.size();
274 for (int i = 0, e = Indent.size(); i != e; ++i) {
275 if (Other.Indent[i] != Indent[i])
276 return Other.Indent[i] > Indent[i];
277 }
278 if (Other.LastSpace.size() != LastSpace.size())
279 return Other.LastSpace.size() > LastSpace.size();
280 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
281 if (Other.LastSpace[i] != LastSpace[i])
282 return Other.LastSpace[i] > LastSpace[i];
283 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000284 if (Other.FirstLessLess.size() != FirstLessLess.size())
285 return Other.FirstLessLess.size() > FirstLessLess.size();
286 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
287 if (Other.FirstLessLess[i] != FirstLessLess[i])
288 return Other.FirstLessLess[i] > FirstLessLess[i];
289 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000290 if (Other.ForLoopVariablePos != ForLoopVariablePos)
291 return Other.ForLoopVariablePos < ForLoopVariablePos;
292 if (Other.LineContainsContinuedForLoopSection !=
293 LineContainsContinuedForLoopSection)
294 return LineContainsContinuedForLoopSection;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000295 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
296 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000297 return false;
298 }
299 };
300
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000301 /// \brief Appends the next token to \p State and updates information
302 /// necessary for indentation.
303 ///
304 /// Puts the token on the current line if \p Newline is \c true and adds a
305 /// line break and necessary indentation otherwise.
306 ///
307 /// If \p DryRun is \c false, also creates and stores the required
308 /// \c Replacement.
309 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000310 const AnnotatedToken &Current = *State.NextToken;
311 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weber51306d22013-01-10 00:25:19 +0000312 assert(State.Indent.size());
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000313 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000314
315 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000316 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000317 if (Current.is(tok::r_brace)) {
318 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000319 } else if (Current.is(tok::string_literal) &&
320 Previous.is(tok::string_literal)) {
321 State.Column = State.Column - Previous.FormatTok.TokenLength;
322 } else if (Current.is(tok::lessless) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000323 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000324 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000325 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000326 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
327 Current.is(tok::period) || Previous.is(tok::question) ||
328 Previous.Type == TT_ConditionalExpr)) {
329 // Indent and extra 4 spaces after if we know the current expression is
330 // continued. Don't do that on the top level, as we already indent 4
331 // there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000332 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000333 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000334 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000335 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000336 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000337 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000338 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000339 }
340
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000341 // A line starting with a closing brace is assumed to be correct for the
342 // same level as before the opening brace.
343 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000344
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000345 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000346 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000347
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000348 if (!DryRun) {
349 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000350 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
351 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000352 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000353 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000354 WhitespaceStartColumn, Style, SourceMgr,
355 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000356 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000357
Daniel Jasper89058942013-01-09 09:50:48 +0000358 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000359 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000360 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000361 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000363 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
364 State.ForLoopVariablePos = State.Column -
365 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000367 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
368 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000369 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000370
Daniel Jasperf7935112012-12-03 18:12:45 +0000371 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000372 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000373
Daniel Jasperbcab4302013-01-09 10:40:23 +0000374 // FIXME: Do we need to do this for assignments nested in other
375 // expressions?
376 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000377 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000378 Previous.is(tok::kw_return)))
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000379 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000380 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000381 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000382 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000383 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000384
Daniel Jasper206df732013-01-07 13:08:40 +0000385 // Top-level spaces that are not part of assignments are exempt as that
386 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000387 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000388 if (Spaces > 0 &&
389 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000390 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000392 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000393 if (Newline && Previous.is(tok::l_brace)) {
394 State.BreakBeforeClosingBrace.back() = true;
395 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000396 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000397
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000398 /// \brief Mark the next token as consumed in \p State and modify its stacks
399 /// accordingly.
400 void moveStateToNextToken(IndentState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000401 const AnnotatedToken &Current = *State.NextToken;
Nico Weber51306d22013-01-10 00:25:19 +0000402 assert(State.Indent.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000403 unsigned ParenLevel = State.Indent.size() - 1;
404
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000405 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000406 State.FirstLessLess[ParenLevel] = State.Column;
407
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000408 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000409 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000410 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
411 Current.is(tok::l_brace) ||
412 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000413 if (Current.is(tok::l_brace)) {
414 // FIXME: This does not work with nested static initializers.
415 // Implement a better handling for static initializers and similar
416 // constructs.
417 State.Indent.push_back(Line.Level * 2 + 2);
418 } else {
419 State.Indent.push_back(4 + State.LastSpace.back());
420 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000421 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000422 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000423 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000424 }
425
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000426 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000427 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000428 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
429 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
430 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000431 State.Indent.pop_back();
432 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000433 State.FirstLessLess.pop_back();
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000434 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000435 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000436
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000437 if (State.NextToken->Children.empty())
438 State.NextToken = NULL;
439 else
440 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000441
442 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000443 }
444
Nico Weber49cbc2c2013-01-07 15:15:29 +0000445 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000446 unsigned splitPenalty(const AnnotatedToken &Tok) {
447 const AnnotatedToken &Left = Tok;
448 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000449
450 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000451 if (RootToken.is(tok::kw_for) &&
452 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000453 return 20;
454
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000455 if (Left.is(tok::semi) || Left.is(tok::comma) ||
456 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000457 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000458 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000459 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000460
Daniel Jasper399d24b2013-01-09 07:06:56 +0000461 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
462 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000463 prec::Level Level = getPrecedence(Left);
464
465 // Breaking after an assignment leads to a bad result as the two sides of
466 // the assignment are visually very close together.
467 if (Level == prec::Assignment)
468 return 50;
469
Daniel Jasperde5c2072012-12-24 00:13:23 +0000470 if (Level != prec::Unknown)
471 return Level;
472
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000473 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000474 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000475
Daniel Jasperf7935112012-12-03 18:12:45 +0000476 return 3;
477 }
478
Daniel Jasper2df93312013-01-09 10:16:05 +0000479 unsigned getColumnLimit() {
480 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
481 }
482
Daniel Jasperf7935112012-12-03 18:12:45 +0000483 /// \brief Calculate the number of lines needed to format the remaining part
484 /// of the unwrapped line.
485 ///
486 /// Assumes the formatting so far has led to
487 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
488 /// added after the previous token.
489 ///
490 /// \param StopAt is used for optimization. If we can determine that we'll
491 /// definitely need at least \p StopAt additional lines, we already know of a
492 /// better solution.
493 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
494 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000495 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000496 return 0;
497
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000498 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000499 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000500 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000501 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000502 if (!NewLine && State.NextToken->is(tok::r_brace) &&
503 State.BreakBeforeClosingBrace.back())
504 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000505 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000506 State.LineContainsContinuedForLoopSection)
507 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000508
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000509 unsigned CurrentPenalty = 0;
510 if (NewLine) {
511 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000512 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000513 } else {
514 if (State.Indent.size() < State.StartOfLineLevel)
515 CurrentPenalty += Parameters.PenaltyLevelDecrease *
516 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000517 }
518
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000519 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000520
Daniel Jasper2df93312013-01-09 10:16:05 +0000521 // Exceeding column limit is bad, assign penalty.
522 if (State.Column > getColumnLimit()) {
523 unsigned ExcessCharacters = State.Column - getColumnLimit();
524 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
525 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000526
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 if (StopAt <= CurrentPenalty)
528 return UINT_MAX;
529 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000530 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000531 if (I != Memory.end()) {
532 // If this state has already been examined, we can safely return the
533 // previous result if we
534 // - have not hit the optimatization (and thus returned UINT_MAX) OR
535 // - are now computing for a smaller or equal StopAt.
536 unsigned SavedResult = I->second.first;
537 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000538 if (SavedResult != UINT_MAX)
539 return SavedResult + CurrentPenalty;
540 else if (StopAt <= SavedStopAt)
541 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000542 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000543
544 unsigned NoBreak = calcPenalty(State, false, StopAt);
545 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
546 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000547
548 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
549 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000550 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000551
552 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 }
554
Daniel Jasperf7935112012-12-03 18:12:45 +0000555 FormatStyle Style;
556 SourceManager &SourceMgr;
557 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000558 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000559 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000560 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000561 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000562 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000563
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000564 // A map from an indent state to a pair (Result, Used-StopAt).
565 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
566 StateMap Memory;
567
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 OptimizationParameters Parameters;
569};
570
571/// \brief Determines extra information about the tokens comprising an
572/// \c UnwrappedLine.
573class TokenAnnotator {
574public:
575 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000576 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000577 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
578 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000579 }
580
581 /// \brief A parser that gathers additional information about tokens.
582 ///
583 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
584 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
585 /// into template parameter lists.
586 class AnnotatingParser {
587 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000588 AnnotatingParser(AnnotatedToken &RootToken)
589 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 }
591
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000592 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000593 while (CurrentToken != NULL) {
594 if (CurrentToken->is(tok::greater)) {
595 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 next();
597 return true;
598 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000599 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
600 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000601 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
603 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000604 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000605 if (!consumeToken())
606 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 }
608 return false;
609 }
610
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000611 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000612 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
613 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000614 while (CurrentToken != NULL) {
615 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000616 next();
617 return true;
618 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000620 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000621 if (!consumeToken())
622 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 }
624 return false;
625 }
626
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000627 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 while (CurrentToken != NULL) {
629 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 next();
631 return true;
632 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000633 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000634 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000635 if (!consumeToken())
636 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000637 }
638 return false;
639 }
640
Daniel Jasper83a54d22013-01-10 09:26:47 +0000641 bool parseBrace() {
642 while (CurrentToken != NULL) {
643 if (CurrentToken->is(tok::r_brace)) {
644 next();
645 return true;
646 }
647 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
648 return false;
649 if (!consumeToken())
650 return false;
651 }
652 // Lines can currently end with '{'.
653 return true;
654 }
655
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000656 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000657 while (CurrentToken != NULL) {
658 if (CurrentToken->is(tok::colon)) {
659 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 next();
661 return true;
662 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000663 if (!consumeToken())
664 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000665 }
666 return false;
667 }
668
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000669 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
671 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000672 next();
673 if (!parseAngle())
674 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000675 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000676 parseLine();
677 return true;
678 }
679 return false;
680 }
681
Daniel Jasperc0880a92013-01-04 18:52:56 +0000682 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000683 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000685 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000686 case tok::plus:
687 case tok::minus:
688 // At the start of the line, +/- specific ObjectiveC method
689 // declarations.
690 if (Tok->Parent == NULL)
691 Tok->Type = TT_ObjCMethodSpecifier;
692 break;
693 case tok::l_paren: {
694 bool ParensWereObjCReturnType =
695 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000696 if (!parseParens())
697 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000698 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
699 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000700 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000701 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
702 CurrentToken->Type = TT_ObjCSelectorStart;
703 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000704 }
Nico Weber9efe2912013-01-10 23:11:41 +0000705 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000707 if (!parseSquare())
708 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000709 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000710 case tok::l_brace:
711 if (!parseBrace())
712 return false;
713 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000715 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000716 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000718 Tok->Type = TT_BinaryOperator;
719 CurrentToken = Tok;
720 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000721 }
722 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000723 case tok::r_paren:
724 case tok::r_square:
725 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000726 case tok::r_brace:
727 // Lines can start with '}'.
728 if (Tok->Parent != NULL)
729 return false;
730 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000731 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000732 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 break;
734 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000735 if (CurrentToken->is(tok::l_paren)) {
736 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000737 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000738 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
739 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000740 next();
741 }
742 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000743 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
744 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000745 next();
746 }
747 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000748 break;
749 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000750 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000751 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000752 case tok::kw_template:
753 parseTemplateDeclaration();
754 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000755 default:
756 break;
757 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000758 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 }
760
Daniel Jasper050948a52012-12-21 17:58:39 +0000761 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000762 while (CurrentToken != NULL) {
763 if (CurrentToken->is(tok::slash))
764 CurrentToken->Type = TT_DirectorySeparator;
765 else if (CurrentToken->is(tok::less))
766 CurrentToken->Type = TT_TemplateOpener;
767 else if (CurrentToken->is(tok::greater))
768 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000769 next();
770 }
771 }
772
773 void parsePreprocessorDirective() {
774 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000775 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000776 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000777 // Hashes in the middle of a line can lead to any strange token
778 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000779 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000780 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000781 switch (
782 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000783 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000784 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000785 parseIncludeDirective();
786 break;
787 default:
788 break;
789 }
790 }
791
Daniel Jasperda16db32013-01-07 10:48:50 +0000792 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000793 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000794 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000795 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000796 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000797 while (CurrentToken != NULL) {
798 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000799 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000800 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000801 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000802 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000803 if (KeywordVirtualFound)
804 return LT_VirtualFunctionDecl;
805 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000806 }
807
808 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000809 if (CurrentToken != NULL && !CurrentToken->Children.empty())
810 CurrentToken = &CurrentToken->Children[0];
811 else
812 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 }
814
815 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000816 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000817 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 };
819
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000820 void createAnnotatedTokens(AnnotatedToken &Current) {
821 if (!Current.FormatTok.Children.empty()) {
822 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
823 Current.Children.back().Parent = &Current;
824 createAnnotatedTokens(Current.Children.back());
825 }
826 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000827
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000828 void calculateExtraInformation(AnnotatedToken &Current) {
829 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
830
Manuel Klimek52b15152013-01-09 15:25:02 +0000831 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000832 Current.MustBreakBefore = true;
833 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000834 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
835 TT_LineComment || (Current.is(tok::string_literal) &&
836 Current.Parent->is(tok::string_literal))) {
837 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000838 } else {
839 Current.MustBreakBefore = false;
840 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000842 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000843 if (!Current.Children.empty())
844 calculateExtraInformation(Current.Children[0]);
845 }
846
847 bool annotate() {
848 createAnnotatedTokens(RootToken);
849
850 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000851 CurrentLineType = Parser.parseLine();
852 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000853 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000854
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000855 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000856
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000857 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000858 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000859 else if (RootToken.Type == TT_ObjCDecl)
860 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000861 else if (RootToken.Type == TT_ObjCProperty)
862 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000863
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 if (!RootToken.Children.empty())
865 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000866 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000867 }
868
Daniel Jasperda16db32013-01-07 10:48:50 +0000869 LineType getLineType() {
870 return CurrentLineType;
871 }
872
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000873 const AnnotatedToken &getRootToken() {
874 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 }
876
877private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000878 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
879 if (getPrecedence(Current) == prec::Assignment ||
880 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
881 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000882
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000883 if (Current.Type == TT_Unknown) {
884 if (Current.is(tok::star) || Current.is(tok::amp)) {
885 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000886 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
887 Current.is(tok::caret)) {
888 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000889 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
890 Current.Type = determineIncrementUsage(Current);
891 } else if (Current.is(tok::exclaim)) {
892 Current.Type = TT_UnaryOperator;
893 } else if (isBinaryOperator(Current)) {
894 Current.Type = TT_BinaryOperator;
895 } else if (Current.is(tok::comment)) {
896 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
897 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000898 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000899 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000902 } else if (Current.is(tok::r_paren) &&
903 (Current.Parent->Type == TT_PointerOrReference ||
904 Current.Parent->Type == TT_TemplateCloser)) {
905 // FIXME: We need to get smarter and understand more cases of casts.
906 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000907 } else if (Current.is(tok::at) && Current.Children.size()) {
908 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
909 case tok::objc_interface:
910 case tok::objc_implementation:
911 case tok::objc_protocol:
912 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000913 break;
914 case tok::objc_property:
915 Current.Type = TT_ObjCProperty;
916 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000917 default:
918 break;
919 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 }
921 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000922
923 if (!Current.Children.empty())
924 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000925 }
926
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000927 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000928 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000929 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000930 }
931
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
933 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000934 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000935 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000936 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000937 const FormatToken &PrevToken = Tok.Parent->FormatTok;
938 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000939
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000940 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
941 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000942 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
943 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000944 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000945
Daniel Jasper542de162013-01-02 15:46:59 +0000946 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000947 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
948 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
949 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
950 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000951 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000952
Daniel Jasper542de162013-01-02 15:46:59 +0000953 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
954 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000955 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000956
Daniel Jasper426702d2012-12-05 07:51:39 +0000957 // It is very unlikely that we are going to find a pointer or reference type
958 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000959 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000960 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000961
Daniel Jasperda16db32013-01-07 10:48:50 +0000962 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000963 }
964
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000965 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000966 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000967 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
968 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
969 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +0000970 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
971 Tok.Parent->is(tok::at))
Daniel Jasperda16db32013-01-07 10:48:50 +0000972 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000973
974 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000975 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +0000976 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000977
978 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000979 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000980 }
981
982 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000983 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
984 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +0000985 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000986
Daniel Jasperda16db32013-01-07 10:48:50 +0000987 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000988 }
989
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000990 bool spaceRequiredBetween(const AnnotatedToken &Left,
991 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +0000992 if (Right.is(tok::hashhash))
993 return Left.is(tok::hash);
994 if (Left.is(tok::hashhash) || Left.is(tok::hash))
995 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +0000996 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
997 return false;
Nico Webera6087752013-01-10 20:12:55 +0000998 if (Right.is(tok::less) &&
999 (Left.is(tok::kw_template) ||
1000 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001001 return true;
1002 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1003 return false;
1004 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1005 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001006 if (Left.is(tok::at) &&
1007 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1008 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001009 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1010 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001011 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001012 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1013 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001014 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001015 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001016 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1017 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001018 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 return Right.FormatTok.Tok.isLiteral() ||
1020 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 if (Right.is(tok::star) && Left.is(tok::l_paren))
1022 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1024 Right.is(tok::r_square))
1025 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001026 if (Left.is(tok::coloncolon) ||
1027 (Right.is(tok::coloncolon) &&
1028 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 return false;
1030 if (Left.is(tok::period) || Right.is(tok::period))
1031 return false;
1032 if (Left.is(tok::colon) || Right.is(tok::colon))
1033 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001034 if (Left.is(tok::l_paren))
1035 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001037 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1038 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1039 Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001040 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001042 if (Left.is(tok::at) &&
1043 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001044 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001045 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1046 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001047 return true;
1048 }
1049
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001050 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001051 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001052 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1053 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001054 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001055 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001056 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001057 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001058 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1059 if (Tok.Type == TT_ObjCSelectorStart)
1060 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001061 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001062 // Don't space between ')' and <id>
1063 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001064 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001065 // Don't space between ':' and '('
1066 return false;
1067 }
Nico Webera2a84952013-01-10 21:30:42 +00001068 if (CurrentLineType == LT_ObjCProperty &&
1069 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1070 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001071
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001072 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001073 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001074 if (Tok.Type == TT_OverloadedOperator)
1075 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001076 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001078 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001079 if (Tok.is(tok::colon))
1080 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001081 if (Tok.Parent->Type == TT_UnaryOperator ||
1082 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001083 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001084 if (Tok.Type == TT_UnaryOperator)
1085 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001086 Tok.Parent->isNot(tok::l_square) &&
1087 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001088 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1089 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001090 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1091 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001092 if (Tok.Type == TT_DirectorySeparator ||
1093 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001094 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001095 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001096 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001097 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001098 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001099 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001100 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001101 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001102 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001103 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001104 }
1105
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 bool canBreakBefore(const AnnotatedToken &Right) {
1107 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001108 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001109 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1110 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001111 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001112 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1113 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001114 // Don't break this identifier as ':' or identifier
1115 // before it will break.
1116 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1118 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001119 // Don't break at ':' if identifier before it can beak.
1120 return false;
1121 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001123 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001125 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001126 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001127 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001128 return false;
1129
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001130 if (Right.is(tok::comment))
1131 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001133 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001134 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1136 Left.is(tok::comma) || Right.is(tok::lessless) ||
1137 Right.is(tok::arrow) || Right.is(tok::period) ||
1138 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001139 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001140 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001142 }
1143
Daniel Jasperf7935112012-12-03 18:12:45 +00001144 FormatStyle Style;
1145 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001146 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001147 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001148 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001149};
1150
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001151class LexerBasedFormatTokenSource : public FormatTokenSource {
1152public:
1153 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001154 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001155 IdentTable(Lex.getLangOpts()) {
1156 Lex.SetKeepWhitespaceMode(true);
1157 }
1158
1159 virtual FormatToken getNextToken() {
1160 if (GreaterStashed) {
1161 FormatTok.NewlinesBefore = 0;
1162 FormatTok.WhiteSpaceStart =
1163 FormatTok.Tok.getLocation().getLocWithOffset(1);
1164 FormatTok.WhiteSpaceLength = 0;
1165 GreaterStashed = false;
1166 return FormatTok;
1167 }
1168
1169 FormatTok = FormatToken();
1170 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001171 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001172 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001173 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1174 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001175
1176 // Consume and record whitespace until we find a significant token.
1177 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001178 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001179 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1180 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001181 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1182
1183 if (FormatTok.Tok.is(tok::eof))
1184 return FormatTok;
1185 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001186 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001187 }
Manuel Klimekef920692013-01-07 07:56:50 +00001188
1189 // Now FormatTok is the next non-whitespace token.
1190 FormatTok.TokenLength = Text.size();
1191
Manuel Klimek1abf7892013-01-04 23:34:14 +00001192 // In case the token starts with escaped newlines, we want to
1193 // take them into account as whitespace - this pattern is quite frequent
1194 // in macro definitions.
1195 // FIXME: What do we want to do with other escaped spaces, and escaped
1196 // spaces or newlines in the middle of tokens?
1197 // FIXME: Add a more explicit test.
1198 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001199 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001200 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001201 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001202 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001203 }
1204
1205 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001206 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001207 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001208 FormatTok.Tok.setKind(Info.getTokenID());
1209 }
1210
1211 if (FormatTok.Tok.is(tok::greatergreater)) {
1212 FormatTok.Tok.setKind(tok::greater);
1213 GreaterStashed = true;
1214 }
1215
1216 return FormatTok;
1217 }
1218
1219private:
1220 FormatToken FormatTok;
1221 bool GreaterStashed;
1222 Lexer &Lex;
1223 SourceManager &SourceMgr;
1224 IdentifierTable IdentTable;
1225
1226 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001227 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1229 Tok.getLength());
1230 }
1231};
1232
Daniel Jasperf7935112012-12-03 18:12:45 +00001233class Formatter : public UnwrappedLineConsumer {
1234public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001235 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1236 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001237 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001238 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001239 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001240
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001241 virtual ~Formatter() {
1242 }
1243
Daniel Jasperf7935112012-12-03 18:12:45 +00001244 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001245 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001246 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001247 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001248 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001249 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1250 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001251 I != E; ++I) {
1252 const UnwrappedLine &TheLine = *I;
1253 if (touchesRanges(TheLine)) {
1254 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
1255 if (!Annotator.annotate())
1256 break;
1257 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1258 TheLine.Level, TheLine.InPPDirective,
1259 PreviousEndOfLineColumn);
1260 bool FitsOnALine = fitsOnALine(Annotator.getRootToken(), Indent,
1261 TheLine.InPPDirective);
1262 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1263 FitsOnALine, Annotator.getLineType(),
1264 Annotator.getRootToken(), Replaces,
1265 StructuralError);
1266 PreviousEndOfLineColumn = Formatter.format();
1267 } else {
1268 // If we did not reformat this unwrapped line, the column at the end of
1269 // the last token is unchanged - thus, we can calculate the end of the
1270 // last token, and return the result.
1271 const FormatToken *Last = getLastLine(TheLine);
1272 PreviousEndOfLineColumn =
1273 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1274 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1275 Lex.getLangOpts()) -
1276 1;
1277 }
1278 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001279 return Replaces;
1280 }
1281
1282private:
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001283 const FormatToken *getLastLine(const UnwrappedLine &TheLine) {
1284 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001285 while (!Last->Children.empty())
1286 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001287 return Last;
1288 }
1289
1290 bool touchesRanges(const UnwrappedLine &TheLine) {
1291 const FormatToken *First = &TheLine.RootToken;
1292 const FormatToken *Last = getLastLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001293 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001294 First->Tok.getLocation(),
1295 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001296 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001297 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1298 Ranges[i].getBegin()) &&
1299 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1300 LineRange.getBegin()))
1301 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001302 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001303 return false;
1304 }
1305
1306 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1307 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001308 }
1309
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +00001310 bool fitsOnALine(const AnnotatedToken &RootToken, unsigned Indent,
1311 bool InPPDirective) {
1312 // Check whether the UnwrappedLine can be put onto a single line. If so,
1313 // this is bound to be the optimal solution (by definition) and we don't
1314 // need to analyze the entire solution space.
1315 unsigned Columns = Indent + RootToken.FormatTok.TokenLength;
1316 bool FitsOnALine = true;
1317 const AnnotatedToken *Tok = &RootToken;
1318 while (Tok != NULL) {
1319 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
1320 Tok->FormatTok.TokenLength;
1321 // A special case for the colon of a constructor initializer as this only
1322 // needs to be put on a new line if the line needs to be split.
1323 if (Columns > Style.ColumnLimit - (InPPDirective ? 1 : 0) ||
1324 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
1325 FitsOnALine = false;
1326 break;
1327 }
1328 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
1329 }
1330 return FitsOnALine;
1331 }
1332
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001333 /// \brief Add a new line and the required indent before the first Token
1334 /// of the \c UnwrappedLine if there was no structural parsing error.
1335 /// Returns the indent level of the \c UnwrappedLine.
1336 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1337 bool InPPDirective,
1338 unsigned PreviousEndOfLineColumn) {
1339 const FormatToken& Tok = RootToken.FormatTok;
1340 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1341 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1342
1343 unsigned Newlines = std::min(Tok.NewlinesBefore,
1344 Style.MaxEmptyLinesToKeep + 1);
1345 if (Newlines == 0 && !Tok.IsFirst)
1346 Newlines = 1;
1347 unsigned Indent = Level * 2;
1348
1349 bool IsAccessModifier = false;
1350 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1351 RootToken.is(tok::kw_private))
1352 IsAccessModifier = true;
1353 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1354 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1355 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1356 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1357 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1358 IsAccessModifier = true;
1359
1360 if (IsAccessModifier &&
1361 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1362 Indent += Style.AccessModifierOffset;
1363 if (!InPPDirective || Tok.HasUnescapedNewline) {
1364 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1365 } else {
1366 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1367 SourceMgr, Replaces);
1368 }
1369 return Indent;
1370 }
1371
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001372 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001373 FormatStyle Style;
1374 Lexer &Lex;
1375 SourceManager &SourceMgr;
1376 tooling::Replacements Replaces;
1377 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001378 std::vector<UnwrappedLine> UnwrappedLines;
1379 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001380};
1381
1382tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1383 SourceManager &SourceMgr,
1384 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001385 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1386 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1387 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1388 DiagnosticsEngine Diagnostics(
1389 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1390 &DiagnosticPrinter, false);
1391 Diagnostics.setSourceManager(&SourceMgr);
1392 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001393 return formatter.format();
1394}
1395
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001396LangOptions getFormattingLangOpts() {
1397 LangOptions LangOpts;
1398 LangOpts.CPlusPlus = 1;
1399 LangOpts.CPlusPlus11 = 1;
1400 LangOpts.Bool = 1;
1401 LangOpts.ObjC1 = 1;
1402 LangOpts.ObjC2 = 1;
1403 return LangOpts;
1404}
1405
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001406} // namespace format
1407} // namespace clang