blob: d2ea7ec3012ba4f840ac3bca4a22b3086e9cdfcf [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,
Daniel Jasper7194e182013-01-10 11:14:08 +000040 TT_ObjCMethodSpecifier,
41 TT_OverloadedOperator,
42 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000043 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_TemplateCloser,
45 TT_TemplateOpener,
46 TT_TrailingUnaryOperator,
47 TT_UnaryOperator,
48 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000049};
50
51enum LineType {
52 LT_Invalid,
53 LT_Other,
54 LT_PreprocessorDirective,
55 LT_VirtualFunctionDecl,
56 LT_ObjCMethodDecl
57};
58
Daniel Jasper7c85fde2013-01-08 14:56:18 +000059class AnnotatedToken {
60public:
61 AnnotatedToken(const FormatToken &FormatTok)
62 : FormatTok(FormatTok), Type(TT_Unknown),
63 ClosesTemplateDeclaration(false), Parent(NULL) {
64 }
65
66 bool is(tok::TokenKind Kind) const {
67 return FormatTok.Tok.is(Kind);
68 }
69 bool isNot(tok::TokenKind Kind) const {
70 return FormatTok.Tok.isNot(Kind);
71 }
72 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
73 return FormatTok.Tok.isObjCAtKeyword(Kind);
74 }
75
76 FormatToken FormatTok;
77
Daniel Jasperf7935112012-12-03 18:12:45 +000078 TokenType Type;
79
Daniel Jasperf7935112012-12-03 18:12:45 +000080 bool SpaceRequiredBefore;
81 bool CanBreakBefore;
82 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000083
84 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000085
86 std::vector<AnnotatedToken> Children;
87 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000088};
89
Daniel Jasper7c85fde2013-01-08 14:56:18 +000090static prec::Level getPrecedence(const AnnotatedToken &Tok) {
91 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000092}
93
Daniel Jasperf7935112012-12-03 18:12:45 +000094using llvm::MutableArrayRef;
95
96FormatStyle getLLVMStyle() {
97 FormatStyle LLVMStyle;
98 LLVMStyle.ColumnLimit = 80;
99 LLVMStyle.MaxEmptyLinesToKeep = 1;
100 LLVMStyle.PointerAndReferenceBindToType = false;
101 LLVMStyle.AccessModifierOffset = -2;
102 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000103 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000104 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 return LLVMStyle;
106}
107
108FormatStyle getGoogleStyle() {
109 FormatStyle GoogleStyle;
110 GoogleStyle.ColumnLimit = 80;
111 GoogleStyle.MaxEmptyLinesToKeep = 1;
112 GoogleStyle.PointerAndReferenceBindToType = true;
113 GoogleStyle.AccessModifierOffset = -1;
114 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000115 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000116 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000117 return GoogleStyle;
118}
119
120struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000121 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000122 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000123 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000124};
125
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000126/// \brief Replaces the whitespace in front of \p Tok. Only call once for
127/// each \c FormatToken.
128static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
129 unsigned Spaces, const FormatStyle &Style,
130 SourceManager &SourceMgr,
131 tooling::Replacements &Replaces) {
132 Replaces.insert(tooling::Replacement(
133 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
134 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
135}
136
137/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
138/// backslashes to escape newlines inside a preprocessor directive.
139///
140/// This function and \c replaceWhitespace have the same behavior if
141/// \c Newlines == 0.
142static void replacePPWhitespace(
143 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
144 unsigned WhitespaceStartColumn, const FormatStyle &Style,
145 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
146 std::string NewLineText;
147 if (NewLines > 0) {
148 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
149 WhitespaceStartColumn);
150 for (unsigned i = 0; i < NewLines; ++i) {
151 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
152 NewLineText += "\\\n";
153 Offset = 0;
154 }
155 }
156 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
157 Tok.FormatTok.WhiteSpaceLength,
158 NewLineText + std::string(Spaces, ' ')));
159}
160
Daniel Jasperf7935112012-12-03 18:12:45 +0000161class UnwrappedLineFormatter {
162public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000163 UnwrappedLineFormatter(
164 const FormatStyle &Style, SourceManager &SourceMgr,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000165 const UnwrappedLine &Line, unsigned FirstIndent,
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000166 LineType CurrentLineType, const AnnotatedToken &RootToken,
167 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000168 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000169 FirstIndent(FirstIndent),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000170 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000171 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000172 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000173 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000174 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 }
176
Manuel Klimek1abf7892013-01-04 23:34:14 +0000177 /// \brief Formats an \c UnwrappedLine.
178 ///
179 /// \returns The column after the last token in the last line of the
180 /// \c UnwrappedLine.
181 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000182 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000183 IndentState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000184 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000185 State.NextToken = &RootToken;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000186 State.Indent.push_back(FirstIndent + 4);
187 State.LastSpace.push_back(FirstIndent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000188 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000189 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000190 State.ForLoopVariablePos = 0;
191 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000192 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000193
194 // The first token has already been indented and thus consumed.
195 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000196
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000197 // Check whether the UnwrappedLine can be put onto a single line. If so,
198 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasperc0880a92013-01-04 18:52:56 +0000199 // need to analyze the entire solution space.
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000200 unsigned Columns = State.Column;
201 bool FitsOnALine = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000202 const AnnotatedToken *Tok = State.NextToken;
203 while (Tok != NULL) {
204 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
205 Tok->FormatTok.TokenLength;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000206 // A special case for the colon of a constructor initializer as this only
207 // needs to be put on a new line if the line needs to be split.
Manuel Klimek38ba11e2013-01-07 09:24:17 +0000208 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000209 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000210 FitsOnALine = false;
211 break;
212 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000213 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000214 }
215
Daniel Jasperf7935112012-12-03 18:12:45 +0000216 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000217 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000218 if (FitsOnALine) {
219 addTokenToState(false, false, State);
220 } else {
221 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
222 unsigned Break = calcPenalty(State, true, NoBreak);
223 addTokenToState(Break < NoBreak, false, State);
224 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000225 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000226 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000227 }
228
229private:
230 /// \brief The current state when indenting a unwrapped line.
231 ///
232 /// As the indenting tries different combinations this is copied by value.
233 struct IndentState {
234 /// \brief The number of used columns in the current line.
235 unsigned Column;
236
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000237 const AnnotatedToken *NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000238
Daniel Jasper6d822722012-12-24 16:43:00 +0000239 /// \brief The parenthesis level of the first token on the current line.
240 unsigned StartOfLineLevel;
241
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 /// \brief The position to which a specific parenthesis level needs to be
243 /// indented.
244 std::vector<unsigned> Indent;
245
Daniel Jaspere9de2602012-12-06 09:56:08 +0000246 /// \brief The position of the last space on each level.
247 ///
248 /// Used e.g. to break like:
249 /// functionCall(Parameter, otherCall(
250 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000251 std::vector<unsigned> LastSpace;
252
Daniel Jaspere9de2602012-12-06 09:56:08 +0000253 /// \brief The position the first "<<" operator encountered on each level.
254 ///
255 /// Used to align "<<" operators. 0 if no such operator has been encountered
256 /// on a level.
257 std::vector<unsigned> FirstLessLess;
258
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000259 /// \brief Whether a newline needs to be inserted before the block's closing
260 /// brace.
261 ///
262 /// We only want to insert a newline before the closing brace if there also
263 /// was a newline after the beginning left brace.
264 std::vector<bool> BreakBeforeClosingBrace;
265
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000266 /// \brief The column of the first variable in a for-loop declaration.
267 ///
268 /// Used to align the second variable if necessary.
269 unsigned ForLoopVariablePos;
270
271 /// \brief \c true if this line contains a continued for-loop section.
272 bool LineContainsContinuedForLoopSection;
273
Daniel Jasperf7935112012-12-03 18:12:45 +0000274 /// \brief Comparison operator to be able to used \c IndentState in \c map.
275 bool operator<(const IndentState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000276 if (Other.NextToken != NextToken)
277 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000278 if (Other.Column != Column)
279 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000280 if (Other.StartOfLineLevel != StartOfLineLevel)
281 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000282 if (Other.Indent.size() != Indent.size())
283 return Other.Indent.size() > Indent.size();
284 for (int i = 0, e = Indent.size(); i != e; ++i) {
285 if (Other.Indent[i] != Indent[i])
286 return Other.Indent[i] > Indent[i];
287 }
288 if (Other.LastSpace.size() != LastSpace.size())
289 return Other.LastSpace.size() > LastSpace.size();
290 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
291 if (Other.LastSpace[i] != LastSpace[i])
292 return Other.LastSpace[i] > LastSpace[i];
293 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294 if (Other.FirstLessLess.size() != FirstLessLess.size())
295 return Other.FirstLessLess.size() > FirstLessLess.size();
296 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
297 if (Other.FirstLessLess[i] != FirstLessLess[i])
298 return Other.FirstLessLess[i] > FirstLessLess[i];
299 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000300 if (Other.ForLoopVariablePos != ForLoopVariablePos)
301 return Other.ForLoopVariablePos < ForLoopVariablePos;
302 if (Other.LineContainsContinuedForLoopSection !=
303 LineContainsContinuedForLoopSection)
304 return LineContainsContinuedForLoopSection;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000305 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
306 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000307 return false;
308 }
309 };
310
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000311 /// \brief Appends the next token to \p State and updates information
312 /// necessary for indentation.
313 ///
314 /// Puts the token on the current line if \p Newline is \c true and adds a
315 /// line break and necessary indentation otherwise.
316 ///
317 /// If \p DryRun is \c false, also creates and stores the required
318 /// \c Replacement.
319 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000320 const AnnotatedToken &Current = *State.NextToken;
321 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weber51306d22013-01-10 00:25:19 +0000322 assert(State.Indent.size());
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000323 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000324
325 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000326 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000327 if (Current.is(tok::r_brace)) {
328 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000329 } else if (Current.is(tok::string_literal) &&
330 Previous.is(tok::string_literal)) {
331 State.Column = State.Column - Previous.FormatTok.TokenLength;
332 } else if (Current.is(tok::lessless) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000333 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000334 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000335 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000336 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
337 Current.is(tok::period) || Previous.is(tok::question) ||
338 Previous.Type == TT_ConditionalExpr)) {
339 // Indent and extra 4 spaces after if we know the current expression is
340 // continued. Don't do that on the top level, as we already indent 4
341 // there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000342 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000343 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000344 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000345 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000346 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000347 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000348 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000349 }
350
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000351 // A line starting with a closing brace is assumed to be correct for the
352 // same level as before the opening brace.
353 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000354
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000355 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000356 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000357
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000358 if (!DryRun) {
359 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000360 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
361 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000362 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000363 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000364 WhitespaceStartColumn, Style, SourceMgr,
365 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000366 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000367
Daniel Jasper89058942013-01-09 09:50:48 +0000368 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000369 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000370 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000371 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000373 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
374 State.ForLoopVariablePos = State.Column -
375 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000376
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000377 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
378 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000379 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000380
Daniel Jasperf7935112012-12-03 18:12:45 +0000381 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000382 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000383
Daniel Jasperbcab4302013-01-09 10:40:23 +0000384 // FIXME: Do we need to do this for assignments nested in other
385 // expressions?
386 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000387 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000388 Previous.is(tok::kw_return)))
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000389 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000390 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000391 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000392 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000393 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000394
Daniel Jasper206df732013-01-07 13:08:40 +0000395 // Top-level spaces that are not part of assignments are exempt as that
396 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000397 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000398 if (Spaces > 0 &&
399 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000400 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000401 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000402 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000403 if (Newline && Previous.is(tok::l_brace)) {
404 State.BreakBeforeClosingBrace.back() = true;
405 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000406 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000407
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000408 /// \brief Mark the next token as consumed in \p State and modify its stacks
409 /// accordingly.
410 void moveStateToNextToken(IndentState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000411 const AnnotatedToken &Current = *State.NextToken;
Nico Weber51306d22013-01-10 00:25:19 +0000412 assert(State.Indent.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000413 unsigned ParenLevel = State.Indent.size() - 1;
414
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000415 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000416 State.FirstLessLess[ParenLevel] = State.Column;
417
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000418 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000419 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000420 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
421 Current.is(tok::l_brace) ||
422 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000423 if (Current.is(tok::l_brace)) {
424 // FIXME: This does not work with nested static initializers.
425 // Implement a better handling for static initializers and similar
426 // constructs.
427 State.Indent.push_back(Line.Level * 2 + 2);
428 } else {
429 State.Indent.push_back(4 + State.LastSpace.back());
430 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000431 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000432 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000433 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000434 }
435
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000436 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000437 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000438 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
439 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
440 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000441 State.Indent.pop_back();
442 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000443 State.FirstLessLess.pop_back();
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000444 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000445 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000446
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000447 if (State.NextToken->Children.empty())
448 State.NextToken = NULL;
449 else
450 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000451
452 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000453 }
454
Nico Weber49cbc2c2013-01-07 15:15:29 +0000455 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000456 unsigned splitPenalty(const AnnotatedToken &Tok) {
457 const AnnotatedToken &Left = Tok;
458 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000459
460 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000461 if (RootToken.is(tok::kw_for) &&
462 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000463 return 20;
464
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000465 if (Left.is(tok::semi) || Left.is(tok::comma) ||
466 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000467 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000468 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000469 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000470
Daniel Jasper399d24b2013-01-09 07:06:56 +0000471 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
472 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000473 prec::Level Level = getPrecedence(Left);
474
475 // Breaking after an assignment leads to a bad result as the two sides of
476 // the assignment are visually very close together.
477 if (Level == prec::Assignment)
478 return 50;
479
Daniel Jasperde5c2072012-12-24 00:13:23 +0000480 if (Level != prec::Unknown)
481 return Level;
482
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000483 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000484 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000485
Daniel Jasperf7935112012-12-03 18:12:45 +0000486 return 3;
487 }
488
Daniel Jasper2df93312013-01-09 10:16:05 +0000489 unsigned getColumnLimit() {
490 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
491 }
492
Daniel Jasperf7935112012-12-03 18:12:45 +0000493 /// \brief Calculate the number of lines needed to format the remaining part
494 /// of the unwrapped line.
495 ///
496 /// Assumes the formatting so far has led to
497 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
498 /// added after the previous token.
499 ///
500 /// \param StopAt is used for optimization. If we can determine that we'll
501 /// definitely need at least \p StopAt additional lines, we already know of a
502 /// better solution.
503 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
504 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000505 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 return 0;
507
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000508 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000509 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000510 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000511 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000512 if (!NewLine && State.NextToken->is(tok::r_brace) &&
513 State.BreakBeforeClosingBrace.back())
514 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000515 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000516 State.LineContainsContinuedForLoopSection)
517 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000518
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000519 unsigned CurrentPenalty = 0;
520 if (NewLine) {
521 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000522 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000523 } else {
524 if (State.Indent.size() < State.StartOfLineLevel)
525 CurrentPenalty += Parameters.PenaltyLevelDecrease *
526 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000527 }
528
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000529 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000530
Daniel Jasper2df93312013-01-09 10:16:05 +0000531 // Exceeding column limit is bad, assign penalty.
532 if (State.Column > getColumnLimit()) {
533 unsigned ExcessCharacters = State.Column - getColumnLimit();
534 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
535 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000536
Daniel Jasperf7935112012-12-03 18:12:45 +0000537 if (StopAt <= CurrentPenalty)
538 return UINT_MAX;
539 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000540 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000541 if (I != Memory.end()) {
542 // If this state has already been examined, we can safely return the
543 // previous result if we
544 // - have not hit the optimatization (and thus returned UINT_MAX) OR
545 // - are now computing for a smaller or equal StopAt.
546 unsigned SavedResult = I->second.first;
547 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000548 if (SavedResult != UINT_MAX)
549 return SavedResult + CurrentPenalty;
550 else if (StopAt <= SavedStopAt)
551 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000552 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000553
554 unsigned NoBreak = calcPenalty(State, false, StopAt);
555 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
556 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000557
558 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
559 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000560 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000561
562 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000563 }
564
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 FormatStyle Style;
566 SourceManager &SourceMgr;
567 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000568 const unsigned FirstIndent;
Daniel Jasperda16db32013-01-07 10:48:50 +0000569 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000570 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000571 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000572
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000573 // A map from an indent state to a pair (Result, Used-StopAt).
574 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
575 StateMap Memory;
576
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 OptimizationParameters Parameters;
578};
579
580/// \brief Determines extra information about the tokens comprising an
581/// \c UnwrappedLine.
582class TokenAnnotator {
583public:
584 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000585 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000586 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
587 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000588 }
589
590 /// \brief A parser that gathers additional information about tokens.
591 ///
592 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
593 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
594 /// into template parameter lists.
595 class AnnotatingParser {
596 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000597 AnnotatingParser(AnnotatedToken &RootToken)
598 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 }
600
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000601 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 while (CurrentToken != NULL) {
603 if (CurrentToken->is(tok::greater)) {
604 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000605 next();
606 return true;
607 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000608 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
609 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000611 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
612 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000613 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000614 if (!consumeToken())
615 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000616 }
617 return false;
618 }
619
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000620 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000621 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
622 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000623 while (CurrentToken != NULL) {
624 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000625 next();
626 return true;
627 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000630 if (!consumeToken())
631 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000632 }
633 return false;
634 }
635
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000636 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000637 while (CurrentToken != NULL) {
638 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000639 next();
640 return true;
641 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000642 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000643 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000644 if (!consumeToken())
645 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 }
647 return false;
648 }
649
Daniel Jasper83a54d22013-01-10 09:26:47 +0000650 bool parseBrace() {
651 while (CurrentToken != NULL) {
652 if (CurrentToken->is(tok::r_brace)) {
653 next();
654 return true;
655 }
656 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
657 return false;
658 if (!consumeToken())
659 return false;
660 }
661 // Lines can currently end with '{'.
662 return true;
663 }
664
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000665 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000666 while (CurrentToken != NULL) {
667 if (CurrentToken->is(tok::colon)) {
668 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 next();
670 return true;
671 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000672 if (!consumeToken())
673 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000674 }
675 return false;
676 }
677
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000678 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000679 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
680 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000681 next();
682 if (!parseAngle())
683 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000684 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000685 parseLine();
686 return true;
687 }
688 return false;
689 }
690
Daniel Jasperc0880a92013-01-04 18:52:56 +0000691 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000692 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000693 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000694 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000695 case tok::l_paren:
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();
701 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000702 break;
703 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000704 if (!parseSquare())
705 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000707 case tok::l_brace:
708 if (!parseBrace())
709 return false;
710 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000711 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000712 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000713 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000715 Tok->Type = TT_BinaryOperator;
716 CurrentToken = Tok;
717 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000718 }
719 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000720 case tok::r_paren:
721 case tok::r_square:
722 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000723 case tok::r_brace:
724 // Lines can start with '}'.
725 if (Tok->Parent != NULL)
726 return false;
727 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000728 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000729 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000730 break;
731 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000732 if (CurrentToken->is(tok::l_paren)) {
733 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000734 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000735 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
736 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000737 next();
738 }
739 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000740 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
741 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000742 next();
743 }
744 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 break;
746 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000747 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000748 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000749 case tok::kw_template:
750 parseTemplateDeclaration();
751 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000752 default:
753 break;
754 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000755 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000756 }
757
Daniel Jasper050948a52012-12-21 17:58:39 +0000758 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000759 while (CurrentToken != NULL) {
760 if (CurrentToken->is(tok::slash))
761 CurrentToken->Type = TT_DirectorySeparator;
762 else if (CurrentToken->is(tok::less))
763 CurrentToken->Type = TT_TemplateOpener;
764 else if (CurrentToken->is(tok::greater))
765 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000766 next();
767 }
768 }
769
770 void parsePreprocessorDirective() {
771 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000773 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000774 // Hashes in the middle of a line can lead to any strange token
775 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000777 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000778 switch (
779 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000780 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000781 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000782 parseIncludeDirective();
783 break;
784 default:
785 break;
786 }
787 }
788
Daniel Jasperda16db32013-01-07 10:48:50 +0000789 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000790 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000791 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000792 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000793 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000794 while (CurrentToken != NULL) {
795 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000796 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000797 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000798 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000799 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000800 if (KeywordVirtualFound)
801 return LT_VirtualFunctionDecl;
802 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 }
804
805 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000806 if (CurrentToken != NULL && !CurrentToken->Children.empty())
807 CurrentToken = &CurrentToken->Children[0];
808 else
809 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 }
811
812 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000813 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000814 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000815 };
816
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000817 void createAnnotatedTokens(AnnotatedToken &Current) {
818 if (!Current.FormatTok.Children.empty()) {
819 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
820 Current.Children.back().Parent = &Current;
821 createAnnotatedTokens(Current.Children.back());
822 }
823 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000824
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000825 void calculateExtraInformation(AnnotatedToken &Current) {
826 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
827
Manuel Klimek52b15152013-01-09 15:25:02 +0000828 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000829 Current.MustBreakBefore = true;
830 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000831 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
832 TT_LineComment || (Current.is(tok::string_literal) &&
833 Current.Parent->is(tok::string_literal))) {
834 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000835 } else {
836 Current.MustBreakBefore = false;
837 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000840 if (!Current.Children.empty())
841 calculateExtraInformation(Current.Children[0]);
842 }
843
844 bool annotate() {
845 createAnnotatedTokens(RootToken);
846
847 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000848 CurrentLineType = Parser.parseLine();
849 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000850 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000851
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000852 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000853
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000854 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000855 CurrentLineType = LT_ObjCMethodDecl;
856
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000857 if (!RootToken.Children.empty())
858 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000859 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 }
861
Daniel Jasperda16db32013-01-07 10:48:50 +0000862 LineType getLineType() {
863 return CurrentLineType;
864 }
865
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000866 const AnnotatedToken &getRootToken() {
867 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000868 }
869
870private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000871 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
872 if (getPrecedence(Current) == prec::Assignment ||
873 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
874 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000875
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 if (Current.Type == TT_Unknown) {
877 if (Current.is(tok::star) || Current.is(tok::amp)) {
878 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000879 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
880 Current.is(tok::caret)) {
881 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000882 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
883 Current.Type = determineIncrementUsage(Current);
884 } else if (Current.is(tok::exclaim)) {
885 Current.Type = TT_UnaryOperator;
886 } else if (isBinaryOperator(Current)) {
887 Current.Type = TT_BinaryOperator;
888 } else if (Current.is(tok::comment)) {
889 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
890 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000891 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000892 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000893 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000894 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000895 } else if (Current.is(tok::r_paren) &&
896 (Current.Parent->Type == TT_PointerOrReference ||
897 Current.Parent->Type == TT_TemplateCloser)) {
898 // FIXME: We need to get smarter and understand more cases of casts.
899 Current.Type = TT_CastRParen;
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 }
901 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902
903 if (!Current.Children.empty())
904 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000905 }
906
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000907 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000908 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000909 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000910 }
911
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000912 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
913 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000914 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000916 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 const FormatToken &PrevToken = Tok.Parent->FormatTok;
918 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000919
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000920 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
921 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000922 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
923 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000924 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000925
Daniel Jasper542de162013-01-02 15:46:59 +0000926 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000927 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
928 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
929 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
930 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000931 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000932
Daniel Jasper542de162013-01-02 15:46:59 +0000933 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
934 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000935 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000936
Daniel Jasper426702d2012-12-05 07:51:39 +0000937 // It is very unlikely that we are going to find a pointer or reference type
938 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000939 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000940 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000941
Daniel Jasperda16db32013-01-07 10:48:50 +0000942 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000943 }
944
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000945 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000946 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000947 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000948 return TT_ObjCMethodSpecifier;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000949
950 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000951 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
952 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
953 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
954 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case))
Daniel Jasperda16db32013-01-07 10:48:50 +0000955 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000956
957 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000958 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +0000959 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000960
961 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000962 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000963 }
964
965 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000966 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
967 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +0000968 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000969
Daniel Jasperda16db32013-01-07 10:48:50 +0000970 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000971 }
972
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000973 bool spaceRequiredBetween(const AnnotatedToken &Left,
974 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +0000975 if (Right.is(tok::hashhash))
976 return Left.is(tok::hash);
977 if (Left.is(tok::hashhash) || Left.is(tok::hash))
978 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +0000979 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
980 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 if (Left.is(tok::kw_template) && Right.is(tok::less))
982 return true;
983 if (Left.is(tok::arrow) || Right.is(tok::arrow))
984 return false;
985 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
986 return false;
Nico Weber77aa2502013-01-08 19:40:21 +0000987 if (Left.is(tok::at) &&
988 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
989 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000990 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
991 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000992 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000993 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
994 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000995 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000996 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000997 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
998 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001000 return Right.FormatTok.Tok.isLiteral() ||
1001 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001002 if (Right.is(tok::star) && Left.is(tok::l_paren))
1003 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001004 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1005 Right.is(tok::r_square))
1006 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001007 if (Left.is(tok::coloncolon) ||
1008 (Right.is(tok::coloncolon) &&
1009 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001010 return false;
1011 if (Left.is(tok::period) || Right.is(tok::period))
1012 return false;
1013 if (Left.is(tok::colon) || Right.is(tok::colon))
1014 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001015 if (Left.is(tok::l_paren))
1016 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001018 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001019 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001020 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001022 if (Left.is(tok::at) &&
1023 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001024 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001025 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1026 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001027 return true;
1028 }
1029
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001030 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001031 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001032 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1033 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001034 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001035 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001036 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001037 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001038 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001039 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001040 // Don't space between ')' and <id>
1041 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001042 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001043 // Don't space between ':' and '('
1044 return false;
1045 }
1046
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001047 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001048 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001049 if (Tok.Type == TT_OverloadedOperator)
1050 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001051 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001052 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001053 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 if (Tok.is(tok::colon))
1055 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001056 if (Tok.Parent->Type == TT_UnaryOperator ||
1057 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001058 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001059 if (Tok.Type == TT_UnaryOperator)
1060 return Tok.Parent->isNot(tok::l_paren) &&
1061 Tok.Parent->isNot(tok::l_square);
1062 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1063 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001064 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1065 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001066 if (Tok.Type == TT_DirectorySeparator ||
1067 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001068 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001069 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001070 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001071 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001072 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001073 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001074 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001075 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001076 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001078 }
1079
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001080 bool canBreakBefore(const AnnotatedToken &Right) {
1081 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001082 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001083 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1084 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001085 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001086 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1087 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001088 // Don't break this identifier as ':' or identifier
1089 // before it will break.
1090 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001091 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1092 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001093 // Don't break at ':' if identifier before it can beak.
1094 return false;
1095 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001096 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001097 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001098 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001099 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001100 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001101 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001102 return false;
1103
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001104 if (Right.is(tok::comment))
1105 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001107 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001108 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001109 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1110 Left.is(tok::comma) || Right.is(tok::lessless) ||
1111 Right.is(tok::arrow) || Right.is(tok::period) ||
1112 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001113 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001114 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001115 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001116 }
1117
Daniel Jasperf7935112012-12-03 18:12:45 +00001118 FormatStyle Style;
1119 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001120 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001121 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001123};
1124
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001125class LexerBasedFormatTokenSource : public FormatTokenSource {
1126public:
1127 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001128 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001129 IdentTable(Lex.getLangOpts()) {
1130 Lex.SetKeepWhitespaceMode(true);
1131 }
1132
1133 virtual FormatToken getNextToken() {
1134 if (GreaterStashed) {
1135 FormatTok.NewlinesBefore = 0;
1136 FormatTok.WhiteSpaceStart =
1137 FormatTok.Tok.getLocation().getLocWithOffset(1);
1138 FormatTok.WhiteSpaceLength = 0;
1139 GreaterStashed = false;
1140 return FormatTok;
1141 }
1142
1143 FormatTok = FormatToken();
1144 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001145 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001146 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001147 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1148 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001149
1150 // Consume and record whitespace until we find a significant token.
1151 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001152 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001153 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1154 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001155 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1156
1157 if (FormatTok.Tok.is(tok::eof))
1158 return FormatTok;
1159 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001160 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001161 }
Manuel Klimekef920692013-01-07 07:56:50 +00001162
1163 // Now FormatTok is the next non-whitespace token.
1164 FormatTok.TokenLength = Text.size();
1165
Manuel Klimek1abf7892013-01-04 23:34:14 +00001166 // In case the token starts with escaped newlines, we want to
1167 // take them into account as whitespace - this pattern is quite frequent
1168 // in macro definitions.
1169 // FIXME: What do we want to do with other escaped spaces, and escaped
1170 // spaces or newlines in the middle of tokens?
1171 // FIXME: Add a more explicit test.
1172 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001173 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001174 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001175 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001176 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001177 }
1178
1179 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001180 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001181 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001182 FormatTok.Tok.setKind(Info.getTokenID());
1183 }
1184
1185 if (FormatTok.Tok.is(tok::greatergreater)) {
1186 FormatTok.Tok.setKind(tok::greater);
1187 GreaterStashed = true;
1188 }
1189
1190 return FormatTok;
1191 }
1192
1193private:
1194 FormatToken FormatTok;
1195 bool GreaterStashed;
1196 Lexer &Lex;
1197 SourceManager &SourceMgr;
1198 IdentifierTable IdentTable;
1199
1200 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001201 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001202 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1203 Tok.getLength());
1204 }
1205};
1206
Daniel Jasperf7935112012-12-03 18:12:45 +00001207class Formatter : public UnwrappedLineConsumer {
1208public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001209 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1210 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001211 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001212 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001213 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001214
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001215 virtual ~Formatter() {
1216 }
1217
Daniel Jasperf7935112012-12-03 18:12:45 +00001218 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001219 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001220 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001221 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001222 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001223 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1224 E = UnwrappedLines.end();
1225 I != E; ++I)
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001226 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1227 PreviousEndOfLineColumn);
Daniel Jasperf7935112012-12-03 18:12:45 +00001228 return Replaces;
1229 }
1230
1231private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001232 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001233 UnwrappedLines.push_back(TheLine);
1234 }
1235
Manuel Klimek1abf7892013-01-04 23:34:14 +00001236 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1237 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001238 const FormatToken *First = &TheLine.RootToken;
1239 const FormatToken *Last = First;
1240 while (!Last->Children.empty())
1241 Last = &Last->Children.back();
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001242 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 First->Tok.getLocation(),
1244 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001245
1246 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1247 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1248 Ranges[i].getBegin()) ||
1249 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1250 LineRange.getBegin()))
1251 continue;
1252
Manuel Klimekc74d2922013-01-07 08:54:53 +00001253 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasperc0880a92013-01-04 18:52:56 +00001254 if (!Annotator.annotate())
Manuel Klimek1abf7892013-01-04 23:34:14 +00001255 break;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001256 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1257 TheLine.Level, TheLine.InPPDirective,
1258 PreviousEndOfLineColumn);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001259 UnwrappedLineFormatter Formatter(
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001260 Style, SourceMgr, TheLine, Indent,
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001261 Annotator.getLineType(), Annotator.getRootToken(), Replaces,
Daniel Jasperda16db32013-01-07 10:48:50 +00001262 StructuralError);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001263 return Formatter.format();
Daniel Jasperf7935112012-12-03 18:12:45 +00001264 }
Manuel Klimek1abf7892013-01-04 23:34:14 +00001265 // If we did not reformat this unwrapped line, the column at the end of the
1266 // last token is unchanged - thus, we can calculate the end of the last
1267 // token, and return the result.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001268 return SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1269 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
Manuel Klimek1abf7892013-01-04 23:34:14 +00001270 Lex.getLangOpts()) -
1271 1;
Daniel Jasperf7935112012-12-03 18:12:45 +00001272 }
1273
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001274 /// \brief Add a new line and the required indent before the first Token
1275 /// of the \c UnwrappedLine if there was no structural parsing error.
1276 /// Returns the indent level of the \c UnwrappedLine.
1277 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1278 bool InPPDirective,
1279 unsigned PreviousEndOfLineColumn) {
1280 const FormatToken& Tok = RootToken.FormatTok;
1281 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1282 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1283
1284 unsigned Newlines = std::min(Tok.NewlinesBefore,
1285 Style.MaxEmptyLinesToKeep + 1);
1286 if (Newlines == 0 && !Tok.IsFirst)
1287 Newlines = 1;
1288 unsigned Indent = Level * 2;
1289
1290 bool IsAccessModifier = false;
1291 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1292 RootToken.is(tok::kw_private))
1293 IsAccessModifier = true;
1294 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1295 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1296 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1297 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1298 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1299 IsAccessModifier = true;
1300
1301 if (IsAccessModifier &&
1302 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1303 Indent += Style.AccessModifierOffset;
1304 if (!InPPDirective || Tok.HasUnescapedNewline) {
1305 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1306 } else {
1307 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1308 SourceMgr, Replaces);
1309 }
1310 return Indent;
1311 }
1312
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001313 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001314 FormatStyle Style;
1315 Lexer &Lex;
1316 SourceManager &SourceMgr;
1317 tooling::Replacements Replaces;
1318 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001319 std::vector<UnwrappedLine> UnwrappedLines;
1320 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001321};
1322
1323tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1324 SourceManager &SourceMgr,
1325 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001326 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1327 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1328 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1329 DiagnosticsEngine Diagnostics(
1330 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1331 &DiagnosticPrinter, false);
1332 Diagnostics.setSourceManager(&SourceMgr);
1333 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001334 return formatter.format();
1335}
1336
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001337LangOptions getFormattingLangOpts() {
1338 LangOptions LangOpts;
1339 LangOpts.CPlusPlus = 1;
1340 LangOpts.CPlusPlus11 = 1;
1341 LangOpts.Bool = 1;
1342 LangOpts.ObjC1 = 1;
1343 LangOpts.ObjC2 = 1;
1344 return LangOpts;
1345}
1346
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001347} // namespace format
1348} // namespace clang